Skip to content

Build your personal knowledge base with Trilium Notes

test(client): first batch of tests

Elian Doran937a13f5ea48
diff --git a/apps/client/src/services/attribute_autocomplete.spec.ts b/apps/client/src/services/attribute_autocomplete.spec.ts
new file mode 100644
index 0000000000..39ff928844
--- /dev/null
+++ b/apps/client/src/services/attribute_autocomplete.spec.ts
@@ -0,0 +1,195 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import $ from "jquery";
+
+import server from "./server.js";
+import attributeAutocomplete from "./attribute_autocomplete.js";
+
+type Dataset = {
+ displayKey: string;
+ cache: boolean;
+ source: (term: string, cb: (rows: object[]) => void) => void | Promise<void>;
+};
+
+// Captures the most recent `$el.autocomplete(config, datasets)` init call so tests
+// can invoke the registered `source` callback directly and exercise its body.
+let lastDatasets: Dataset[] | undefined;
+let autocompleteSpy: ReturnType<typeof vi.fn>;
+
+function registerAutocompleteStub() {
+ lastDatasets = undefined;
+ autocompleteSpy = vi.fn(function (this: JQuery, config: object | string, datasets?: Dataset[]) {
+ if (typeof config === "object" && Array.isArray(datasets)) {
+ lastDatasets = datasets;
+ }
+ return this;
+ });
+ ($.fn as any).autocomplete = autocompleteSpy;
+}
+
+function makeEl(extraClass = "") {
+ return $(`<input class="${extraClass}" />`);
+}
+
+describe("attribute_autocomplete", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ registerAutocompleteStub();
+ });
+
+ describe("initAttributeNameAutocomplete", () => {
+ it("initializes autocomplete, wires the name source and the readonly opened handler", async () => {
+ const $el = makeEl();
+ server.get = vi.fn(async () => ["foo", "bar"]) as typeof server.get;
+
+ attributeAutocomplete.initAttributeNameAutocomplete({
+ $el,
+ attributeType: "label",
+ open: true
+ });
+
+ // init form (config + datasets) followed by the "open" command.
+ expect(autocompleteSpy).toHaveBeenCalledWith(
+ expect.objectContaining({ openOnFocus: true, minLength: 0 }),
+ expect.any(Array)
+ );
+ expect(autocompleteSpy).toHaveBeenCalledWith("open");
+ expect(lastDatasets?.[0].displayKey).toBe("name");
+ expect(lastDatasets?.[0].cache).toBe(false);
+
+ // Exercise the source callback with a static attributeType.
+ const cb = vi.fn();
+ await lastDatasets![0].source("co lor", cb);
+ expect(server.get).toHaveBeenCalledWith("attribute-names/?type=label&query=co%20lor");
+ expect(cb).toHaveBeenCalledWith([{ name: "foo" }, { name: "bar" }]);
+
+ // readonly element -> opened handler closes the autocomplete.
+ $el.attr("readonly", "readonly");
+ $el.trigger("autocomplete:opened");
+ expect(autocompleteSpy).toHaveBeenCalledWith("close");
+ });
+
+ it("resolves a function attributeType and does not close when not readonly; skips open when open=false", async () => {
+ const $el = makeEl();
+ server.get = vi.fn(async () => ["x"]) as typeof server.get;
+
+ attributeAutocomplete.initAttributeNameAutocomplete({
+ $el,
+ attributeType: () => "relation",
+ open: false
+ });
+
+ // open=false -> the "open" command is never issued.
+ expect(autocompleteSpy).not.toHaveBeenCalledWith("open");
+
+ const cb = vi.fn();
+ await lastDatasets![0].source("q", cb);
+ expect(server.get).toHaveBeenCalledWith("attribute-names/?type=relation&query=q");
+
+ // not readonly -> opened handler does NOT close.
+ $el.trigger("autocomplete:opened");
+ expect(autocompleteSpy).not.toHaveBeenCalledWith("close");
+ });
+
+ it("skips re-initialization when the element already has the aa-input class", () => {
+ const $el = makeEl("aa-input");
+
+ attributeAutocomplete.initAttributeNameAutocomplete({
+ $el,
+ attributeType: "label",
+ open: false
+ });
+
+ // Already initialized -> no init call (config+datasets) was made.
+ expect(lastDatasets).toBeUndefined();
+ expect(autocompleteSpy).not.toHaveBeenCalled();
+ });
+ });
+
+ describe("initLabelValueAutocomplete", () => {
+ it("returns early without a nameCallback (empty attribute name)", async () => {
+ const $el = makeEl();
+ server.get = vi.fn(async () => ["v"]) as typeof server.get;
+
+ await attributeAutocomplete.initLabelValueAutocomplete({ $el, open: true });
+
+ expect(server.get).not.toHaveBeenCalled();
+ expect(autocompleteSpy).not.toHaveBeenCalled();
+ });
+
+ it("returns early when the nameCallback yields a blank name", async () => {
+ const $el = makeEl();
+ server.get = vi.fn(async () => ["v"]) as typeof server.get;
+
+ await attributeAutocomplete.initLabelValueAutocomplete({
+ $el,
+ open: true,
+ nameCallback: () => " "
+ });
+
+ expect(server.get).not.toHaveBeenCalled();
+ });
+
+ it("returns early when no attribute values are returned", async () => {
+ const $el = makeEl();
+ server.get = vi.fn(async () => []) as typeof server.get;
+
+ await attributeAutocomplete.initLabelValueAutocomplete({
+ $el,
+ open: true,
+ nameCallback: () => "color"
+ });
+
+ expect(server.get).toHaveBeenCalledWith("attribute-values/color");
+ expect(autocompleteSpy).not.toHaveBeenCalledWith(expect.any(Object), expect.any(Array));
+ });
+
+ it("destroys an existing instance, inits the value source, filters case-insensitively and closes on readonly", async () => {
+ const $el = makeEl("aa-input");
+ server.get = vi.fn(async () => ["Apple", "Banana", "Cherry"]) as typeof server.get;
+
+ await attributeAutocomplete.initLabelValueAutocomplete({
+ $el,
+ open: true,
+ nameCallback: () => "my color"
+ });
+
+ // aa-input present -> destroy was called before re-init.
+ expect(autocompleteSpy).toHaveBeenCalledWith("destroy");
+ expect(server.get).toHaveBeenCalledWith("attribute-values/my%20color");
+ expect(autocompleteSpy).toHaveBeenCalledWith(
+ expect.objectContaining({ openOnFocus: false }),
+ expect.any(Array)
+ );
+ expect(autocompleteSpy).toHaveBeenCalledWith("open");
+ expect(lastDatasets?.[0].displayKey).toBe("value");
+
+ // source filters by lower-cased substring ("AN" -> "an" matches only "Banana").
+ const cb = vi.fn();
+ await lastDatasets![0].source("AN", cb);
+ expect(cb).toHaveBeenCalledWith([{ value: "Banana" }]);
+
+ // readonly -> opened handler closes.
+ $el.attr("readonly", "readonly");
+ $el.trigger("autocomplete:opened");
+ expect(autocompleteSpy).toHaveBeenCalledWith("close");
+ });
+
+ it("does not destroy when not aa-input, does not open when open=false, and keeps the dropdown open when not readonly", async () => {
+ const $el = makeEl();
+ server.get = vi.fn(async () => ["a"]) as typeof server.get;
+
+ await attributeAutocomplete.initLabelValueAutocomplete({
+ $el,
+ open: false,
+ nameCallback: () => "tag"
+ });
+
+ expect(autocompleteSpy).not.toHaveBeenCalledWith("destroy");
+ expect(autocompleteSpy).not.toHaveBeenCalledWith("open");
+
+ // not readonly -> opened handler does not close.
+ $el.trigger("autocomplete:opened");
+ expect(autocompleteSpy).not.toHaveBeenCalledWith("close");
+ });
+ });
+});
diff --git a/apps/client/src/services/attribute_parser.spec.ts b/apps/client/src/services/attribute_parser.spec.ts
index b63081961a..730188101b 100644
--- a/apps/client/src/services/attribute_parser.spec.ts
+++ b/apps/client/src/services/attribute_parser.spec.ts
@@ -37,23 +37,62 @@ describe("Lexing", () => {
expect(attributeParser.lex("#`label a` = `hello'\" world`").map((t: any) => t.text)).toEqual(["#label a", "=", "hello'\" world"]);
});
-});
-describe.todo("Parser", () => {
- /* #TODO
- it("simple label", () => {
+ it("returns no tokens for an empty / whitespace-only string", () => {
+ expect(attributeParser.lex("")).toEqual([]);
+ expect(attributeParser.lex(" ")).toEqual([]);
+ });
+
+ it("escapes the next character with a backslash", () => {
+ // backslash before a space keeps it inside the word instead of finishing it
+ expect(attributeParser.lex("#a\\ b").map((t: any) => t.text)).toEqual(["#a b"]);
+ // backslash before a quote keeps the quote as a literal character
+ expect(attributeParser.lex('#a\\"b').map((t: any) => t.text)).toEqual(['#a"b']);
+ });
+
+ it("keeps a trailing backslash literally when it is the last character", () => {
+ expect(attributeParser.lex("#a\\").map((t: any) => t.text)).toEqual(["#a\\"]);
+ });
+
+ it("opens quotes directly after an operator symbol, finishing the operator first", () => {
+ // the `=` is finished as its own token before the quoted value opens
+ expect(attributeParser.lex("#a=\"b c\"").map((t: any) => t.text)).toEqual(["#a", "=", "b c"]);
+ });
+
+ it("treats parentheses as standalone tokens around a word", () => {
+ expect(attributeParser.lex("#a(inheritable)").map((t: any) => t.text)).toEqual(["#a", "(", "inheritable", ")"]);
+ // a lone parenthesis with no preceding word still becomes its own token
+ expect(attributeParser.lex("()").map((t: any) => t.text)).toEqual(["(", ")"]);
+ });
+
+ it("splits operator symbols from adjacent non-operator characters", () => {
+ // operator run is its own token, separate from the value
+ expect(attributeParser.lex("#a>=b").map((t: any) => t.text)).toEqual(["#a", ">=", "b"]);
+ // leading operator (no preceding word, currentWord empty) starts a fresh operator token
+ expect(attributeParser.lex("=b").map((t: any) => t.text)).toEqual(["=", "b"]);
+ });
- const attrs = attributeParser.parse(["#token"].map((t: any) => ({ text: t })));
+ it("only treats # / ~ as a prefix at the start of a word", () => {
+ // a # in the middle of a word is a literal character, not a new attribute marker
+ expect(attributeParser.lex("#a#b").map((t: any) => t.text)).toEqual(["#a#b"]);
+ });
+});
+
+describe("Parser", () => {
+ it("parses a simple label without value or inheritance", () => {
+ const attrs = attributeParser.lexAndParse("#token");
expect(attrs.length).toEqual(1);
expect(attrs[0].type).toEqual("label");
expect(attrs[0].name).toEqual("token");
expect(attrs[0].isInheritable).toBeFalsy();
expect(attrs[0].value).toBeFalsy();
+ expect(attrs[0].startIndex).toEqual(0);
+ expect(attrs[0].endIndex).toEqual(5);
});
- it("inherited label", () => {
- const attrs = attributeParser.parse(["#token", "(", "inheritable", ")"].map((t: any) => ({ text: t })));
+ it("parses an inheritable label", () => {
+ const attrs = attributeParser.lexAndParse("#token(inheritable)");
expect(attrs.length).toEqual(1);
expect(attrs[0].type).toEqual("label");
@@ -62,31 +101,80 @@ describe.todo("Parser", () => {
expect(attrs[0].value).toBeFalsy();
});
- it("label with value", () => {
- const attrs = attributeParser.parse(["#token", "=", "val"].map((t: any) => ({ text: t })));
+ it("parses a label with a value and tracks the value end index", () => {
+ const attrs = attributeParser.lexAndParse("#token=val");
expect(attrs.length).toEqual(1);
expect(attrs[0].type).toEqual("label");
expect(attrs[0].name).toEqual("token");
expect(attrs[0].value).toEqual("val");
+ // endIndex moves to the end of the value token
+ expect(attrs[0].endIndex).toEqual(9);
});
- it("relation", () => {
- let attrs = attributeParser.parse(["~token", "=", "#root/RclIpMauTOKS/NFi2gL4xtPxM"].map((t: any) => ({ text: t })));
+ it("parses an inheritable label that also has a value", () => {
+ const attrs = attributeParser.lexAndParse("#token(inheritable)=val");
+
+ expect(attrs.length).toEqual(1);
+ expect(attrs[0].isInheritable).toBeTruthy();
+ expect(attrs[0].value).toEqual("val");
+ });
+
+ it("parses a relation, extracting the note id from a full note path", () => {
+ const attrs = attributeParser.lexAndParse("~token=#root/RclIpMauTOKS/NFi2gL4xtPxM");
expect(attrs.length).toEqual(1);
expect(attrs[0].type).toEqual("relation");
expect(attrs[0].name).toEqual("token");
expect(attrs[0].value).toEqual("NFi2gL4xtPxM");
+ });
- attrs = attributeParser.parse(["~token", "=", "#NFi2gL4xtPxM"].map((t: any) => ({ text: t })));
+ it("parses a relation whose target is a bare #-prefixed note id", () => {
+ const attrs = attributeParser.lexAndParse("~token=#NFi2gL4xtPxM");
expect(attrs.length).toEqual(1);
expect(attrs[0].type).toEqual("relation");
expect(attrs[0].name).toEqual("token");
expect(attrs[0].value).toEqual("NFi2gL4xtPxM");
});
- */
+
+ it("parses a relation whose target is a plain note id (no #)", () => {
+ const attrs = attributeParser.lexAndParse("~token=NFi2gL4xtPxM");
+
+ expect(attrs[0].value).toEqual("NFi2gL4xtPxM");
+ });
+
+ it("parses an inheritable relation", () => {
+ const attrs = attributeParser.lexAndParse("~token(inheritable)=NFi2gL4xtPxM");
+
+ expect(attrs.length).toEqual(1);
+ expect(attrs[0].type).toEqual("relation");
+ expect(attrs[0].isInheritable).toBeTruthy();
+ expect(attrs[0].value).toEqual("NFi2gL4xtPxM");
+ });
+
+ it("parses multiple attributes in a single expression", () => {
+ const attrs = attributeParser.lexAndParse("#a=1 #b ~c=NFi2gL4xtPxM");
+
+ expect(attrs.map((a) => a.type)).toEqual(["label", "label", "relation"]);
+ expect(attrs.map((a) => a.name)).toEqual(["a", "b", "c"]);
+ expect(attrs.map((a) => a.value)).toEqual(["1", undefined, "NFi2gL4xtPxM"]);
+ });
+
+ it("allows an empty relation when allowEmptyRelations is set, stopping at it", () => {
+ const attrs = attributeParser.lexAndParse("#a ~token", true);
+
+ // the leading label is kept and parsing breaks out on the dangling relation
+ expect(attrs.map((a) => a.name)).toEqual(["a", "token"]);
+ expect(attrs[1].type).toEqual("relation");
+ expect(attrs[1].value).toBeUndefined();
+ });
+
+ it("does not treat a partial 3-token inheritable suffix as inheritable", () => {
+ // "(" "inheritable" present but the closing ")" is missing -> isInheritable false,
+ // and the dangling tokens are then rejected as invalid attributes
+ expect(() => attributeParser.lexAndParse("#a ( inheritable")).toThrow(/Invalid attribute "\("/);
+ });
});
describe("error cases", () => {
@@ -97,4 +185,34 @@ describe("error cases", () => {
expect(() => attributeParser.lexAndParse("#")).toThrow(`Attribute name is empty, please fill the name.`);
});
+
+ it("throws when a label ends with '=' but has no value", () => {
+ expect(() => attributeParser.lexAndParse("#token=")).toThrow(/Missing value for label "#token"/);
+ });
+
+ it("throws for a relation with '=' but no target token", () => {
+ expect(() => attributeParser.lexAndParse("~token=")).toThrow(/Relation "~token" .* should point to a note\./);
+ });
+
+ it("throws for a token that is neither a label nor a relation", () => {
+ // a bare value with no leading # or ~ is an invalid attribute
+ expect(() => attributeParser.lexAndParse("foo")).toThrow(/Invalid attribute "foo"/);
+ });
+
+ it("truncates long surrounding context with leading and trailing ellipses", () => {
+ // a long run before and after the offending relation triggers both
+ // the startIndex !== 0 ("...") and endIndex !== str.length ("...") branches in context()
+ const prefix = "#aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
+ const suffix = "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb";
+ const str = `${prefix} ~token ${suffix}`;
+
+ try {
+ attributeParser.lexAndParse(str);
+ throw new Error("should have thrown");
+ } catch (e: any) {
+ // the dangling relation is reported with truncated context on both sides
+ expect(e.message).toContain('Relation "~token"');
+ expect(e.message).toMatch(/in "\.\.\..*\.\.\."/);
+ }
+ });
});
diff --git a/apps/client/src/services/attribute_renderer.spec.ts b/apps/client/src/services/attribute_renderer.spec.ts
new file mode 100644
index 0000000000..276dc4dcab
--- /dev/null
+++ b/apps/client/src/services/attribute_renderer.spec.ts
@@ -0,0 +1,154 @@
+import { describe, expect, it, vi } from "vitest";
+
+import FAttribute from "../entities/fattribute.js";
+import type { AttributeType } from "../entities/fattribute.js";
+import { buildNote } from "../test/easy-froca";
+import attributeRenderer from "./attribute_renderer.js";
+import froca from "./froca.js";
+import ws from "./ws.js";
+
+// ws is globally mocked but the stub does not define logError.
+(ws as any).logError = vi.fn();
+
+function attr(props: { type: AttributeType; name: string; value: string; isInheritable?: boolean }) {
+ return new FAttribute(froca, {
+ attributeId: Math.random().toString(36).slice(2),
+ noteId: "n_attr",
+ type: props.type,
+ name: props.name,
+ value: props.value,
+ position: 0,
+ isInheritable: !!props.isInheritable
+ });
+}
+
+describe("renderAttribute", () => {
+ it("renders a label without value", async () => {
+ const $attr = await attributeRenderer.renderAttribute(attr({ type: "label", name: "foo", value: "" }), false);
+ expect($attr.text()).toBe("#foo");
+ });
+
+ it("renders a label with a simple value", async () => {
+ const $attr = await attributeRenderer.renderAttribute(attr({ type: "label", name: "color", value: "red" }), false);
+ expect($attr.text()).toBe("#color=red");
+ });
+
+ it("appends the inheritable marker only when both flags are set", async () => {
+ const inheritable = attr({ type: "label", name: "foo", value: "", isInheritable: true });
+ expect((await attributeRenderer.renderAttribute(inheritable, true)).text()).toBe("#foo(inheritable)");
+ // renderIsInheritable false -> no marker even though the attr is inheritable
+ expect((await attributeRenderer.renderAttribute(inheritable, false)).text()).toBe("#foo");
+ // renderIsInheritable true but attr not inheritable -> no marker
+ const notInheritable = attr({ type: "label", name: "foo", value: "" });
+ expect((await attributeRenderer.renderAttribute(notInheritable, true)).text()).toBe("#foo");
+ });
+
+ it("returns an empty span for auto-link attributes", async () => {
+ const $attr = await attributeRenderer.renderAttribute(attr({ type: "label", name: "internalBookmark", value: "x" }), false);
+ expect($attr.text()).toBe("");
+ expect($attr.children().length).toBe(0);
+ });
+
+ it("renders a relation with a resolvable target as a reference link", async () => {
+ const target = buildNote({ title: "Target Note" });
+ const $attr = await attributeRenderer.renderAttribute(attr({ type: "relation", name: "myrel", value: target.noteId }), false);
+ expect($attr.text()).toBe(`~myrel=Target Note`);
+ const $link = $attr.find("a.reference-link");
+ expect($link.length).toBe(1);
+ expect($link.attr("href")).toBe(`#root/${target.noteId}`);
+ });
+
+ it("renders relation prefix but no link when the target note is missing", async () => {
+ const orig = froca.getNote;
+ froca.getNote = vi.fn(async () => null) as typeof froca.getNote;
+ try {
+ const $attr = await attributeRenderer.renderAttribute(attr({ type: "relation", name: "myrel", value: "missing" }), false);
+ expect($attr.text()).toBe("~myrel=");
+ expect($attr.find("a").length).toBe(0);
+ } finally {
+ froca.getNote = orig;
+ }
+ });
+
+ it("renders nothing for a valueless relation", async () => {
+ const $attr = await attributeRenderer.renderAttribute(attr({ type: "relation", name: "myrel", value: "" }), false);
+ expect($attr.text()).toBe("");
+ });
+
+ it("logs an error for an unknown attribute type", async () => {
+ (ws as any).logError = vi.fn();
+ const bad = attr({ type: "label", name: "x", value: "" });
+ (bad as any).type = "weird";
+ const $attr = await attributeRenderer.renderAttribute(bad, false);
+ expect(ws.logError).toHaveBeenCalledWith("Unknown attr type: weird");
+ expect($attr.text()).toBe("");
+ });
+});
+
+describe("formatValue (via label rendering)", () => {
+ async function rendered(value: string) {
+ const $attr = await attributeRenderer.renderAttribute(attr({ type: "label", name: "v", value }), false);
+ return $attr.text().replace(/^#v=/, "");
+ }
+
+ it("formats values across every quoting branch", async () => {
+ // plain (matches the allowed-character regex) -> unquoted
+ expect(await rendered("simple-value_1,2.3")).toBe("simple-value_1,2.3");
+ // contains a space (fails regex), no double quote -> wrap in double quotes
+ expect(await rendered("a b")).toBe(`"a b"`);
+ // contains a double quote, no single quote -> wrap in single quotes
+ expect(await rendered(`he said "hi"`)).toBe(`'he said "hi"'`);
+ // contains both double and single quotes, no backtick -> wrap in backticks
+ expect(await rendered(`"x" and 'y'`)).toBe("`\"x\" and 'y'`");
+ // contains double, single and backtick -> escape double quotes and wrap in double quotes
+ expect(await rendered("\"a\" 'b' `c`")).toBe(`"\\"a\\" 'b' \`c\`"`);
+ });
+});
+
+describe("renderAttributes", () => {
+ it("joins multiple attributes with a space and stays empty for none", async () => {
+ const $container = await attributeRenderer.renderAttributes(
+ [attr({ type: "label", name: "a", value: "" }), attr({ type: "label", name: "b", value: "" })],
+ false
+ );
+ expect($container.hasClass("rendered-note-attributes")).toBe(true);
+ expect($container.text()).toBe("#a #b");
+
+ const $empty = await attributeRenderer.renderAttributes([], false);
+ expect($empty.text()).toBe("");
+ });
+});
+
+describe("renderNormalAttributes", () => {
+ it("renders plain attributes, excluding definitions/auto-links/hidden/foreign", async () => {
+ const note = buildNote({
+ title: "Note",
+ "#color": "red",
+ "#archived": "true", // hidden attribute -> excluded
+ "#internalBookmark": "x" // auto-link -> excluded
+ });
+ // a definition-style label is also excluded by isDefinition()
+ const def = attr({ type: "label", name: "label:foo", value: "promoted" });
+ (def as any).noteId = note.noteId;
+
+ const { count, $renderedAttributes } = await attributeRenderer.renderNormalAttributes(note);
+
+ expect(count).toBe(1);
+ expect($renderedAttributes.text()).toBe("#color=red");
+ });
+
+ it("renders only the attributes matching promoted definitions when present", async () => {
+ const note = buildNote({
+ title: "Promoted note",
+ "#label:rank": "promoted,single,text",
+ "#rank": "5",
+ "#color": "red"
+ });
+
+ const { count, $renderedAttributes } = await attributeRenderer.renderNormalAttributes(note);
+
+ // Only #rank matches the promoted definition #label:rank
+ expect(count).toBe(1);
+ expect($renderedAttributes.text()).toBe("#rank=5");
+ });
+});
diff --git a/apps/client/src/services/attributes.spec.ts b/apps/client/src/services/attributes.spec.ts
index f9caa6906d..80694427bf 100644
--- a/apps/client/src/services/attributes.spec.ts
+++ b/apps/client/src/services/attributes.spec.ts
@@ -1,7 +1,7 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import { buildNote } from "../test/easy-froca";
-import { setBooleanWithInheritance } from "./attributes";
+import attributeService, { removeOwnedAttributesByNameOrType, setAttribute, setBooleanWithInheritance, setLabel, setRelation } from "./attributes";
import froca from "./froca";
import server from "./server.js";
@@ -135,3 +135,226 @@ describe("Set boolean with inheritance", () => {
}, undefined);
});
});
+
+describe("addLabel / setLabel / setRelation", () => {
+ beforeEach(() => vi.clearAllMocks());
+
+ it("addLabel PUTs to the attribute endpoint with defaults", async () => {
+ const note = buildNote({ title: "N" });
+ await attributeService.addLabel(note.noteId, "color");
+ expect(server.put).toHaveBeenCalledWith(`notes/${note.noteId}/attribute`, {
+ type: "label",
+ name: "color",
+ value: "",
+ isInheritable: false
+ });
+ });
+
+ it("addLabel PUTs with explicit value and inheritance", async () => {
+ const note = buildNote({ title: "N" });
+ await attributeService.addLabel(note.noteId, "color", "red", true);
+ expect(server.put).toHaveBeenCalledWith(`notes/${note.noteId}/attribute`, {
+ type: "label",
+ name: "color",
+ value: "red",
+ isInheritable: true
+ });
+ });
+
+ it("setLabel PUTs to set-attribute with componentId passthrough", async () => {
+ const note = buildNote({ title: "N" });
+ await setLabel(note.noteId, "color", "red", true, "comp-1");
+ expect(server.put).toHaveBeenCalledWith(`notes/${note.noteId}/set-attribute`, {
+ type: "label",
+ name: "color",
+ value: "red",
+ isInheritable: true
+ }, "comp-1");
+ });
+
+ it("setRelation PUTs to set-attribute", async () => {
+ const note = buildNote({ title: "N" });
+ await setRelation(note.noteId, "template", "abc123", true);
+ expect(server.put).toHaveBeenCalledWith(`notes/${note.noteId}/set-attribute`, {
+ type: "relation",
+ name: "template",
+ value: "abc123",
+ isInheritable: true
+ });
+ });
+});
+
+describe("removeAttributeById / removeOwnedAttributesByNameOrType", () => {
+ beforeEach(() => vi.clearAllMocks());
+
+ it("removeAttributeById issues a DELETE", async () => {
+ const note = buildNote({ title: "N" });
+ await attributeService.removeAttributeById(note.noteId, "attr-xyz");
+ expect(server.remove).toHaveBeenCalledWith(`notes/${note.noteId}/attributes/attr-xyz`);
+ });
+
+ it("removeOwnedAttributesByNameOrType removes only matching owned attributes", async () => {
+ const note = buildNote({
+ title: "N",
+ "#color": "red",
+ "#size": "big",
+ "~template": "tpl1"
+ });
+ const colorId = note.getOwnedLabel("color")!.attributeId;
+ await removeOwnedAttributesByNameOrType(note, "label", "color");
+ expect(server.remove).toHaveBeenCalledTimes(1);
+ expect(server.remove).toHaveBeenCalledWith(`notes/${note.noteId}/attributes/${colorId}`);
+ });
+});
+
+describe("removeOwnedLabelByName / removeOwnedRelationByName", () => {
+ beforeEach(() => vi.clearAllMocks());
+
+ it("removeOwnedLabelByName removes an existing label and returns true", () => {
+ const note = buildNote({ title: "N", "#color": "red" });
+ const labelId = note.getOwnedLabel("color")!.attributeId;
+ expect(attributeService.removeOwnedLabelByName(note, "color")).toBe(true);
+ expect(server.remove).toHaveBeenCalledWith(`notes/${note.noteId}/attributes/${labelId}`);
+ });
+
+ it("removeOwnedLabelByName returns false when label is absent", () => {
+ const note = buildNote({ title: "N" });
+ expect(attributeService.removeOwnedLabelByName(note, "missing")).toBe(false);
+ expect(server.remove).not.toHaveBeenCalled();
+ });
+
+ it("removeOwnedRelationByName removes an existing relation and returns true", () => {
+ const note = buildNote({ title: "N", "~template": "tpl1" });
+ const relId = note.getOwnedRelation("template")!.attributeId;
+ expect(attributeService.removeOwnedRelationByName(note, "template")).toBe(true);
+ expect(server.remove).toHaveBeenCalledWith(`notes/${note.noteId}/attributes/${relId}`);
+ });
+
+ it("removeOwnedRelationByName returns false when relation is absent", () => {
+ const note = buildNote({ title: "N" });
+ expect(attributeService.removeOwnedRelationByName(note, "missing")).toBe(false);
+ expect(server.remove).not.toHaveBeenCalled();
+ });
+});
+
+describe("setAttribute", () => {
+ beforeEach(() => vi.clearAllMocks());
+
+ it("PUTs when a value is provided", async () => {
+ const note = buildNote({ title: "N" });
+ await setAttribute(note, "label", "color", "red", "comp-2");
+ expect(server.put).toHaveBeenCalledWith(`notes/${note.noteId}/set-attribute`, {
+ type: "label",
+ name: "color",
+ value: "red"
+ }, "comp-2");
+ expect(server.remove).not.toHaveBeenCalled();
+ });
+
+ it("removes an existing attribute when value is null", async () => {
+ const note = buildNote({ title: "N", "#color": "red" });
+ const attrId = note.getAttribute("label", "color")!.attributeId;
+ await setAttribute(note, "label", "color", null, "comp-3");
+ expect(server.remove).toHaveBeenCalledWith(`notes/${note.noteId}/attributes/${attrId}`, "comp-3");
+ expect(server.put).not.toHaveBeenCalled();
+ });
+
+ it("does nothing when value is undefined and the attribute is absent", async () => {
+ const note = buildNote({ title: "N" });
+ await setAttribute(note, "label", "color", undefined);
+ expect(server.remove).not.toHaveBeenCalled();
+ expect(server.put).not.toHaveBeenCalled();
+ });
+});
+
+describe("isAffecting", () => {
+ it("returns false when there is no affected note or no attribute row", () => {
+ const note = buildNote({ title: "N" });
+ expect(attributeService.isAffecting({ attributeId: "x" } as any, null)).toBe(false);
+ expect(attributeService.isAffecting(null as any, note)).toBe(false);
+ });
+
+ it("returns false when the attribute's owning note is not in froca", () => {
+ const note = buildNote({ title: "N" });
+ expect(attributeService.isAffecting({ attributeId: "x", noteId: "not-loaded" } as any, note)).toBe(false);
+ });
+
+ it("returns true when the attribute is directly owned by the affected note", () => {
+ const note = buildNote({ title: "N" });
+ expect(attributeService.isAffecting({ attributeId: "x", noteId: note.noteId } as any, note)).toBe(true);
+ });
+
+ it("returns true for an inheritable attribute owned by an ancestor", () => {
+ const parent = buildNote({
+ title: "Parent",
+ children: [{ title: "Child" }]
+ });
+ const child = froca.getNoteFromCache(parent.children[0])!;
+ expect(attributeService.isAffecting(
+ { attributeId: "x", noteId: parent.noteId, isInheritable: true } as any,
+ child
+ )).toBe(true);
+ });
+
+ it("returns false for an inheritable attribute owned by an unrelated note", () => {
+ const unrelated = buildNote({ title: "Unrelated" });
+ const note = buildNote({ title: "N" });
+ expect(attributeService.isAffecting(
+ { attributeId: "x", noteId: unrelated.noteId, isInheritable: true } as any,
+ note
+ )).toBe(false);
+ });
+
+ it("returns false for a non-inheritable attribute owned by an unrelated note", () => {
+ const unrelated = buildNote({ title: "Unrelated2" });
+ const note = buildNote({ title: "N2" });
+ expect(attributeService.isAffecting(
+ { attributeId: "x", noteId: unrelated.noteId, isInheritable: false } as any,
+ note
+ )).toBe(false);
+ });
+});
+
+describe("toggleDangerousAttribute", () => {
+ beforeEach(() => vi.clearAllMocks());
+
+ it("disables a label by prefixing it and removing the original", async () => {
+ const note = buildNote({ title: "N", "#run": "frontendStartup" });
+ const attrId = note.getOwnedLabel("run")!.attributeId;
+ await attributeService.toggleDangerousAttribute(note, "label", "run", false);
+ expect(server.put).toHaveBeenCalledWith(`notes/${note.noteId}/set-attribute`, {
+ type: "label",
+ name: "disabled:run",
+ value: "frontendStartup",
+ isInheritable: false
+ }, undefined);
+ expect(server.remove).toHaveBeenCalledWith(`notes/${note.noteId}/attributes/${attrId}`);
+ });
+
+ it("enables a disabled relation by stripping the prefix", async () => {
+ const note = buildNote({ title: "N", "~disabled:runOnInstance": "tgt" });
+ const attrId = note.getOwnedRelation("disabled:runOnInstance")!.attributeId;
+ await attributeService.toggleDangerousAttribute(note, "relation", "runOnInstance", true);
+ expect(server.put).toHaveBeenCalledWith(`notes/${note.noteId}/set-attribute`, {
+ type: "relation",
+ name: "runOnInstance",
+ value: "tgt",
+ isInheritable: false
+ });
+ expect(server.remove).toHaveBeenCalledWith(`notes/${note.noteId}/attributes/${attrId}`);
+ });
+
+ it("skips attributes whose name already matches the desired state", async () => {
+ const note = buildNote({ title: "N", "#widget": "x" });
+ await attributeService.toggleDangerousAttribute(note, "label", "widget", true);
+ expect(server.put).not.toHaveBeenCalled();
+ expect(server.remove).not.toHaveBeenCalled();
+ });
+});
+
+describe("getNameWithoutDangerousPrefix", () => {
+ it("strips the disabled: prefix when present and leaves plain names untouched", () => {
+ expect(attributeService.getNameWithoutDangerousPrefix("disabled:run")).toBe("run");
+ expect(attributeService.getNameWithoutDangerousPrefix("run")).toBe("run");
+ });
+});
diff --git a/apps/client/src/services/branches.spec.ts b/apps/client/src/services/branches.spec.ts
new file mode 100644
index 0000000000..b529046a51
--- /dev/null
+++ b/apps/client/src/services/branches.spec.ts
@@ -0,0 +1,485 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+// branches.ts registers two ws.subscribeToMessages callbacks at import time. branches.ts is loaded
+// transitively (via app_context -> main_tree_executors) before any top-level spec code runs, so we
+// must capture those subscribers through a hoisted ws mock. We still provide
+// waitForMaxKnownEntityChangeId so froca keeps working.
+const { wsCallbacks } = vi.hoisted(() => ({ wsCallbacks: [] as ((message: any) => Promise<void>)[] }));
+
+vi.mock("./ws.js", () => {
+ const logError = (message: string) => console.error(message);
+ const logInfo = (message: string) => console.log(message);
+ // ws.ts sets these window globals as a side effect; froca.ts relies on the global logError.
+ (window as any).logError = logError;
+ (window as any).logInfo = logInfo;
+ const subscribeToMessages = (cb: (message: any) => Promise<void>) => {
+ wsCallbacks.push(cb);
+ };
+ return {
+ default: {
+ subscribeToMessages,
+ waitForMaxKnownEntityChangeId: async () => {},
+ getMaxKnownEntityChangeSyncId: () => 0,
+ logError
+ },
+ subscribeToMessages,
+ logError,
+ logInfo,
+ throwError: (message: string) => {
+ throw new Error(message);
+ }
+ };
+});
+
+/** Dispatch a websocket message to every captured subscriber (branches filters by taskType). */
+async function dispatchWs(message: any) {
+ for (const cb of wsCallbacks) {
+ await cb(message);
+ }
+}
+
+import appContext from "../components/app_context.js";
+import FBranch from "../entities/fbranch.js";
+import { buildNote } from "../test/easy-froca.js";
+import branches from "./branches.js";
+import froca from "./froca.js";
+import hoistedNoteService from "./hoisted_note.js";
+import server from "./server.js";
+import toastService from "./toast.js";
+import utils from "./utils.js";
+
+// Seed the "root" note so branches whose parent/target is "root" resolve from the froca cache
+// instead of triggering the throwing tree/load POST.
+buildNote({ id: "root", title: "root" });
+
+/** Register a branch directly in froca with full control over its ids. */
+function makeBranch(branchId: string, noteId: string, parentNoteId = "root") {
+ const branch = new FBranch(froca, {
+ branchId,
+ noteId,
+ parentNoteId,
+ notePosition: 0,
+ fromSearchNote: false
+ });
+ froca.branches[branchId] = branch;
+ return branch;
+}
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ // Reset commonly-overridden collaborators back to safe defaults.
+ server.put = vi.fn(async () => ({ success: true, message: "" })) as typeof server.put;
+ server.remove = vi.fn(async () => ({})) as typeof server.remove;
+ toastService.showError = vi.fn();
+ toastService.showPersistent = vi.fn();
+ toastService.closePersistent = vi.fn();
+ hoistedNoteService.getHoistedNoteId = vi.fn(() => "root");
+ appContext.tabManager = { getActiveContext: () => undefined } as any;
+});
+
+describe("moveBeforeBranch", () => {
+ it("filters root/search branches, moves valid ones and bails on server failure", async () => {
+ const targetNote = buildNote({ title: "Target" });
+ const beforeBranch = makeBranch("before1", targetNote.noteId);
+ const a = makeBranch("a1", buildNote({ title: "A" }).noteId);
+
+ // virt- branches and root/hoisted branches are filtered out before the loop.
+ makeBranch("rootBranch", "root");
+
+ await branches.moveBeforeBranch(["virt-x", "rootBranch", "a1"], "before1");
+ expect(server.put).toHaveBeenCalledTimes(1);
+ expect(server.put).toHaveBeenCalledWith(`branches/a1/move-before/before1`);
+ expect(beforeBranch.noteId).toBe(targetNote.noteId);
+ expect(a).toBeDefined();
+
+ // server failure -> error toast and early return
+ server.put = vi.fn(async () => ({ success: false, message: "nope" })) as typeof server.put;
+ await branches.moveBeforeBranch(["a1"], "before1");
+ expect(toastService.showError).toHaveBeenCalledWith("nope");
+ });
+
+ it("returns early when before-branch is missing", async () => {
+ await branches.moveBeforeBranch(["a1"], "does-not-exist");
+ expect(server.put).not.toHaveBeenCalled();
+ });
+
+ it("rejects moving before root or launch bar config", async () => {
+ makeBranch("rootDest", "root");
+ await branches.moveBeforeBranch(["a1"], "rootDest");
+ expect(toastService.showError).toHaveBeenCalledTimes(1);
+
+ const lbSpy = vi.spyOn(utils, "isLaunchBarConfig").mockReturnValue(true);
+ makeBranch("lbDest", "_lbVisibleLaunchers");
+ await branches.moveBeforeBranch(["a1"], "lbDest");
+ expect(toastService.showError).toHaveBeenCalledTimes(2);
+ lbSpy.mockRestore();
+ });
+});
+
+describe("moveAfterBranch", () => {
+ it("moves valid branches in reverse and bails on server failure", async () => {
+ const dest = buildNote({ title: "Dest" });
+ makeBranch("afterDest", dest.noteId);
+ const n1 = buildNote({ title: "N1" });
+ const n2 = buildNote({ title: "N2" });
+ makeBranch("m1", n1.noteId);
+ makeBranch("m2", n2.noteId);
+
+ await branches.moveAfterBranch(["m1", "m2"], "afterDest");
+ expect(server.put).toHaveBeenCalledTimes(2);
+ // reversed order: m2 first, then m1
+ expect((server.put as any).mock.calls[0][0]).toBe("branches/m2/move-after/afterDest");
+ expect((server.put as any).mock.calls[1][0]).toBe("branches/m1/move-after/afterDest");
+
+ server.put = vi.fn(async () => ({ success: false, message: "fail" })) as typeof server.put;
+ await branches.moveAfterBranch(["m1"], "afterDest");
+ expect(toastService.showError).toHaveBeenCalledWith("fail");
+ });
+
+ it("returns early when after-note is missing", async () => {
+ await branches.moveAfterBranch(["m1"], "missing");
+ expect(server.put).not.toHaveBeenCalled();
+ });
+
+ it("rejects moving after a forbidden destination note", async () => {
+ // dest note id "root" is in the forbidden list
+ makeBranch("forbiddenDest", "root");
+ await branches.moveAfterBranch(["m1"], "forbiddenDest");
+ expect(toastService.showError).toHaveBeenCalledTimes(1);
+ expect(server.put).not.toHaveBeenCalled();
+ });
+});
+
+describe("moveToParentNote", () => {
+ it("returns early when new parent branch is missing", async () => {
+ await branches.moveToParentNote(["m1"], "no-parent");
+ expect(server.put).not.toHaveBeenCalled();
+ });
+
+ it("rejects moving into _lbRoot", async () => {
+ makeBranch("lbRootBranch", "_lbRoot");
+ await branches.moveToParentNote(["m1"], "lbRootBranch");
+ expect(toastService.showError).toHaveBeenCalledTimes(1);
+ expect(server.put).not.toHaveBeenCalled();
+ });
+
+ it("skips missing/hoisted/search-parent branches and moves valid ones", async () => {
+ const parentNote = buildNote({ title: "Parent" });
+ makeBranch("destParent", parentNote.noteId);
+
+ // a regular note under root
+ const regular = buildNote({ title: "Regular" });
+ makeBranch("regularBranch", regular.noteId, "root");
+
+ // a note whose parent is a search note -> skipped
+ const searchParent = buildNote({ title: "Search", type: "search" });
+ const childOfSearch = buildNote({ title: "Child" });
+ makeBranch("searchChildBranch", childOfSearch.noteId, searchParent.noteId);
+
+ // a hoisted note branch -> skipped
+ hoistedNoteService.getHoistedNoteId = vi.fn(() => regular.noteId === "x" ? "" : "hoistedId");
+ const hoisted = buildNote({ id: "hoistedId", title: "Hoisted" });
+ makeBranch("hoistedBranch", hoisted.noteId, "root");
+
+ await branches.moveToParentNote(["missingBranch", "hoistedBranch", "searchChildBranch", "regularBranch"], "destParent", "comp-1");
+
+ expect(server.put).toHaveBeenCalledTimes(1);
+ expect(server.put).toHaveBeenCalledWith("branches/regularBranch/move-to/destParent", undefined, "comp-1");
+ });
+
+ it("shows error and bails when the move fails", async () => {
+ const parentNote = buildNote({ title: "Parent2" });
+ makeBranch("destParent2", parentNote.noteId);
+ const regular = buildNote({ title: "Regular2" });
+ makeBranch("regularBranch2", regular.noteId, "root");
+
+ server.put = vi.fn(async () => ({ success: false, message: "boom" })) as typeof server.put;
+ await branches.moveToParentNote(["regularBranch2"], "destParent2");
+ expect(toastService.showError).toHaveBeenCalledWith("boom");
+ });
+});
+
+describe("deleteNotes", () => {
+ it("returns false when nothing remains after filtering root notes", async () => {
+ makeBranch("onlyRoot", "root");
+ const result = await branches.deleteNotes(["onlyRoot"]);
+ expect(result).toBe(false);
+ });
+
+ it("returns false when the user cancels the dialog", async () => {
+ const note = buildNote({ title: "Del" });
+ makeBranch("delBranch", note.noteId, "root");
+ appContext.triggerCommand = vi.fn((_name: any, data: any) => {
+ data.callback({ proceed: false });
+ }) as any;
+ const result = await branches.deleteNotes(["delBranch"]);
+ expect(result).toBe(false);
+ });
+
+ it("deletes a single branch, navigates to parent, and returns true", async () => {
+ const note = buildNote({ title: "Del2" });
+ makeBranch("delBranch2", note.noteId, "root");
+ const note2 = buildNote({ title: "Del2b" });
+ makeBranch("delBranch2b", note2.noteId, "root");
+
+ const setNote = vi.fn(async () => {});
+ appContext.tabManager = {
+ getActiveContext: () => ({ notePathArray: ["root", note.noteId], setNote })
+ } as any;
+ appContext.triggerCommand = vi.fn((_name: any, data: any) => {
+ data.callback({ proceed: true, deleteAllClones: false, eraseNotes: false });
+ }) as any;
+
+ // Two branches -> first iteration has last=false, second has last=true.
+ const result = await branches.deleteNotes(["delBranch2", "delBranch2b"]);
+ expect(result).toBe(true);
+ expect(server.remove).toHaveBeenCalledTimes(2);
+ const firstArg = (server.remove as any).mock.calls[0][0] as string;
+ const secondArg = (server.remove as any).mock.calls[1][0] as string;
+ expect(firstArg.startsWith(`branches/delBranch2?taskId=`)).toBe(true);
+ expect(firstArg).toContain("eraseNotes=false");
+ expect(firstArg).toContain("last=false");
+ expect(secondArg).toContain("last=true");
+ // navigated to the parent path ("root")
+ expect(setNote).toHaveBeenCalledWith("root");
+ });
+
+ it("deletes all clones (note endpoint), erases & reloads, and tolerates navigation errors", async () => {
+ const note = buildNote({ title: "Del3" });
+ makeBranch("delBranch3", note.noteId, "root");
+
+ appContext.tabManager = {
+ getActiveContext: () => {
+ throw new Error("navigation blew up");
+ }
+ } as any;
+ appContext.triggerCommand = vi.fn((_name: any, data: any) => {
+ data.callback({ proceed: true, deleteAllClones: true, eraseNotes: true });
+ }) as any;
+ const reloadSpy = vi.spyOn(utils, "reloadFrontendApp").mockImplementation(() => {});
+ const errSpy = vi.spyOn(console, "error").mockImplementation(() => {});
+
+ const result = await branches.deleteNotes(["delBranch3"], false, true, "comp-9");
+ expect(result).toBe(true);
+ // deleteAllClones -> notes/<noteId> endpoint
+ const removeArg = (server.remove as any).mock.calls[0][0] as string;
+ expect(removeArg.startsWith(`notes/${note.noteId}?taskId=`)).toBe(true);
+ expect(removeArg).toContain("eraseNotes=true");
+ expect(reloadSpy).toHaveBeenCalledTimes(1);
+ expect(errSpy).toHaveBeenCalled();
+ reloadSpy.mockRestore();
+ errSpy.mockRestore();
+ });
+
+ it("skips parent navigation when moveToParent is false", async () => {
+ const note = buildNote({ title: "Del4" });
+ makeBranch("delBranch4", note.noteId, "root");
+ const getActiveContext = vi.fn(() => undefined);
+ appContext.tabManager = { getActiveContext } as any;
+ appContext.triggerCommand = vi.fn((_name: any, data: any) => {
+ data.callback({ proceed: true, deleteAllClones: false, eraseNotes: false });
+ }) as any;
+
+ const result = await branches.deleteNotes(["delBranch4"], false, false);
+ expect(result).toBe(true);
+ // getActiveContext only used by activateParentNotePath, which is skipped
+ expect(getActiveContext).not.toHaveBeenCalled();
+ });
+
+ it("handles a deleteAllClones request where the branch is no longer in froca", async () => {
+ // filterRootNote keeps non-root ids even if the branch is gone? No: filterRootNote drops
+ // unknown branches. So to exercise the `deleteAllClones && !branch` fallback we keep a real
+ // branch through filtering, then remove it from froca before the delete loop runs.
+ const note = buildNote({ title: "Del5" });
+ makeBranch("delBranch5", note.noteId, "root");
+ appContext.triggerCommand = vi.fn((_name: any, data: any) => {
+ // remove the branch right when the dialog "resolves", before the delete loop reads it
+ delete froca.branches["delBranch5"];
+ data.callback({ proceed: true, deleteAllClones: true, eraseNotes: false });
+ }) as any;
+
+ const result = await branches.deleteNotes(["delBranch5"], false, false);
+ expect(result).toBe(true);
+ // branch missing -> falls back to deleting the branch id endpoint
+ const removeArg = (server.remove as any).mock.calls[0][0] as string;
+ expect(removeArg.startsWith("branches/delBranch5?taskId=")).toBe(true);
+ });
+});
+
+describe("activateParentNotePath (via deleteNotes navigation)", () => {
+ it("does not navigate when the deleted note is not on the active path", async () => {
+ const note = buildNote({ title: "Off" });
+ makeBranch("offBranch", note.noteId, "root");
+ const setNote = vi.fn(async () => {});
+ appContext.tabManager = {
+ getActiveContext: () => ({ notePathArray: ["someOtherNote"], setNote })
+ } as any;
+ appContext.triggerCommand = vi.fn((_name: any, data: any) => {
+ data.callback({ proceed: true, deleteAllClones: false, eraseNotes: false });
+ }) as any;
+
+ await branches.deleteNotes(["offBranch"]);
+ expect(setNote).not.toHaveBeenCalled();
+ });
+
+ it("does not navigate when the deleted note is the path root (no parent path)", async () => {
+ const note = buildNote({ title: "Top" });
+ makeBranch("topBranch", note.noteId, "root");
+ const setNote = vi.fn(async () => {});
+ appContext.tabManager = {
+ getActiveContext: () => ({ notePathArray: [note.noteId, "child"], setNote })
+ } as any;
+ appContext.triggerCommand = vi.fn((_name: any, data: any) => {
+ data.callback({ proceed: true, deleteAllClones: false, eraseNotes: false });
+ }) as any;
+
+ await branches.deleteNotes(["topBranch"]);
+ // earliestIndex is 0 -> parentPath is empty -> no setNote
+ expect(setNote).not.toHaveBeenCalled();
+ });
+
+ it("ignores deleted-then-missing branches and a context without a note path", async () => {
+ const noteA = buildNote({ title: "Ancestor" });
+ makeBranch("ancBranch", noteA.noteId, "root");
+ const setNote = vi.fn(async () => {});
+ // Active context exists but has no notePathArray -> the `?? []` fallback is exercised.
+ appContext.tabManager = {
+ getActiveContext: () => ({ notePathArray: undefined, setNote })
+ } as any;
+ appContext.triggerCommand = vi.fn((_name: any, data: any) => {
+ // Remove the branch after filtering but before navigation, so activateParentNotePath's
+ // `froca.getBranch(...)` returns undefined and the `if (branch)` false arm is taken.
+ delete froca.branches["ancBranch"];
+ data.callback({ proceed: true, deleteAllClones: false, eraseNotes: false });
+ }) as any;
+
+ const result = await branches.deleteNotes(["ancBranch"]);
+ expect(result).toBe(true);
+ // empty note path + missing branch -> no navigation
+ expect(setNote).not.toHaveBeenCalled();
+ });
+});
+
+describe("moveNodeUpInHierarchy", () => {
+ function fakeNode(opts: { parentNoteType?: string; parentBranchId?: string; branchId?: string }) {
+ const parent: any = {
+ data: { noteType: opts.parentNoteType, branchId: opts.parentBranchId },
+ getParent: () => null
+ };
+ return {
+ data: { branchId: opts.branchId },
+ getParent: () => parent
+ } as unknown as Fancytree.FancytreeNode;
+ }
+
+ it("returns early for hoisted, top-level or search-parent nodes", async () => {
+ // hoisted node
+ hoistedNoteService.isHoistedNode = vi.fn(() => true);
+ hoistedNoteService.isTopLevelNode = vi.fn(() => false);
+ await branches.moveNodeUpInHierarchy(fakeNode({ parentNoteType: "text" }));
+ expect(server.put).not.toHaveBeenCalled();
+
+ // top-level node
+ hoistedNoteService.isHoistedNode = vi.fn(() => false);
+ hoistedNoteService.isTopLevelNode = vi.fn(() => true);
+ await branches.moveNodeUpInHierarchy(fakeNode({ parentNoteType: "text" }));
+ expect(server.put).not.toHaveBeenCalled();
+
+ // search-parent node
+ hoistedNoteService.isTopLevelNode = vi.fn(() => false);
+ await branches.moveNodeUpInHierarchy(fakeNode({ parentNoteType: "search" }));
+ expect(server.put).not.toHaveBeenCalled();
+ });
+
+ it("moves the node after its parent's branch and shows error on failure", async () => {
+ hoistedNoteService.isHoistedNode = vi.fn(() => false);
+ hoistedNoteService.isTopLevelNode = vi.fn(() => false);
+
+ await branches.moveNodeUpInHierarchy(fakeNode({ parentNoteType: "text", parentBranchId: "pb", branchId: "cb" }));
+ expect(server.put).toHaveBeenCalledWith("branches/cb/move-after/pb");
+
+ server.put = vi.fn(async () => ({ success: false, message: "denied" })) as typeof server.put;
+ await branches.moveNodeUpInHierarchy(fakeNode({ parentNoteType: "text", parentBranchId: "pb", branchId: "cb" }));
+ expect(toastService.showError).toHaveBeenCalledWith("denied");
+ });
+});
+
+describe("clone helpers", () => {
+ it("cloneNoteToBranch calls server and surfaces errors", async () => {
+ await branches.cloneNoteToBranch("childN", "parentB", "px");
+ expect(server.put).toHaveBeenCalledWith("notes/childN/clone-to-branch/parentB", { prefix: "px" });
+
+ server.put = vi.fn(async () => ({ success: false, message: "e1" })) as typeof server.put;
+ await branches.cloneNoteToBranch("childN", "parentB");
+ expect(toastService.showError).toHaveBeenCalledWith("e1");
+ });
+
+ it("cloneNoteToParentNote calls server and surfaces errors", async () => {
+ await branches.cloneNoteToParentNote("childN", "parentN", "py");
+ expect(server.put).toHaveBeenCalledWith("notes/childN/clone-to-note/parentN", { prefix: "py" });
+
+ server.put = vi.fn(async () => ({ success: false, message: "e2" })) as typeof server.put;
+ await branches.cloneNoteToParentNote("childN", "parentN");
+ expect(toastService.showError).toHaveBeenCalledWith("e2");
+ });
+
+ it("cloneNoteAfter calls server and surfaces errors", async () => {
+ await branches.cloneNoteAfter("noteN", "afterB");
+ expect(server.put).toHaveBeenCalledWith("notes/noteN/clone-after/afterB");
+
+ server.put = vi.fn(async () => ({ success: false, message: "e3" })) as typeof server.put;
+ await branches.cloneNoteAfter("noteN", "afterB");
+ expect(toastService.showError).toHaveBeenCalledWith("e3");
+ });
+});
+
+describe("ws task-message subscribers", () => {
+ it("registered at least the two branch task subscribers at import time", () => {
+ // Other modules also subscribe; branches.ts contributes two, identified by their taskType filter.
+ expect(wsCallbacks.length).toBeGreaterThanOrEqual(2);
+ });
+
+ it("deleteNotes subscriber reacts to error/progress/success and ignores other task types", async () => {
+ // Messages without a matching taskType (or without taskType at all) -> ignored by branch subscribers.
+ await dispatchWs({ type: "taskProgressCount", taskId: "t", progressCount: 1 });
+ await dispatchWs({ taskType: "deleteNotes" }); // matching taskType but no recognized type -> no branch taken
+ expect(toastService.showError).not.toHaveBeenCalled();
+ expect(toastService.showPersistent).not.toHaveBeenCalled();
+
+ await dispatchWs({ taskType: "deleteNotes", type: "taskError", taskId: "e1", message: "boom" });
+ expect(toastService.closePersistent).toHaveBeenCalledWith("e1");
+ expect(toastService.showError).toHaveBeenCalledWith("boom");
+
+ await dispatchWs({ taskType: "deleteNotes", type: "taskProgressCount", taskId: "p1", progressCount: 3 });
+ expect(toastService.showPersistent).toHaveBeenCalledTimes(1);
+ expect((toastService.showPersistent as any).mock.calls[0][0].id).toBe("p1");
+
+ await dispatchWs({ taskType: "deleteNotes", type: "taskSucceeded", taskId: "s1" });
+ const succeededToast = (toastService.showPersistent as any).mock.calls[1][0];
+ expect(succeededToast.id).toBe("s1");
+ expect(succeededToast.timeout).toBe(5000);
+ expect(succeededToast.icon).toBe("trash");
+ });
+
+ it("undeleteNotes subscriber reacts to error/progress/success and ignores other task types", async () => {
+ // undelete message with no recognized type -> falls through every else-if (no toast).
+ await dispatchWs({ taskType: "undeleteNotes" });
+ expect(toastService.showError).not.toHaveBeenCalled();
+ expect(toastService.showPersistent).not.toHaveBeenCalled();
+
+ // a deleteNotes message must NOT be handled by the undelete subscriber as an undelete,
+ // but it IS handled by the delete subscriber. Assert the undelete-specific outcome instead.
+ await dispatchWs({ taskType: "undeleteNotes", type: "taskError", taskId: "ue1", message: "undel-boom" });
+ expect(toastService.closePersistent).toHaveBeenCalledWith("ue1");
+ expect(toastService.showError).toHaveBeenCalledWith("undel-boom");
+
+ await dispatchWs({ taskType: "undeleteNotes", type: "taskProgressCount", taskId: "ue2", progressCount: 7 });
+ expect(toastService.showPersistent).toHaveBeenCalledTimes(1);
+ expect((toastService.showPersistent as any).mock.calls[0][0].id).toBe("ue2");
+
+ await dispatchWs({ taskType: "undeleteNotes", type: "taskSucceeded", taskId: "ue3" });
+ const succeededToast = (toastService.showPersistent as any).mock.calls[1][0];
+ expect(succeededToast.id).toBe("ue3");
+ expect(succeededToast.timeout).toBe(5000);
+ });
+});
diff --git a/apps/client/src/services/bulk_action.spec.ts b/apps/client/src/services/bulk_action.spec.ts
new file mode 100644
index 0000000000..a01d665367
--- /dev/null
+++ b/apps/client/src/services/bulk_action.spec.ts
@@ -0,0 +1,118 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+import FAttribute from "../entities/fattribute.js";
+import froca from "./froca.js";
+import noteAttributeCache from "./note_attribute_cache.js";
+import { buildNote } from "../test/easy-froca";
+import bulkActionService, { executeBulkActions } from "./bulk_action";
+import AddLabelBulkAction from "../widgets/bulk_actions/label/add_label";
+import server from "./server.js";
+import ws from "./ws.js";
+import toast from "./toast.js";
+
+// The target awaits ws.waitForMaxKnownEntityChangeId(), which the global ws stub does not provide.
+ws.waitForMaxKnownEntityChangeId = vi.fn(async () => {}) as typeof ws.waitForMaxKnownEntityChangeId;
+
+/** Registers an extra "action" label on an already-built note, bypassing buildNote's unique-key limitation. */
+function addActionLabel(noteId: string, value: string) {
+ const attribute = new FAttribute(froca, {
+ noteId,
+ attributeId: `attr_${Math.random().toString(36).slice(2)}`,
+ type: "label",
+ name: "action",
+ value,
+ position: 0,
+ isInheritable: false
+ });
+ froca.attributes[attribute.attributeId] = attribute;
+ froca.notes[noteId].attributes.push(attribute.attributeId);
+ if (!noteAttributeCache.attributes[noteId]) {
+ noteAttributeCache.attributes[noteId] = [];
+ }
+ noteAttributeCache.attributes[noteId].push(attribute);
+ return attribute;
+}
+
+describe("bulk_action service", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ ws.waitForMaxKnownEntityChangeId = vi.fn(async () => {}) as typeof ws.waitForMaxKnownEntityChangeId;
+ });
+
+ it("exposes the action metadata via the default export", () => {
+ expect(bulkActionService.ACTION_CLASSES).toContain(AddLabelBulkAction);
+ // Four groups: labels, relations, notes, other.
+ expect(bulkActionService.ACTION_GROUPS).toHaveLength(4);
+ expect(bulkActionService.ACTION_GROUPS[3].actions).toEqual([
+ bulkActionService.ACTION_GROUPS[3].actions[0]
+ ]);
+ });
+
+ it("addAction posts an action attribute and waits for sync", async () => {
+ server.post = vi.fn(async () => ({})) as typeof server.post;
+ const note = buildNote({ title: "Target" });
+
+ await bulkActionService.addAction(note.noteId, "addLabel");
+
+ expect(server.post).toHaveBeenCalledWith(`notes/${note.noteId}/attributes`, {
+ type: "label",
+ name: "action",
+ value: JSON.stringify({ name: "addLabel" })
+ });
+ expect(ws.waitForMaxKnownEntityChangeId).toHaveBeenCalledTimes(1);
+ });
+
+ it("parseActions instantiates known actions and skips invalid/unknown ones", () => {
+ const logError = vi.fn();
+ (globalThis as any).logError = logError;
+
+ const note = buildNote({ title: "Note with actions" });
+ // Valid known action.
+ addActionLabel(note.noteId, JSON.stringify({ name: "addLabel", labelName: "foo" }));
+ // Invalid JSON -> JSON.parse throws -> catch branch -> null.
+ addActionLabel(note.noteId, "{not-valid-json");
+ // Valid JSON but unknown action name -> no ActionClass -> null.
+ addActionLabel(note.noteId, JSON.stringify({ name: "doesNotExist" }));
+
+ const actions = bulkActionService.parseActions(note);
+
+ // Only the valid known action survives the filter.
+ expect(actions).toHaveLength(1);
+ expect(actions[0]).toBeInstanceOf(AddLabelBulkAction);
+ expect(actions[0].actionDef).toEqual({ name: "addLabel", labelName: "foo" });
+ // Both failures were logged.
+ expect(logError).toHaveBeenCalledTimes(2);
+ expect(logError.mock.calls[0][0]).toContain("failed with error");
+ expect(logError.mock.calls[1][0]).toContain("No action class");
+ });
+
+ it("executeBulkActions posts the actions, waits for sync, and toasts (default includeDescendants)", async () => {
+ server.post = vi.fn(async () => ({})) as typeof server.post;
+ const toastSpy = vi.spyOn(toast, "showMessage").mockImplementation(() => {});
+ const actions = [{ name: "addLabel" }] as any;
+
+ await executeBulkActions(["a", "b"], actions);
+
+ expect(server.post).toHaveBeenCalledWith("bulk-action/execute", {
+ noteIds: ["a", "b"],
+ includeDescendants: false,
+ actions
+ });
+ expect(ws.waitForMaxKnownEntityChangeId).toHaveBeenCalledTimes(1);
+ expect(toastSpy).toHaveBeenCalledTimes(1);
+ expect(toastSpy.mock.calls[0][1]).toBe(3000);
+ });
+
+ it("executeBulkActions forwards includeDescendants when provided", async () => {
+ server.post = vi.fn(async () => ({})) as typeof server.post;
+ vi.spyOn(toast, "showMessage").mockImplementation(() => {});
+
+ await executeBulkActions(["x"], [] as any, true);
+
+ expect(server.post).toHaveBeenCalledWith("bulk-action/execute", {
+ noteIds: ["x"],
+ includeDescendants: true,
+ actions: []
+ });
+ });
+});
diff --git a/apps/client/src/services/bundle.spec.ts b/apps/client/src/services/bundle.spec.ts
index 5f9bb5dd8e..f063fe639d 100644
--- a/apps/client/src/services/bundle.spec.ts
+++ b/apps/client/src/services/bundle.spec.ts
@@ -1,6 +1,17 @@
-import { describe, expect, it } from "vitest";
-import { Bundle, executeBundle } from "./bundle";
+import { beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
+
import { buildNote } from "../test/easy-froca";
+import bundleService, { Bundle, executeBundle, executeBundleWithoutErrorHandling, WidgetsByParent } from "./bundle";
+import server from "./server.js";
+import * as toast from "./toast";
+import ws from "./ws.js";
+
+// `bundle.ts` references a bare global `logError(...)` in its catch branches (normally set on
+// `window` by ws.ts, which is globally mocked here). Provide it so the catch paths don't throw.
+beforeAll(() => {
+ (window as any).logError = vi.fn();
+ (ws as any).waitForMaxKnownEntityChangeId = vi.fn(async () => {});
+});
describe("Script bundle", () => {
it("dayjs is available", async () => {
@@ -18,6 +29,283 @@ describe("Script bundle", () => {
});
});
+describe("executeBundle / executeBundleWithoutErrorHandling", () => {
+ it("executeBundleWithoutErrorHandling propagates script errors", async () => {
+ const id = buildNote({ title: "Throwing note" }).noteId;
+ const bundle: Bundle = {
+ script: `throw new Error("boom");`,
+ html: "",
+ noteId: id,
+ allNoteIds: [id]
+ };
+ await expect(executeBundleWithoutErrorHandling(bundle, null)).rejects.toThrow("boom");
+ });
+
+ it("executeBundle swallows errors and reports them via showErrorForScriptNote + logError", async () => {
+ const id = buildNote({ title: "Throwing note" }).noteId;
+ const spy = vi.spyOn(toast, "showErrorForScriptNote").mockResolvedValue(undefined);
+ const bundle: Bundle = {
+ script: `throw new Error("kaboom");`,
+ html: "",
+ noteId: id,
+ allNoteIds: [id]
+ };
+ const result = await executeBundle(bundle, null);
+ expect(result).toBeUndefined();
+ expect(spy).toHaveBeenCalled();
+ expect(spy.mock.calls[0][0]).toBe(id);
+ expect((window as any).logError).toHaveBeenCalled();
+ spy.mockRestore();
+ });
+});
+
+describe("getAndExecuteBundle (default export)", () => {
+ it("posts to script/bundle and executes the returned bundle", async () => {
+ const id = buildNote({ title: "Posted note" }).noteId;
+ const bundle: Bundle = {
+ script: `return 41 + 1;`,
+ html: "",
+ noteId: id,
+ allNoteIds: [id]
+ };
+ const postSpy = vi.fn(async () => bundle);
+ server.post = postSpy as unknown as typeof server.post;
+
+ const result = await bundleService.getAndExecuteBundle(id);
+ expect(postSpy).toHaveBeenCalledWith(`script/bundle/${id}`, { script: null, params: null });
+ expect(result).toBe(42);
+ });
+});
+
+describe("executeStartupBundles (default export)", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ (window as any).logError = vi.fn();
+ });
+
+ it("requests non-mobile startup scripts and executes each bundle", async () => {
+ const id = buildNote({ title: "Startup note" }).noteId;
+ const bundles: Bundle[] = [{
+ script: `api.__startupRan = true;`,
+ html: "",
+ noteId: id,
+ allNoteIds: [id]
+ }];
+ const getSpy = vi.fn(async () => bundles);
+ server.get = getSpy as unknown as typeof server.get;
+ const utils = (await import("./utils.js")).default;
+ vi.spyOn(utils, "isMobile").mockReturnValue(false);
+
+ await bundleService.executeStartupBundles();
+ expect(getSpy).toHaveBeenCalledWith("script/startup");
+ });
+
+ it("requests mobile startup scripts when on mobile", async () => {
+ const getSpy = vi.fn(async () => [] as Bundle[]);
+ server.get = getSpy as unknown as typeof server.get;
+ const utils = (await import("./utils.js")).default;
+ vi.spyOn(utils, "isMobile").mockReturnValue(true);
+
+ await bundleService.executeStartupBundles();
+ expect(getSpy).toHaveBeenCalledWith("script/startup?mobile=true");
+ });
+});
+
+describe("WidgetsByParent", () => {
+ let errorSpy: ReturnType<typeof vi.spyOn>;
+
+ beforeEach(() => {
+ errorSpy = vi.spyOn(toast, "showErrorForScriptNote").mockResolvedValue(undefined);
+ errorSpy.mockClear();
+ });
+
+ function legacyWidget(noteId: string, parentWidget?: string) {
+ return { _noteId: noteId, parentWidget } as any;
+ }
+
+ it("add() registers a legacy widget under its parentWidget", () => {
+ const w = new WidgetsByParent();
+ w.add(legacyWidget("note-legacy", "left-pane"));
+ expect(errorSpy).not.toHaveBeenCalled();
+ expect(w.getLegacyWidgets("left-pane")).toHaveLength(1);
+ expect(w.getLegacyWidgets("right-pane")).toEqual([]);
+ });
+
+ it("add() instantiates legacy widgets provided as a class (prototype)", () => {
+ const w = new WidgetsByParent();
+ class MyWidget {
+ _noteId = "note-class";
+ }
+ // The class carries a static `parentWidget` so add() registers it, and it has a `.prototype`
+ // so getLegacyWidgets() instantiates it (rather than using the instance directly).
+ (MyWidget as any).parentWidget = "center-pane";
+ w.add(MyWidget as any);
+ const widgets = w.getLegacyWidgets("center-pane");
+ expect(widgets).toHaveLength(1);
+ expect(widgets[0]).toBeInstanceOf(MyWidget);
+ });
+
+ it("add() registers a preact widget under its parent", () => {
+ const w = new WidgetsByParent();
+ const preactWidget = {
+ _noteId: "note-preact",
+ type: "preact-widget",
+ parent: "right-pane",
+ render: () => null,
+ position: 25
+ } as any;
+ w.add(preactWidget);
+ expect(errorSpy).not.toHaveBeenCalled();
+ expect(w.getPreactWidgets("right-pane")).toHaveLength(1);
+ expect(w.getPreactWidgets("left-pane")).toEqual([]);
+ });
+
+ it("add() reports an error for a legacy widget without a parentWidget", () => {
+ const w = new WidgetsByParent();
+ w.add(legacyWidget("note-orphan"));
+ expect(errorSpy).toHaveBeenCalledTimes(1);
+ expect(errorSpy.mock.calls[0][0]).toBe("note-orphan");
+ });
+
+ it("add() reports an error for a preact widget without a parent", () => {
+ const w = new WidgetsByParent();
+ const preactWidget = {
+ _noteId: "note-preact-orphan",
+ type: "preact-widget",
+ parent: "",
+ render: () => null
+ } as any;
+ w.add(preactWidget);
+ expect(errorSpy).toHaveBeenCalledTimes(1);
+ expect(errorSpy.mock.calls[0][0]).toBe("note-preact-orphan");
+ });
+
+ it("get() returns legacy widgets plus rendered+positioned preact widgets", () => {
+ const w = new WidgetsByParent();
+ w.add(legacyWidget("note-legacy", "right-pane"));
+ w.add({
+ _noteId: "note-preact",
+ type: "preact-widget",
+ parent: "right-pane",
+ render: () => null,
+ position: 77
+ } as any);
+
+ const widgets = w.get("right-pane");
+ // one legacy + one wrapped preact widget
+ expect(widgets).toHaveLength(2);
+ const wrapped = widgets[1] as any;
+ expect(wrapped.position).toBe(77);
+ });
+
+ it("get() wraps a preact widget without a position without overriding it", () => {
+ const w = new WidgetsByParent();
+ w.add({
+ _noteId: "note-preact",
+ type: "preact-widget",
+ parent: "right-pane",
+ render: () => null
+ } as any);
+
+ const widgets = w.get("right-pane");
+ expect(widgets.length).toBeGreaterThanOrEqual(1);
+ });
+});
+
+describe("getWidgetBundlesByParent (default export)", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ (window as any).logError = vi.fn();
+ });
+
+ it("executes widget bundles, tags them with noteId, and adds them by parent", async () => {
+ const id = buildNote({ title: "Widget note" }).noteId;
+ // bundle returns a widget object that becomes a legacy widget once tagged with _noteId
+ const bundle: Bundle = {
+ script: `return { parentWidget: "left-pane" };`,
+ html: "",
+ noteId: id,
+ allNoteIds: [id]
+ };
+ server.get = vi.fn(async (url: string) => {
+ if (url === "script/widgets") return [bundle];
+ return [];
+ }) as unknown as typeof server.get;
+
+ const result = await bundleService.getWidgetBundlesByParent();
+ const widgets = result.getLegacyWidgets("left-pane");
+ expect(widgets).toHaveLength(1);
+ expect((widgets[0] as any)._noteId).toBe(id);
+ });
+
+ it("ignores bundles that produce no widget (falsy return)", async () => {
+ const id = buildNote({ title: "Empty widget note" }).noteId;
+ const bundle: Bundle = {
+ script: `return undefined;`,
+ html: "",
+ noteId: id,
+ allNoteIds: [id]
+ };
+ server.get = vi.fn(async (url: string) => {
+ if (url === "script/widgets") return [bundle];
+ return [];
+ }) as unknown as typeof server.get;
+
+ const result = await bundleService.getWidgetBundlesByParent();
+ expect(result.getLegacyWidgets("left-pane")).toEqual([]);
+ });
+
+ it("reports a per-bundle error when executing a single bundle throws", async () => {
+ const id = buildNote({ title: "Bad widget note" }).noteId;
+ const errorSpy = vi.spyOn(toast, "showErrorForScriptNote").mockResolvedValue(undefined);
+ // executeBundleWithoutErrorHandling needs the note to resolve in froca; force the per-bundle
+ // try/catch by making add() throw on a widget that has neither parent nor parentWidget while
+ // also having a falsy _noteId is not enough — instead throw during execution by referencing
+ // an unknown allNoteId so ScriptContext can't build the api, surfacing inside executeBundle's
+ // own handler. To exercise getWidgetBundlesByParent's inner catch we make add() throw.
+ const w = new WidgetsByParent();
+ const addSpy = vi.spyOn(WidgetsByParent.prototype, "add").mockImplementation(() => {
+ throw new Error("add failed");
+ });
+ const bundle: Bundle = {
+ script: `return { parentWidget: "left-pane" };`,
+ html: "",
+ noteId: id,
+ allNoteIds: [id]
+ };
+ server.get = vi.fn(async (url: string) => {
+ if (url === "script/widgets") return [bundle];
+ return [];
+ }) as unknown as typeof server.get;
+
+ const result = await bundleService.getWidgetBundlesByParent();
+ expect(addSpy).toHaveBeenCalled();
+ expect(errorSpy).toHaveBeenCalled();
+ expect(errorSpy.mock.calls[0][0]).toBe(id);
+ expect((window as any).logError).toHaveBeenCalled();
+ expect(result).toBeInstanceOf(WidgetsByParent);
+ void w;
+ addSpy.mockRestore();
+ errorSpy.mockRestore();
+ });
+
+ it("shows a persistent toast when fetching the widget list fails", async () => {
+ const persistentSpy = vi.spyOn(toast.default, "showPersistent").mockReturnValue(undefined as any);
+ server.get = vi.fn(async (url: string) => {
+ if (url === "script/widgets") throw new Error("list fetch failed");
+ return [];
+ }) as unknown as typeof server.get;
+
+ const result = await bundleService.getWidgetBundlesByParent();
+ expect(persistentSpy).toHaveBeenCalledWith(expect.objectContaining({
+ id: "custom-widget-list-failure",
+ icon: "bx bx-error-circle"
+ }));
+ expect(result).toBeInstanceOf(WidgetsByParent);
+ persistentSpy.mockRestore();
+ });
+});
+
function getBundle(script: string) {
const id = buildNote({
title: "Script note"
diff --git a/apps/client/src/services/clipboard.spec.ts b/apps/client/src/services/clipboard.spec.ts
new file mode 100644
index 0000000000..9b3c85f3b7
--- /dev/null
+++ b/apps/client/src/services/clipboard.spec.ts
@@ -0,0 +1,195 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+import { buildNote } from "../test/easy-froca";
+import branchService from "./branches.js";
+import clipboard from "./clipboard.js";
+import froca from "./froca.js";
+import linkService from "./link.js";
+import toastService from "./toast.js";
+import utils from "./utils.js";
+import * as ws from "./ws.js";
+
+// `throwError` is a named export of ws.js that the global setup mock does not provide.
+// Supply a throwing implementation so the "unrecognized clipboard mode" branch behaves like production.
+(ws as any).throwError = vi.fn((message: string) => {
+ throw new Error(message);
+});
+
+// froca.ts references a global `logError` (normally installed by the real ws.ts, which is mocked here).
+// Provide a no-op so looking up an unknown branch id doesn't blow up.
+(globalThis as any).logError = (globalThis as any).logError ?? (() => {});
+
+branchService.moveAfterBranch = vi.fn(async () => {}) as typeof branchService.moveAfterBranch;
+branchService.moveToParentNote = vi.fn(async () => {}) as typeof branchService.moveToParentNote;
+branchService.cloneNoteAfter = vi.fn(async () => {}) as typeof branchService.cloneNoteAfter;
+branchService.cloneNoteToBranch = vi.fn(async () => {}) as typeof branchService.cloneNoteToBranch;
+toastService.showMessage = vi.fn() as typeof toastService.showMessage;
+
+/** Build a parent note with a single child and return both notes plus the child's branch id. */
+function buildParentWithChild() {
+ const parent = buildNote({ title: "Parent", children: [{ title: "Child" }] });
+ const childNoteId = parent.children[0];
+ const childBranchId = parent.childToBranch[childNoteId];
+ return { parent, childBranchId, childNoteId };
+}
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ // Reset module-level clipboard state to a known-empty baseline before each test.
+ clipboard.cut([]);
+});
+
+describe("cut", () => {
+ it("sets cut mode and toasts when given branches; does nothing for an empty list", () => {
+ const { childBranchId } = buildParentWithChild();
+
+ clipboard.cut([childBranchId]);
+ expect(clipboard.isClipboardEmpty()).toBe(false);
+ expect(toastService.showMessage).toHaveBeenCalledTimes(1);
+
+ vi.clearAllMocks();
+ clipboard.cut([]);
+ expect(clipboard.isClipboardEmpty()).toBe(true);
+ expect(toastService.showMessage).not.toHaveBeenCalled();
+ });
+});
+
+describe("isClipboardEmpty", () => {
+ it("filters out branches no longer present in froca", () => {
+ const { childBranchId } = buildParentWithChild();
+
+ clipboard.cut([childBranchId, "does-not-exist"]);
+ expect(clipboard.isClipboardEmpty()).toBe(false);
+
+ clipboard.cut(["does-not-exist-either"]);
+ expect(clipboard.isClipboardEmpty()).toBe(true);
+ });
+});
+
+describe("copy", () => {
+ afterEach(() => {
+ delete (window as any).electronApi;
+ delete (globalThis as any).ClipboardItem;
+ });
+
+ it("sets copy mode and toasts on a non-Electron platform", async () => {
+ const { childBranchId } = buildParentWithChild();
+ expect(utils.isElectron()).toBe(false);
+
+ await clipboard.copy([childBranchId]);
+
+ expect(clipboard.isClipboardEmpty()).toBe(false);
+ expect(toastService.showMessage).toHaveBeenCalledTimes(1);
+ });
+
+ it("writes reference links to the system clipboard on Electron", async () => {
+ const { childBranchId } = buildParentWithChild();
+
+ (window as any).electronApi = {};
+ const writeSpy = vi.fn(async (..._args: any[]) => {});
+ // happy-dom exposes `navigator.clipboard` as a getter-only property, so define our own.
+ Object.defineProperty(navigator, "clipboard", {
+ configurable: true,
+ get: () => ({ write: writeSpy })
+ });
+ (globalThis as any).ClipboardItem = class {
+ constructor(public readonly data: Record<string, unknown>) {}
+ };
+
+ const link = $("<a>").attr("href", "ref").text("Child link");
+ linkService.createLink = vi.fn(async () => link) as typeof linkService.createLink;
+
+ await clipboard.copy([childBranchId]);
+
+ expect(linkService.createLink).toHaveBeenCalledTimes(1);
+ expect(writeSpy).toHaveBeenCalledTimes(1);
+ const items = writeSpy.mock.calls[0][0] as any[];
+ expect(items).toHaveLength(1);
+ expect(items[0].data["text/html"]).toBeInstanceOf(Blob);
+ expect(items[0].data["text/plain"]).toBeInstanceOf(Blob);
+ expect(toastService.showMessage).toHaveBeenCalledTimes(1);
+ });
+});
+
+describe("pasteAfter", () => {
+ it("returns early when the clipboard is empty", async () => {
+ await clipboard.pasteAfter("any-branch");
+ expect(branchService.moveAfterBranch).not.toHaveBeenCalled();
+ expect(branchService.cloneNoteAfter).not.toHaveBeenCalled();
+ });
+
+ it("moves branches and clears the clipboard in cut mode", async () => {
+ const { childBranchId } = buildParentWithChild();
+ clipboard.cut([childBranchId]);
+
+ await clipboard.pasteAfter("target-branch");
+
+ expect(branchService.moveAfterBranch).toHaveBeenCalledWith([childBranchId], "target-branch");
+ // Cut clears the clipboard afterwards.
+ expect(clipboard.isClipboardEmpty()).toBe(true);
+ });
+
+ it("clones the note and keeps the clipboard in copy mode, skipping branches with no note", async () => {
+ const { childBranchId, childNoteId } = buildParentWithChild();
+ // A branch whose note resolves to null exercises the `!clipboardNote` continue.
+ const orphanBranchId = "orphan-branch";
+ froca.branches[orphanBranchId] = {
+ branchId: orphanBranchId,
+ noteId: "missing-note",
+ getNote: async () => null
+ } as any;
+
+ // "missing-branch" is dropped by isClipboardEmpty()'s filter before the clone loop runs.
+ clipboard.copy([childBranchId, "missing-branch", orphanBranchId]);
+ vi.clearAllMocks();
+
+ await clipboard.pasteAfter("target-branch");
+
+ expect(branchService.cloneNoteAfter).toHaveBeenCalledTimes(1);
+ expect(branchService.cloneNoteAfter).toHaveBeenCalledWith(childNoteId, "target-branch");
+ // Copy keeps the clipboard so it can be pasted again.
+ expect(clipboard.isClipboardEmpty()).toBe(false);
+
+ delete froca.branches[orphanBranchId];
+ });
+
+});
+
+describe("pasteInto", () => {
+ it("returns early when the clipboard is empty", async () => {
+ await clipboard.pasteInto("any-branch");
+ expect(branchService.moveToParentNote).not.toHaveBeenCalled();
+ expect(branchService.cloneNoteToBranch).not.toHaveBeenCalled();
+ });
+
+ it("moves branches to the parent and clears the clipboard in cut mode", async () => {
+ const { childBranchId } = buildParentWithChild();
+ clipboard.cut([childBranchId]);
+
+ await clipboard.pasteInto("parent-branch");
+
+ expect(branchService.moveToParentNote).toHaveBeenCalledWith([childBranchId], "parent-branch");
+ expect(clipboard.isClipboardEmpty()).toBe(true);
+ });
+
+ it("clones the note into the parent and keeps the clipboard in copy mode, skipping branches with no note", async () => {
+ const { childBranchId, childNoteId } = buildParentWithChild();
+ const orphanBranchId = "orphan-branch-into";
+ froca.branches[orphanBranchId] = {
+ branchId: orphanBranchId,
+ noteId: "missing-note",
+ getNote: async () => null
+ } as any;
+
+ clipboard.copy([childBranchId, "missing-branch", orphanBranchId]);
+ vi.clearAllMocks();
+
+ await clipboard.pasteInto("parent-branch");
+
+ expect(branchService.cloneNoteToBranch).toHaveBeenCalledTimes(1);
+ expect(branchService.cloneNoteToBranch).toHaveBeenCalledWith(childNoteId, "parent-branch");
+ expect(clipboard.isClipboardEmpty()).toBe(false);
+
+ delete froca.branches[orphanBranchId];
+ });
+});
diff --git a/apps/client/src/services/clipboard.ts b/apps/client/src/services/clipboard.ts
index 741e2c4c60..0f3569b3d4 100644
--- a/apps/client/src/services/clipboard.ts
+++ b/apps/client/src/services/clipboard.ts
@@ -23,6 +23,7 @@ async function pasteAfter(afterBranchId: string) {
const clipboardBranches = clipboardBranchIds.map((branchId) => froca.getBranch(branchId));
for (const clipboardBranch of clipboardBranches) {
+ /* v8 ignore next 3 -- isClipboardEmpty() already filtered out non-existent branches, so this is defensive */
if (!clipboardBranch) {
continue;
}
@@ -36,9 +37,11 @@ async function pasteAfter(afterBranchId: string) {
}
// copy will keep clipboardBranchIds and clipboardMode, so it's possible to paste into multiple places
+ /* v8 ignore start -- clipboardMode is only ever set to "cut"/"copy" while the clipboard is non-empty */
} else {
throwError(`Unrecognized clipboard mode=${clipboardMode}`);
}
+ /* v8 ignore stop */
}
async function pasteInto(parentBranchId: string) {
@@ -55,6 +58,7 @@ async function pasteInto(parentBranchId: string) {
const clipboardBranches = clipboardBranchIds.map((branchId) => froca.getBranch(branchId));
for (const clipboardBranch of clipboardBranches) {
+ /* v8 ignore next 3 -- isClipboardEmpty() already filtered out non-existent branches, so this is defensive */
if (!clipboardBranch) {
continue;
}
@@ -68,9 +72,11 @@ async function pasteInto(parentBranchId: string) {
}
// copy will keep clipboardBranchIds and clipboardMode, so it's possible to paste into multiple places
+ /* v8 ignore start -- clipboardMode is only ever set to "cut"/"copy" while the clipboard is non-empty */
} else {
throwError(`Unrecognized clipboard mode=${clipboardMode}`);
}
+ /* v8 ignore stop */
}
async function copy(branchIds: string[]) {
diff --git a/apps/client/src/services/clipboard_ext.spec.ts b/apps/client/src/services/clipboard_ext.spec.ts
new file mode 100644
index 0000000000..7c00adfcf3
--- /dev/null
+++ b/apps/client/src/services/clipboard_ext.spec.ts
@@ -0,0 +1,105 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+import toast from "./toast.js";
+import { copyText, copyTextWithToast } from "./clipboard_ext.js";
+
+const originalClipboard = Object.getOwnPropertyDescriptor(navigator, "clipboard");
+
+function setClipboard(value: unknown) {
+ Object.defineProperty(navigator, "clipboard", {
+ value,
+ configurable: true,
+ writable: true
+ });
+}
+
+afterEach(() => {
+ vi.restoreAllMocks();
+ if (originalClipboard) {
+ Object.defineProperty(navigator, "clipboard", originalClipboard);
+ } else {
+ setClipboard(undefined);
+ }
+ document.body.innerHTML = "";
+});
+
+describe("copyText", () => {
+ it("returns undefined for empty text without touching the clipboard", () => {
+ const writeText = vi.fn();
+ setClipboard({ writeText });
+
+ expect(copyText("")).toBeUndefined();
+ expect(writeText).not.toHaveBeenCalled();
+ });
+
+ it("uses navigator.clipboard.writeText when available and returns true", () => {
+ const writeText = vi.fn();
+ setClipboard({ writeText });
+
+ expect(copyText("hello")).toBe(true);
+ expect(writeText).toHaveBeenCalledWith("hello");
+ });
+
+ it("falls back to execCommand when navigator.clipboard is unavailable", () => {
+ setClipboard(undefined);
+
+ let capturedValue: string | undefined;
+ const execCommand = vi.fn((command: string) => {
+ // The textarea must still be attached when copy runs.
+ const textArea = document.querySelector("textarea");
+ capturedValue = textArea?.value;
+ return command === "copy";
+ });
+ (document as unknown as { execCommand: typeof execCommand }).execCommand = execCommand;
+
+ expect(copyText("fallback-text")).toBe(true);
+ expect(execCommand).toHaveBeenCalledWith("copy");
+ expect(capturedValue).toBe("fallback-text");
+ // The textarea is removed in the finally block.
+ expect(document.querySelector("textarea")).toBeNull();
+ });
+
+ it("returns false and warns when the fallback throws", () => {
+ setClipboard(undefined);
+
+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
+ const error = new Error("execCommand failed");
+ (document as unknown as { execCommand: () => never }).execCommand = () => {
+ throw error;
+ };
+
+ expect(copyText("boom")).toBe(false);
+ expect(warn).toHaveBeenCalledWith(error);
+ // The textarea is still cleaned up despite the throw.
+ expect(document.querySelector("textarea")).toBeNull();
+ });
+});
+
+describe("copyTextWithToast", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it("shows a success message when the copy succeeds", () => {
+ setClipboard({ writeText: vi.fn() });
+ const showMessage = vi.spyOn(toast, "showMessage").mockImplementation(() => {});
+ const showError = vi.spyOn(toast, "showError").mockImplementation(() => {});
+
+ copyTextWithToast("yay");
+
+ expect(showMessage).toHaveBeenCalledTimes(1);
+ expect(showError).not.toHaveBeenCalled();
+ });
+
+ it("shows an error message when the copy fails", () => {
+ setClipboard(undefined);
+ (document as unknown as { execCommand: () => boolean }).execCommand = () => false;
+ const showMessage = vi.spyOn(toast, "showMessage").mockImplementation(() => {});
+ const showError = vi.spyOn(toast, "showError").mockImplementation(() => {});
+
+ copyTextWithToast("nope");
+
+ expect(showError).toHaveBeenCalledTimes(1);
+ expect(showMessage).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/client/src/services/command_registry.spec.ts b/apps/client/src/services/command_registry.spec.ts
new file mode 100644
index 0000000000..7950078561
--- /dev/null
+++ b/apps/client/src/services/command_registry.spec.ts
@@ -0,0 +1,429 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+import type { ActionKeyboardShortcut } from "@triliumnext/commons";
+
+// ---- Mocks -----------------------------------------------------------------
+// vi.hoisted lets these shared spies exist before the hoisted vi.mock factories.
+const {
+ triggerCommand,
+ getComponentByEl,
+ getActiveContextNotePath,
+ getActiveContext,
+ getActions,
+ isElectron
+} = vi.hoisted(() => ({
+ triggerCommand: vi.fn(),
+ getComponentByEl: vi.fn(),
+ getActiveContextNotePath: vi.fn<() => string | null | undefined>(() => "root/abc"),
+ getActiveContext: vi.fn(),
+ getActions: vi.fn<() => Promise<ActionKeyboardShortcut[]>>(async () => []),
+ isElectron: vi.fn(() => false)
+}));
+
+// translationsInitializedPromise must be already-resolved so the registry's
+// async loadCommands() proceeds. t() is made a deterministic stub.
+vi.mock("./i18n.js", () => ({
+ translationsInitializedPromise: Promise.resolve(),
+ t: (key: string, opts?: Record<string, unknown>) =>
+ opts && "name" in opts ? `${key}:${opts.name}` : key
+}));
+
+vi.mock("../components/app_context.js", () => ({
+ default: {
+ triggerCommand,
+ getComponentByEl,
+ tabManager: {
+ activeNtxId: "ntx-1",
+ getActiveContextNotePath,
+ getActiveContext
+ }
+ }
+}));
+
+vi.mock("./keyboard_actions.js", () => ({
+ default: { getActions }
+}));
+
+vi.mock("./utils.js", () => ({
+ default: { isElectron }
+}));
+
+// Imported AFTER the mocks (vi.mock is hoisted).
+import { CommandRegistry } from "./command_registry.js";
+
+/** Build a fresh registry and wait for its async loadCommands() to settle. */
+async function freshRegistry() {
+ const registry = new CommandRegistry();
+ // Flush the microtask/macrotask queue so the fire-and-forget constructor
+ // promise chain (translations -> default commands -> keyboard actions) runs.
+ await new Promise((r) => setTimeout(r, 0));
+ return registry;
+}
+
+function action(overrides: Partial<Record<keyof ActionKeyboardShortcut, unknown>>): ActionKeyboardShortcut {
+ return {
+ actionName: "someAction",
+ friendlyName: "Some Action",
+ description: "Does something",
+ ...overrides
+ } as ActionKeyboardShortcut;
+}
+
+afterEach(() => {
+ vi.clearAllMocks();
+ getActions.mockImplementation(async () => []);
+ isElectron.mockImplementation(() => false);
+ getActiveContextNotePath.mockImplementation(() => "root/abc");
+});
+
+describe("CommandRegistry default commands", () => {
+ it("registers all default commands after translations resolve", async () => {
+ const registry = await freshRegistry();
+ const ids = registry.getAllCommands().map((c) => c.id);
+ expect(ids).toEqual(
+ expect.arrayContaining([
+ "export-note",
+ "show-attachments",
+ "search-notes",
+ "search-in-subtree",
+ "show-search-history",
+ "show-launch-bar"
+ ])
+ );
+ // getAllCommands returns a name-sorted list.
+ const names = registry.getAllCommands().map((c) => c.name);
+ expect([...names].sort((a, b) => a.localeCompare(b))).toEqual(names);
+ });
+
+ it("default command handlers trigger the right app commands", async () => {
+ const registry = await freshRegistry();
+
+ await registry.executeCommand("export-note");
+ expect(triggerCommand).toHaveBeenCalledWith("showExportDialog", {
+ notePath: "root/abc",
+ defaultType: "single"
+ });
+
+ await registry.executeCommand("show-attachments");
+ expect(triggerCommand).toHaveBeenCalledWith("showAttachments");
+
+ await registry.executeCommand("search-notes");
+ expect(triggerCommand).toHaveBeenCalledWith("searchNotes", {});
+
+ await registry.executeCommand("search-in-subtree");
+ expect(triggerCommand).toHaveBeenCalledWith("searchInSubtree", { notePath: "root/abc" });
+
+ await registry.executeCommand("show-search-history");
+ expect(triggerCommand).toHaveBeenCalledWith("showSearchHistory");
+
+ await registry.executeCommand("show-launch-bar");
+ expect(triggerCommand).toHaveBeenCalledWith("showLaunchBarSubtree");
+ });
+
+ it("export-note and search-in-subtree skip triggering when there is no active note path", async () => {
+ const registry = await freshRegistry();
+ getActiveContextNotePath.mockImplementation(() => null);
+
+ await registry.executeCommand("export-note");
+ await registry.executeCommand("search-in-subtree");
+ expect(triggerCommand).not.toHaveBeenCalled();
+ });
+});
+
+describe("CommandRegistry keyboard actions", () => {
+ it("registers eligible keyboard actions, formatting shortcuts and tree-scoped names", async () => {
+ getActions.mockImplementation(async () => [
+ action({
+ actionName: "newAction",
+ friendlyName: "New Action",
+ iconClass: "bx bx-plus",
+ effectiveShortcuts: ["CommandOrControl+N", "Alt+X"]
+ }),
+ action({
+ actionName: "treeAction",
+ friendlyName: "Tree Action",
+ scope: "note-tree"
+ })
+ ]);
+
+ const registry = await freshRegistry();
+
+ const newCmd = registry.getCommand("newAction")!;
+ expect(newCmd.source).toBe("keyboard-action");
+ expect(newCmd.commandName).toBe("newAction");
+ // formatShortcut: CommandOrControl -> Ctrl, + -> " + "
+ expect(newCmd.shortcut).toBe("Ctrl + N");
+
+ const treeCmd = registry.getCommand("treeAction")!;
+ // note-tree scope wraps the name with the tree-action-name translation key
+ expect(treeCmd.name).toBe("command_palette.tree-action-name:Tree Action");
+ });
+
+ it("skips already-registered, description-less, electron-only and ignored actions", async () => {
+ getActions.mockImplementation(async () => [
+ // Collides with a manually-registered default command id -> skipped.
+ action({ actionName: "export-note" }),
+ // No description -> skipped.
+ action({ actionName: "noDesc", description: undefined }),
+ // Electron-only while not in electron -> skipped.
+ action({ actionName: "electronOnly", isElectronOnly: true }),
+ // Explicitly ignored -> skipped.
+ action({ actionName: "ignored", ignoreFromCommandPalette: true }),
+ // No shortcut at all -> registered, shortcut undefined.
+ action({ actionName: "noShortcut", effectiveShortcuts: [] })
+ ]);
+
+ const registry = await freshRegistry();
+
+ // export-note stays the manually-registered command (has a handler).
+ expect(registry.getCommand("export-note")!.handler).toBeTypeOf("function");
+ expect(registry.getCommand("noDesc")).toBeUndefined();
+ expect(registry.getCommand("electronOnly")).toBeUndefined();
+ expect(registry.getCommand("ignored")).toBeUndefined();
+
+ const noShortcut = registry.getCommand("noShortcut")!;
+ expect(noShortcut.shortcut).toBeUndefined();
+ });
+
+ it("registers electron-only actions when running under electron", async () => {
+ isElectron.mockImplementation(() => true);
+ getActions.mockImplementation(async () => [
+ action({ actionName: "electronOnly", isElectronOnly: true })
+ ]);
+
+ const registry = await freshRegistry();
+ expect(registry.getCommand("electronOnly")).toBeDefined();
+ });
+
+ it("logs an error when loading keyboard actions fails", async () => {
+ const consoleError = vi.spyOn(console, "error").mockImplementation(() => {});
+ getActions.mockImplementation(async () => {
+ throw new Error("boom");
+ });
+
+ await freshRegistry();
+ expect(consoleError).toHaveBeenCalledWith("Failed to load keyboard actions:", expect.any(Error));
+ consoleError.mockRestore();
+ });
+});
+
+describe("CommandRegistry register & aliases", () => {
+ let registry: CommandRegistry;
+ beforeEach(async () => {
+ registry = await freshRegistry();
+ });
+
+ it("stores commands and lowercases registered aliases", () => {
+ registry.register({ id: "custom", name: "Custom", aliases: ["FooBar", "baz"] });
+ expect(registry.getCommand("custom")!.name).toBe("Custom");
+ // Aliases are matched case-insensitively in search.
+ expect(registry.searchCommands("foobar").map((c) => c.id)).toContain("custom");
+ });
+
+ it("getCommand returns undefined for unknown ids", () => {
+ expect(registry.getCommand("does-not-exist")).toBeUndefined();
+ });
+});
+
+describe("CommandRegistry searchCommands scoring", () => {
+ let registry: CommandRegistry;
+ beforeEach(async () => {
+ registry = await freshRegistry();
+ registry.register({ id: "alpha", name: "Alpha", description: "first letter" });
+ registry.register({ id: "alphabet", name: "Alphabet soup" });
+ registry.register({ id: "zeta", name: "Zeta", description: "contains alpha word" });
+ registry.register({ id: "aliased", name: "Totally unrelated", aliases: ["alphakeyword"] });
+ });
+
+ it("ranks exact > starts-with > contains, and orders ties by name", () => {
+ const ids = registry.searchCommands("alpha").map((c) => c.id);
+ // "Alpha" exact (100) first; "Alphabet soup" starts-with (80); then
+ // description contains (40) for "first letter"? no — that doesn't match.
+ // "Zeta" matches via description contains "alpha" (40); "aliased" via alias (50).
+ expect(ids[0]).toBe("alpha");
+ expect(ids[1]).toBe("alphabet");
+ // alias match (50) ranks above description match (40)
+ expect(ids.indexOf("aliased")).toBeLessThan(ids.indexOf("zeta"));
+ });
+
+ it("name-contains beats description-contains", () => {
+ registry.register({ id: "mid", name: "xxAlphaxx" });
+ const ids = registry.searchCommands("alpha").map((c) => c.id);
+ expect(ids.indexOf("mid")).toBeLessThan(ids.indexOf("zeta"));
+ });
+
+ it("returns empty for a query that matches nothing", () => {
+ expect(registry.searchCommands("zzz-no-match-zzz")).toEqual([]);
+ });
+
+ it("breaks score ties alphabetically by name", () => {
+ // Both start with "tie" -> identical score (80); ordered by name.
+ registry.register({ id: "tieB", name: "Tie Bravo" });
+ registry.register({ id: "tieA", name: "Tie Alpha" });
+ const ids = registry.searchCommands("tie").map((c) => c.id);
+ const a = ids.indexOf("tieA");
+ const b = ids.indexOf("tieB");
+ expect(a).toBeGreaterThanOrEqual(0);
+ expect(b).toBeGreaterThan(a);
+ });
+});
+
+describe("CommandRegistry executeCommand", () => {
+ let registry: CommandRegistry;
+ beforeEach(async () => {
+ registry = await freshRegistry();
+ });
+
+ it("logs an error for an unknown command", async () => {
+ const consoleError = vi.spyOn(console, "error").mockImplementation(() => {});
+ await registry.executeCommand("nope");
+ expect(consoleError).toHaveBeenCalledWith("Command not found: nope");
+ expect(triggerCommand).not.toHaveBeenCalled();
+ consoleError.mockRestore();
+ });
+
+ it("logs an error for a command with neither handler nor commandName", async () => {
+ const consoleError = vi.spyOn(console, "error").mockImplementation(() => {});
+ registry.register({ id: "empty", name: "Empty" });
+ await registry.executeCommand("empty");
+ expect(consoleError).toHaveBeenCalledWith("Command empty has no handler or commandName");
+ consoleError.mockRestore();
+ });
+
+ it("triggers commandName with active ntxId when there is no keyboard action", async () => {
+ registry.register({
+ id: "plainCmd",
+ name: "Plain",
+ commandName: "showOptions" as never
+ });
+ await registry.executeCommand("plainCmd");
+ expect(triggerCommand).toHaveBeenCalledWith("showOptions", { ntxId: "ntx-1" });
+ });
+
+ it("triggers commandName with active ntxId for a window-scoped keyboard action", async () => {
+ registry.register({
+ id: "winCmd",
+ name: "Window",
+ commandName: "showOptions" as never,
+ keyboardAction: action({ scope: "window" })
+ });
+ await registry.executeCommand("winCmd");
+ expect(triggerCommand).toHaveBeenCalledWith("showOptions", { ntxId: "ntx-1" });
+ });
+
+ it("note-tree scoped action triggers on the tree component with the active node", async () => {
+ const tree = document.createElement("div");
+ tree.className = "tree-wrapper";
+ document.body.appendChild(tree);
+
+ const treeTrigger = vi.fn();
+ const getActiveNode = vi.fn(() => ({ key: "node-1" }));
+ getComponentByEl.mockReturnValue({ getActiveNode, triggerCommand: treeTrigger });
+
+ registry.register({
+ id: "treeCmd",
+ name: "Tree",
+ commandName: "deleteNotes" as never,
+ keyboardAction: action({ scope: "note-tree" })
+ });
+ await registry.executeCommand("treeCmd");
+
+ expect(getComponentByEl).toHaveBeenCalledWith(tree);
+ expect(treeTrigger).toHaveBeenCalledWith("deleteNotes", {
+ ntxId: "ntx-1",
+ node: { key: "node-1" }
+ });
+ tree.remove();
+ });
+
+ it("note-tree scoped action does nothing when the tree element is absent", async () => {
+ // Ensure no .tree-wrapper element exists.
+ document.querySelectorAll(".tree-wrapper").forEach((el) => el.remove());
+
+ registry.register({
+ id: "treeCmd2",
+ name: "Tree2",
+ commandName: "deleteNotes" as never,
+ keyboardAction: action({ scope: "note-tree" })
+ });
+ await registry.executeCommand("treeCmd2");
+ expect(getComponentByEl).not.toHaveBeenCalled();
+ });
+
+ it("text-detail scoped action triggers on the active type widget", async () => {
+ const widgetTrigger = vi.fn();
+ getActiveContext.mockReturnValue({
+ getTypeWidget: async () => ({ triggerCommand: widgetTrigger })
+ });
+
+ registry.register({
+ id: "textCmd",
+ name: "Text",
+ commandName: "addLinkToText" as never,
+ keyboardAction: action({ scope: "text-detail" })
+ });
+ await registry.executeCommand("textCmd");
+ expect(widgetTrigger).toHaveBeenCalledWith("addLinkToText", { ntxId: "ntx-1" });
+ });
+
+ it("text-detail scoped action does nothing when there is no type widget", async () => {
+ getActiveContext.mockReturnValue({ getTypeWidget: async () => null });
+
+ registry.register({
+ id: "textCmd2",
+ name: "Text2",
+ commandName: "addLinkToText" as never,
+ keyboardAction: action({ scope: "text-detail" })
+ });
+ await registry.executeCommand("textCmd2");
+ expect(triggerCommand).not.toHaveBeenCalled();
+ });
+
+ it("text-detail scoped action does nothing when there is no active context", async () => {
+ getActiveContext.mockReturnValue(undefined);
+
+ registry.register({
+ id: "textCmd3",
+ name: "Text3",
+ commandName: "addLinkToText" as never,
+ keyboardAction: action({ scope: "text-detail" })
+ });
+ await registry.executeCommand("textCmd3");
+ expect(triggerCommand).not.toHaveBeenCalled();
+ });
+
+ it("prefers a custom handler over keyboardAction/commandName", async () => {
+ const handler = vi.fn(async () => {});
+ registry.register({
+ id: "handlerCmd",
+ name: "Handler",
+ commandName: "showOptions" as never,
+ keyboardAction: action({ scope: "window" }),
+ handler
+ });
+ await registry.executeCommand("handlerCmd");
+ expect(handler).toHaveBeenCalledTimes(1);
+ expect(triggerCommand).not.toHaveBeenCalled();
+ });
+
+ it("keyboardAction without a commandName falls through to the commandName fallback", async () => {
+ // keyboardAction present but commandName missing -> the keyboardAction
+ // block is skipped (needs both); no commandName -> error path.
+ const consoleError = vi.spyOn(console, "error").mockImplementation(() => {});
+ registry.register({
+ id: "kbNoName",
+ name: "KbNoName",
+ keyboardAction: action({ scope: "window" })
+ });
+ await registry.executeCommand("kbNoName");
+ expect(consoleError).toHaveBeenCalledWith("Command kbNoName has no handler or commandName");
+ consoleError.mockRestore();
+ });
+});
+
+describe("command_registry singleton", () => {
+ it("exports a default singleton instance", async () => {
+ const mod = await import("./command_registry.js");
+ expect(mod.default).toBeInstanceOf(CommandRegistry);
+ });
+});
diff --git a/apps/client/src/services/command_registry.ts b/apps/client/src/services/command_registry.ts
index f0bb2eef59..2e696d083f 100644
--- a/apps/client/src/services/command_registry.ts
+++ b/apps/client/src/services/command_registry.ts
@@ -19,7 +19,7 @@ export interface CommandDefinition {
keyboardAction?: ActionKeyboardShortcut;
}
-class CommandRegistry {
+export class CommandRegistry {
private commands: Map<string, CommandDefinition> = new Map();
private aliases: Map<string, string> = new Map();
diff --git a/apps/client/src/services/content_renderer.spec.ts b/apps/client/src/services/content_renderer.spec.ts
new file mode 100644
index 0000000000..bf3b5018e8
--- /dev/null
+++ b/apps/client/src/services/content_renderer.spec.ts
@@ -0,0 +1,521 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+// --- Mock heavy / side-effecting collaborators BEFORE importing the SUT. ---
+// content_renderer_text: renderText / postProcessRichContent / renderChildrenList
+const renderText = vi.fn(async (...args: any[]) => {
+ args[1].append($('<div class="from-render-text">'));
+});
+const postProcessRichContent = vi.fn(async (..._args: any[]) => {});
+const renderChildrenList = vi.fn(async (..._args: any[]) => {});
+vi.mock("./content_renderer_text.js", () => ({
+ default: (...args: any[]) => renderText(...args),
+ postProcessRichContent: (...args: any[]) => postProcessRichContent(...args),
+ renderChildrenList: (...args: any[]) => renderChildrenList(...args)
+}));
+
+const renderDoc = vi.fn(async (..._args: any[]) => $('<div class="doc-html"><span>doc</span></div>'));
+vi.mock("./doc_renderer.js", () => ({ default: (...args: any[]) => renderDoc(...args) }));
+
+const renderServiceRender = vi.fn(async (...args: any[]) => {
+ args[1].append($('<div class="render-ok">'));
+});
+vi.mock("./render.js", () => ({ default: { render: (...args: any[]) => renderServiceRender(...args) } }));
+
+const applySingleBlockSyntaxHighlight = vi.fn(async (..._args: any[]) => {});
+vi.mock("./syntax_highlight.js", () => ({
+ applySingleBlockSyntaxHighlight: (...args: any[]) => applySingleBlockSyntaxHighlight(...args)
+}));
+
+const setupContextMenu = vi.fn((..._args: any[]) => {});
+vi.mock("../menus/image_context_menu.js", () => ({ default: { setupContextMenu: (...a: any[]) => setupContextMenu(...a) } }));
+
+const wheelZoomCreate = vi.fn((..._args: any[]) => {});
+vi.mock("vanilla-js-wheel-zoom", () => ({ default: { create: (...a: any[]) => wheelZoomCreate(...a) } }));
+
+const enterProtectedSession = vi.fn((..._args: any[]) => {});
+vi.mock("./protected_session.js", () => ({ default: { enterProtectedSession: (...a: any[]) => enterProtectedSession(...a) } }));
+
+const isProtectedSessionAvailable = vi.fn(() => false);
+const touchProtectedSession = vi.fn((..._args: any[]) => {});
+vi.mock("./protected_session_holder.js", () => ({
+ default: {
+ isProtectedSessionAvailable: () => isProtectedSessionAvailable(),
+ touchProtectedSession: () => touchProtectedSession()
+ }
+}));
+
+const getUrlForDownload = vi.fn((...args: any[]) => `DL:${args[0]}`);
+const downloadFileNote = vi.fn((..._args: any[]) => {});
+const openNoteExternally = vi.fn(async (..._args: any[]) => {});
+vi.mock("./open.js", () => ({
+ default: {
+ getUrlForDownload: (...a: any[]) => getUrlForDownload(...a),
+ downloadFileNote: (...a: any[]) => downloadFileNote(...a),
+ openNoteExternally: (...a: any[]) => openNoteExternally(...a)
+ }
+}));
+
+const loadElkIfNeeded = vi.fn(async (..._args: any[]) => {});
+const postprocessMermaidSvg = vi.fn((...args: any[]) => `<svg class="mm">${args[0]}</svg>`);
+vi.mock("./mermaid.js", () => ({
+ loadElkIfNeeded: (...a: any[]) => loadElkIfNeeded(...a),
+ postprocessMermaidSvg: (...a: any[]) => postprocessMermaidSvg(...a)
+}));
+
+const mermaidRender = vi.fn(async (..._args: any[]) => ({ svg: "<g/>" }));
+const mermaidInitialize = vi.fn((..._args: any[]) => {});
+vi.mock("mermaid", () => ({
+ default: { mermaidAPI: { initialize: (...a: any[]) => mermaidInitialize(...a), render: (...a: any[]) => mermaidRender(...a) } }
+}));
+
+const pdfViewerComponent = vi.fn(() => null);
+vi.mock("../widgets/type_widgets/file/PdfViewer", () => ({ default: pdfViewerComponent }));
+
+vi.mock("dompurify", () => ({ default: { sanitize: (s: string) => s } }));
+
+const renderToHtml = vi.fn((...args: any[]) => `<p>${args[0]}</p>`);
+vi.mock("@triliumnext/commons", async (orig) => ({
+ ...(await (orig() as Promise<object>)),
+ renderToHtml: (...a: any[]) => renderToHtml(...a)
+}));
+
+// --- Imports AFTER the mocks. ---
+import FAttachment from "../entities/fattachment.js";
+import { buildNote } from "../test/easy-froca.js";
+import froca from "./froca.js";
+import { getRenderedContent as rawGetRenderedContent } from "./content_renderer.js";
+import server from "./server.js";
+
+// getRenderedContent declares an explicit `this` parameter; bind it so callers don't need to.
+const getRenderedContent = (...args: Parameters<typeof rawGetRenderedContent>) => rawGetRenderedContent.call({}, ...args);
+
+function buildAttachment(row: Partial<ConstructorParameters<typeof FAttachment>[1]> = {}) {
+ const att = new FAttachment(froca as any, {
+ attachmentId: Math.random().toString(36).slice(2),
+ ownerId: "owner",
+ role: "image",
+ mime: "image/png",
+ title: "att",
+ dateModified: new Date().toISOString(),
+ utcDateModified: new Date().toISOString(),
+ utcDateScheduledForErasureSince: "",
+ contentLength: 0,
+ ...row
+ } as any);
+ return att;
+}
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ isProtectedSessionAvailable.mockReturnValue(false);
+ (window as any).electronApi = undefined;
+});
+
+describe("getRenderedContent dispatch", () => {
+ it("renders text/book via renderText and applies css class", async () => {
+ const note = buildNote({ title: "T", type: "text", "#cssClass": "my-class" });
+ const { $renderedContent, type } = await getRenderedContent(note);
+ expect(type).toBe("text");
+ expect(renderText).toHaveBeenCalledOnce();
+ expect($renderedContent.hasClass("rendered-content")).toBe(true);
+ expect($renderedContent.hasClass("my-class")).toBe(true);
+ expect($renderedContent.find(".from-render-text").length).toBe(1);
+
+ const book = buildNote({ title: "B", type: "book" });
+ expect((await getRenderedContent(book)).type).toBe("book");
+ expect(renderText).toHaveBeenCalledTimes(2);
+ });
+
+ it("renders markdown with content through renderToHtml + postProcess", async () => {
+ const note = buildNote({ title: "Doc", type: "code", content: "# Hi" });
+ note.mime = "text/markdown";
+ const { type, $renderedContent } = await getRenderedContent(note);
+ expect(type).toBe("markdown");
+ expect(renderToHtml).toHaveBeenCalledWith("# Hi", "Doc", expect.anything());
+ expect($renderedContent.find(".ck-content").html()).toContain("<p># Hi</p>");
+ expect(postProcessRichContent).toHaveBeenCalledOnce();
+ // exercise the formatHref + sanitize callbacks passed to renderToHtml
+ const opts = renderToHtml.mock.calls[0][2] as any;
+ expect(opts.wikiLink.formatHref("abc")).toBe("#root/abc");
+ expect(opts.sanitize("<b>x</b>")).toBe("<b>x</b>");
+ });
+
+ it("treats a markdown note with a null blob as empty", async () => {
+ const note = buildNote({ title: "NullBlob", type: "code" });
+ note.mime = "text/markdown";
+ note.getBlob = (async () => null) as any;
+ await getRenderedContent(note);
+ expect(renderToHtml).not.toHaveBeenCalled();
+ expect(renderChildrenList).toHaveBeenCalledOnce();
+ });
+
+ it("renders empty markdown as a children list (FNote, not noChildrenList)", async () => {
+ const note = buildNote({ title: "Empty", type: "code", content: " " });
+ note.mime = "text/markdown";
+ await getRenderedContent(note);
+ expect(renderToHtml).not.toHaveBeenCalled();
+ expect(renderChildrenList).toHaveBeenCalledOnce();
+ expect(renderChildrenList).toHaveBeenCalledWith(expect.anything(), note, false);
+ });
+
+ it("empty markdown with noChildrenList skips the children list", async () => {
+ const note = buildNote({ title: "Empty2", type: "code", content: "" });
+ note.mime = "text/markdown";
+ await getRenderedContent(note, { noChildrenList: true });
+ expect(renderChildrenList).not.toHaveBeenCalled();
+ });
+
+ it("empty markdown honors includeArchivedNotes flag", async () => {
+ const note = buildNote({ title: "Empty3", type: "code", content: "" });
+ note.mime = "text/markdown";
+ await getRenderedContent(note, { includeArchivedNotes: true });
+ expect(renderChildrenList).toHaveBeenCalledWith(expect.anything(), note, true);
+ });
+});
+
+describe("getRenderedContent code rendering", () => {
+ it("pretty-prints valid JSON code notes", async () => {
+ const note = buildNote({ title: "J", type: "code", content: '{"a":1}' });
+ note.mime = "application/json";
+ const { type, $renderedContent } = await getRenderedContent(note);
+ expect(type).toBe("code");
+ expect($renderedContent.find("pre > code").text()).toBe('{\n "a": 1\n}');
+ expect(applySingleBlockSyntaxHighlight).toHaveBeenCalledOnce();
+ });
+
+ it("leaves invalid JSON untouched", async () => {
+ const note = buildNote({ title: "JBad", type: "code", content: "{not json" });
+ note.mime = "application/json";
+ const { $renderedContent } = await getRenderedContent(note);
+ expect($renderedContent.find("code").text()).toBe("{not json");
+ });
+
+ it("renders non-JSON code with empty content fallback", async () => {
+ const note = buildNote({ title: "C", type: "code", content: "" });
+ note.mime = "text/x-csrc";
+ const { $renderedContent } = await getRenderedContent(note);
+ expect($renderedContent.find("code").text()).toBe("");
+ });
+});
+
+describe("getRenderedContent image rendering", () => {
+ it("renders an FNote image with an api/images url", async () => {
+ const note = buildNote({ title: "Pic", type: "image" });
+ const { type, $renderedContent } = await getRenderedContent(note);
+ expect(type).toBe("image");
+ const $img = $renderedContent.find("img");
+ expect($img.attr("src")).toContain(`api/images/${note.noteId}/`);
+ expect($img.attr("id")).toMatch(/^attachment-image-\d+$/);
+ expect(setupContextMenu).toHaveBeenCalledOnce();
+ expect(wheelZoomCreate).not.toHaveBeenCalled();
+ });
+
+ it("renders an FAttachment image with an api/attachments url", async () => {
+ const att = buildAttachment({ role: "image" });
+ const { type, $renderedContent } = await getRenderedContent(att);
+ expect(type).toBe("image");
+ expect($renderedContent.find("img").attr("src")).toContain(`api/attachments/${att.attachmentId}/image/`);
+ });
+
+ it("initializes wheel zoom when imageHasZoom is set and the element is present", async () => {
+ const note = buildNote({ title: "Zoom", type: "canvas" });
+ const { $renderedContent } = await getRenderedContent(note, { imageHasZoom: true });
+ // the img must be attached to the live DOM so document.querySelector finds it
+ document.body.append($renderedContent[0]);
+ await new Promise((r) => requestAnimationFrame(() => r(null)));
+ await new Promise((r) => setTimeout(r, 0));
+ expect(wheelZoomCreate).toHaveBeenCalled();
+ $renderedContent.remove();
+ });
+
+ it("retries via requestAnimationFrame while the element is missing", async () => {
+ const rafSpy = vi.spyOn(window, "requestAnimationFrame");
+ const note = buildNote({ title: "ZoomMiss", type: "mindMap" });
+ // Do NOT attach to the DOM, so querySelector returns null and it reschedules.
+ await getRenderedContent(note, { imageHasZoom: true });
+ await new Promise((r) => setTimeout(r, 0));
+ expect(rafSpy).toHaveBeenCalled();
+ expect(wheelZoomCreate).not.toHaveBeenCalled();
+ rafSpy.mockRestore();
+ });
+
+ it("appends OCR text for FNote images when showTextRepresentation and OCR succeeds", async () => {
+ const note = buildNote({ title: "OcrPic", type: "spreadsheet" });
+ server.get = vi.fn(async () => ({ success: true, hasOcr: true, text: "hello-ocr" })) as typeof server.get;
+ const { $renderedContent } = await getRenderedContent(note, { showTextRepresentation: true });
+ expect(server.get).toHaveBeenCalledWith(`ocr/notes/${note.noteId}/text`);
+ expect($renderedContent.find(".ocr-content").text()).toBe("hello-ocr");
+ });
+
+ it("omits OCR section when the OCR response is unsuccessful", async () => {
+ const note = buildNote({ title: "OcrNo", type: "image" });
+ server.get = vi.fn(async () => ({ success: false, hasOcr: false, text: "" })) as typeof server.get;
+ const { $renderedContent } = await getRenderedContent(note, { showTextRepresentation: true });
+ expect($renderedContent.find(".ocr-content").length).toBe(0);
+ });
+
+ it("swallows OCR fetch errors", async () => {
+ const note = buildNote({ title: "OcrErr", type: "image" });
+ const debugSpy = vi.spyOn(console, "debug").mockImplementation(() => {});
+ server.get = vi.fn(async () => { throw new Error("boom"); }) as typeof server.get;
+ const { $renderedContent } = await getRenderedContent(note, { showTextRepresentation: true });
+ expect($renderedContent.find(".ocr-content").length).toBe(0);
+ expect(debugSpy).toHaveBeenCalled();
+ debugSpy.mockRestore();
+ });
+
+ it("does not fetch OCR for attachments even with showTextRepresentation", async () => {
+ const att = buildAttachment({ role: "image" });
+ server.get = vi.fn(async () => ({ success: true, hasOcr: true, text: "x" })) as typeof server.get;
+ await getRenderedContent(att, { showTextRepresentation: true });
+ expect(server.get).not.toHaveBeenCalledWith(expect.stringContaining("ocr/"));
+ });
+});
+
+describe("getRenderedContent file rendering", () => {
+ it("renders a pdf note with a viewer, download and open buttons", async () => {
+ const note = buildNote({ title: "P", type: "file" });
+ note.mime = "application/pdf";
+ const { type, $renderedContent } = await getRenderedContent(note);
+ expect(type).toBe("pdf");
+ expect(pdfViewerComponent).toHaveBeenCalled();
+ expect($renderedContent.find(".file-download").length).toBe(1);
+ const $open = $renderedContent.find(".file-open");
+ expect($open.length).toBe(1);
+
+ // exercise the click handlers
+ $renderedContent.find(".file-download").trigger("click");
+ expect(downloadFileNote).toHaveBeenCalledWith(note, null, null);
+ await $open.trigger("click");
+ expect(openNoteExternally).toHaveBeenCalledWith(note.noteId, note.mime);
+ });
+
+ it("does not render file when tooltip option is set", async () => {
+ const note = buildNote({ title: "PT", type: "file" });
+ note.mime = "application/pdf";
+ const { $renderedContent } = await getRenderedContent(note, { tooltip: true });
+ expect($renderedContent.find(".file-download").length).toBe(0);
+ // falls through to the generic FNote no-preview branch
+ expect($renderedContent.hasClass("no-preview")).toBe(true);
+ });
+
+ it("renders an audio file note", async () => {
+ const note = buildNote({ title: "A", type: "file" });
+ note.mime = "audio/mpeg";
+ const { type, $renderedContent } = await getRenderedContent(note);
+ expect(type).toBe("audio");
+ expect($renderedContent.find("audio").attr("src")).toBe(getUrlForDownload(`api/notes/${note.noteId}/open-partial`));
+ });
+
+ it("renders a video file note", async () => {
+ const note = buildNote({ title: "V", type: "file" });
+ note.mime = "video/mp4";
+ const { type, $renderedContent } = await getRenderedContent(note);
+ expect(type).toBe("video");
+ expect($renderedContent.find("video").length).toBe(1);
+ });
+
+ it("hides the open button for protected file notes", async () => {
+ const note = buildNote({ title: "Prot", type: "file" });
+ note.mime = "video/mp4";
+ note.isProtected = true;
+ isProtectedSessionAvailable.mockReturnValue(true); // keep type === file (not protectedSession)
+ const { $renderedContent } = await getRenderedContent(note);
+ expect(touchProtectedSession).toHaveBeenCalled();
+ expect($renderedContent.find(".file-open").css("display")).toBe("none");
+ });
+
+ it("renders a file attachment without note-only footer buttons", async () => {
+ const att = buildAttachment({ role: "file", mime: "video/mp4" });
+ const { type, $renderedContent } = await getRenderedContent(att);
+ expect(type).toBe("video");
+ expect($renderedContent.find(".file-footer").length).toBe(0);
+ });
+
+ it("appends OCR text inside the file content when requested", async () => {
+ const note = buildNote({ title: "FileOcr", type: "file" });
+ note.mime = "audio/mpeg";
+ server.get = vi.fn(async () => ({ success: true, hasOcr: true, text: "ocr-file" })) as typeof server.get;
+ const { $renderedContent } = await getRenderedContent(note, { showTextRepresentation: true });
+ expect($renderedContent.find(".ocr-content").text()).toBe("ocr-file");
+ });
+});
+
+describe("getRenderedContent render / doc / protectedSession / mermaid", () => {
+ it("renders a render-type note and surfaces render-service output", async () => {
+ const note = buildNote({ title: "R", type: "render" });
+ const { type, $renderedContent } = await getRenderedContent(note);
+ expect(type).toBe("render");
+ expect(renderServiceRender).toHaveBeenCalledOnce();
+ expect($renderedContent.find(".render-ok").length).toBe(1);
+ });
+
+ it("render error callback shows an admonition with the error message", async () => {
+ renderServiceRender.mockImplementationOnce(async (_n: any, $content: any, onError: any) => {
+ onError(new Error("kaput"));
+ });
+ const note = buildNote({ title: "RErr", type: "render" });
+ const { $renderedContent } = await getRenderedContent(note);
+ const $err = $renderedContent.find(".admonition.caution");
+ expect($err.length).toBe(1);
+ expect($err.text()).toContain("kaput");
+ });
+
+ it("render error callback accepts a string error directly", async () => {
+ renderServiceRender.mockImplementationOnce(async (_n: any, $content: any, onError: any) => {
+ onError("plain-string-error");
+ });
+ const note = buildNote({ title: "RErrStr", type: "render" });
+ const { $renderedContent } = await getRenderedContent(note);
+ expect($renderedContent.find(".admonition.caution").text()).toBe("plain-string-error");
+ });
+
+ it("renders a doc note via the doc renderer", async () => {
+ const note = buildNote({ title: "D", type: "doc" });
+ const { type, $renderedContent } = await getRenderedContent(note);
+ expect(type).toBe("doc");
+ expect(renderDoc).toHaveBeenCalledOnce();
+ expect($renderedContent.html()).toContain("doc");
+ });
+
+ it("renders the protected-session prompt with a working enter button", async () => {
+ const note = buildNote({ title: "S", type: "text" });
+ note.isProtected = true;
+ isProtectedSessionAvailable.mockReturnValue(false);
+ const { type, $renderedContent } = await getRenderedContent(note);
+ expect(type).toBe("protectedSession");
+ const $btn = $renderedContent.find("button");
+ expect($btn.length).toBe(1);
+ $btn.trigger("click");
+ expect(enterProtectedSession).toHaveBeenCalledOnce();
+ });
+
+ it("renders a mermaid diagram and post-processes the svg", async () => {
+ const note = buildNote({ title: "M", type: "mermaid", content: "graph TD; A-->B" });
+ const { type, $renderedContent } = await getRenderedContent(note);
+ expect(type).toBe("mermaid");
+ expect(mermaidInitialize).toHaveBeenCalledOnce();
+ expect(loadElkIfNeeded).toHaveBeenCalledOnce();
+ expect(postprocessMermaidSvg).toHaveBeenCalledWith("<g/>");
+ expect($renderedContent.find("svg.mm").length).toBe(1);
+ });
+
+ it("renders a mermaid error message when rendering throws", async () => {
+ mermaidRender.mockRejectedValueOnce(new Error("bad diagram"));
+ const note = buildNote({ title: "MErr", type: "mermaid", content: "bogus" });
+ const { $renderedContent } = await getRenderedContent(note);
+ expect($renderedContent.find("p").length).toBe(1);
+ expect(postprocessMermaidSvg).not.toHaveBeenCalled();
+ });
+
+ it("handles a mermaid note with no blob content", async () => {
+ const note = buildNote({ title: "MEmpty", type: "mermaid" });
+ note.getBlob = (async () => null) as any;
+ const { type } = await getRenderedContent(note);
+ expect(type).toBe("mermaid");
+ expect(mermaidRender).toHaveBeenCalled();
+ });
+});
+
+describe("generic FNote fallback / webView", () => {
+ it("renders the no-preview icon block for unknown types", async () => {
+ const note = buildNote({ title: "Map", type: "noteMap" });
+ const { type, $renderedContent } = await getRenderedContent(note);
+ expect(type).toBe("noteMap");
+ expect($renderedContent.hasClass("no-preview")).toBe(true);
+ expect($renderedContent.find("span").length).toBeGreaterThan(0);
+ });
+
+ it("renders a webView footer that opens in a new window when not in electron", async () => {
+ const note = buildNote({ title: "W", type: "webView", "#webViewSrc": "https://example.com" });
+ const openSpy = vi.spyOn(window, "open").mockImplementation(() => null);
+ const { $renderedContent } = await getRenderedContent(note);
+ const $btn = $renderedContent.find(".webview-footer .file-open");
+ expect($btn.length).toBe(1);
+ $btn.trigger("click");
+ expect(openSpy).toHaveBeenCalledWith("https://example.com", "_blank", "noopener,noreferrer");
+ openSpy.mockRestore();
+ });
+
+ it("uses the electron shell when electronApi is present", async () => {
+ const note = buildNote({ title: "WE", type: "webView", "#webViewSrc": "https://el.example" });
+ const openExternal = vi.fn();
+ (window as any).electronApi = { shell: { openExternal } };
+ const { $renderedContent } = await getRenderedContent(note);
+ $renderedContent.find(".webview-footer .file-open").trigger("click");
+ expect(openExternal).toHaveBeenCalledWith("https://el.example");
+ });
+
+ it("does nothing on click when webViewSrc label value is missing", async () => {
+ const note = buildNote({ title: "WNull", type: "webView", "#webViewSrc": "" });
+ const openSpy = vi.spyOn(window, "open").mockImplementation(() => null);
+ const { $renderedContent } = await getRenderedContent(note);
+ $renderedContent.find(".webview-footer .file-open").trigger("click");
+ expect(openSpy).not.toHaveBeenCalled();
+ openSpy.mockRestore();
+ });
+
+ it("renders a plain webView (no webViewSrc label) without a footer", async () => {
+ const note = buildNote({ title: "WPlain", type: "webView" });
+ const { $renderedContent } = await getRenderedContent(note);
+ expect($renderedContent.find(".webview-footer").length).toBe(0);
+ expect($renderedContent.hasClass("no-preview")).toBe(true);
+ });
+});
+
+describe("defensive guards for entities that are neither FNote nor FAttachment", () => {
+ // These exercise branches that production never hits (the static type is FNote | FAttachment),
+ // but the runtime code keeps defensive `instanceof` fallbacks. We feed crafted duck-typed objects.
+
+ it("image rendering falls back to an empty src url and skips the FNote-only fallback block", async () => {
+ const fake = { role: "image", title: "Fake", isProtected: false, mime: "image/png" } as any;
+ const { type, $renderedContent } = await getRenderedContent(fake);
+ expect(type).toBe("image");
+ expect($renderedContent.find("img").attr("src")).toBe("");
+ // final `entity instanceof FNote` is false -> no no-preview / css class added
+ expect($renderedContent.hasClass("no-preview")).toBe(false);
+ });
+
+ it("file rendering throws for an unrecognized entity type", async () => {
+ const fake = { role: "file", title: "Fake", isProtected: false, mime: "audio/mpeg" } as any;
+ await expect(getRenderedContent(fake)).rejects.toThrow(/Can't recognize entity type/);
+ });
+
+ it("rendering type defaults to empty when the entity has neither type nor role", async () => {
+ const fake = { title: "Fake", isProtected: false } as any;
+ const { type } = await getRenderedContent(fake);
+ expect(type).toBe("");
+ });
+});
+
+describe("getRenderingType detection", () => {
+ it("classifies an attachment by its role", async () => {
+ const att = buildAttachment({ role: "image" });
+ expect((await getRenderedContent(att)).type).toBe("image");
+ });
+
+ it("returns the raw role for an attachment with an unhandled role (no rendering branch)", async () => {
+ const att = buildAttachment({ role: "unknownRole" });
+ const { type, $renderedContent } = await getRenderedContent(att);
+ expect(type).toBe("unknownRole");
+ // attachment falls through to the final `entity instanceof FNote` check (false) -> empty content
+ expect($renderedContent.hasClass("no-preview")).toBe(false);
+ expect($renderedContent.children().length).toBe(0);
+ });
+
+ it("maps json file notes to code unless tagged as an icon pack", async () => {
+ const jsonFile = buildNote({ title: "cfg", type: "file" });
+ jsonFile.mime = "application/json";
+ expect((await getRenderedContent(jsonFile)).type).toBe("code");
+
+ const viewConfig = buildNote({ title: "vc" });
+ viewConfig.type = "viewConfig" as any;
+ viewConfig.mime = "application/json";
+ expect((await getRenderedContent(viewConfig)).type).toBe("code");
+
+ const iconPack = buildNote({ title: "icons", type: "file", "#iconPack": "" });
+ iconPack.mime = "application/json";
+ // iconPack stays a file -> renders as a generic file (not tooltip), so type === file
+ expect((await getRenderedContent(iconPack)).type).toBe("file");
+ });
+});
diff --git a/apps/client/src/services/content_renderer_text.spec.ts b/apps/client/src/services/content_renderer_text.spec.ts
index 4199965ccb..e5313add43 100644
--- a/apps/client/src/services/content_renderer_text.spec.ts
+++ b/apps/client/src/services/content_renderer_text.spec.ts
@@ -1,8 +1,28 @@
import { trimIndentation } from "@triliumnext/commons";
-import { describe, expect, it } from "vitest";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import FAttachment from "../entities/fattachment";
+import froca from "./froca";
+import server from "./server";
import { buildNote } from "../test/easy-froca";
-import renderText from "./content_renderer_text";
+
+// `applyInlineMermaid` dynamically imports "mermaid"; provide a controllable
+// stub whose behavior we tune per-test via the shared `mermaidRunImpl` hook.
+let mermaidRunImpl: (args: { nodes: HTMLElement[] }) => void | Promise<void> = () => {};
+const mermaidInitialize = vi.fn();
+vi.mock("mermaid", () => ({
+ default: {
+ initialize: (...args: unknown[]) => mermaidInitialize(...args),
+ run: (args: { nodes: HTMLElement[] }) => mermaidRunImpl(args)
+ }
+}));
+
+import renderText, {
+ applyInlineMermaid,
+ postProcessRichContent,
+ renderChildrenList,
+ rewriteMermaidDiagramsInContainer
+} from "./content_renderer_text";
describe("Text content renderer", () => {
it("renders included note", async () => {
@@ -129,4 +149,318 @@ describe("Text content renderer", () => {
expect(items[0].textContent).toBe("Child note 1");
expect(items[1].textContent).toBe("Child note 3");
});
+
+ it("renders nothing for an empty note with no children when noChildrenList is set", async () => {
+ const contentEl = document.createElement("div");
+ const note = buildNote({ title: "Empty note" });
+ await renderText(note, $(contentEl), { noChildrenList: true });
+ expect(contentEl.innerHTML).toBe("");
+ });
+
+ it("invokes KaTeX inline rendering when math-tex spans are present", async () => {
+ const contentEl = document.createElement("div");
+ const note = buildNote({
+ title: "Math note",
+ content: `<p>Formula: <span class="math-tex">\\(a^2 + b^2\\)</span></p>`
+ });
+ // happy-dom runs in quirks mode, so KaTeX may surface a parse error rather
+ // than a full .katex tree; either way, auto-render touches the span. We only
+ // assert that the math span survives the rendering pass (line is exercised).
+ await expect(renderText(note, $(contentEl))).resolves.toBeUndefined();
+ // The math span is preserved through the KaTeX auto-render pass.
+ expect(contentEl.querySelector("span.math-tex")).not.toBeNull();
+ });
+
+ it("rewrites reference-link titles using the note title", async () => {
+ const contentEl = document.createElement("div");
+ const target = buildNote({ id: "refTarget1", title: "Referenced Title" });
+ const note = buildNote({
+ title: "Note with reference",
+ content: `<p><a class="reference-link" href="#root/${target.noteId}">stale</a></p>`
+ });
+ await renderText(note, $(contentEl));
+ const refLink = contentEl.querySelector("a.reference-link");
+ expect(refLink).not.toBeNull();
+ // The original "stale" child text was replaced with a span carrying the live title.
+ expect(refLink?.textContent).toContain("Referenced Title");
+ });
+
+ it("tolerates reference links without an href", async () => {
+ const contentEl = document.createElement("div");
+ const note = buildNote({
+ title: "Note with bad reference",
+ content: `<p><a class="reference-link">no href</a></p>`
+ });
+ // Should resolve without throwing even though there is no href to resolve.
+ await expect(renderText(note, $(contentEl))).resolves.toBeUndefined();
+ expect(contentEl.querySelector("a.reference-link")).not.toBeNull();
+ });
+});
+
+describe("renderIncludedNotes via postProcessRichContent", () => {
+ it("warns and skips an include-note section whose note cannot be found", async () => {
+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
+ // Make the froca reload a no-op so the missing note stays absent from the
+ // cache (instead of the default throwing tree/load stub).
+ const originalPost = server.post;
+ server.post = vi.fn(async () => ({ notes: [], branches: [], attributes: [] })) as typeof server.post;
+ try {
+ const $rendered = $('<div>').append($('<div class="ck-content">').html(
+ `<section class="include-note" data-note-id="doesNotExist999">&nbsp;</section>`
+ ));
+ const host = buildNote({ title: "Host note" });
+ await postProcessRichContent(host, $rendered);
+ // Section is left in place (not removed) because the note was missing.
+ expect($rendered.find("section.include-note").length).toBe(1);
+ expect(warn).toHaveBeenCalledWith(expect.stringContaining("doesNotExist999"));
+ } finally {
+ server.post = originalPost;
+ warn.mockRestore();
+ }
+ });
+
+ it("ignores include-note sections without a data-note-id", async () => {
+ const $rendered = $('<div>').append($('<div class="ck-content">').html(
+ `<section class="include-note">&nbsp;</section>`
+ ));
+ const host = buildNote({ title: "Host note 2" });
+ await postProcessRichContent(host, $rendered);
+ // No data-note-id means it is skipped in both gather and render loops.
+ expect($rendered.find("section.include-note").length).toBe(1);
+ });
+});
+
+describe("postProcessRichContent with FAttachment", () => {
+ it("adds the attachmentId to seenNoteIds for an attachment owner", async () => {
+ const owner = buildNote({ title: "Owner" });
+ const attachment = new FAttachment(froca, {
+ attachmentId: "att-pp-1",
+ ownerId: owner.noteId,
+ role: "file",
+ mime: "text/html",
+ title: "Attachment",
+ dateModified: "",
+ utcDateModified: "",
+ utcDateScheduledForErasureSince: "",
+ contentLength: 0
+ });
+ const seenNoteIds = new Set<string>();
+ const $rendered = $('<div>').append($('<div class="ck-content">').html("<p>hi</p>"));
+ await postProcessRichContent(attachment, $rendered, { seenNoteIds });
+ expect(seenNoteIds.has("att-pp-1")).toBe(true);
+ });
+});
+
+describe("renderText with FAttachment", () => {
+ it("does not render a children list for an empty attachment blob", async () => {
+ const owner = buildNote({ title: "Owner 2" });
+ const attachment = new FAttachment(froca, {
+ attachmentId: "att-rt-1",
+ ownerId: owner.noteId,
+ role: "file",
+ mime: "text/html",
+ title: "Empty attachment",
+ dateModified: "",
+ utcDateModified: "",
+ utcDateScheduledForErasureSince: "",
+ contentLength: 0
+ });
+ // Empty blob, and an attachment is not an FNote, so neither branch runs.
+ attachment.getBlob = (async () => ({ content: "" })) as typeof attachment.getBlob;
+ const contentEl = document.createElement("div");
+ await renderText(attachment, $(contentEl));
+ expect(contentEl.innerHTML).toBe("");
+ });
+});
+
+describe("renderChildrenList", () => {
+ it("returns immediately when the note has no children", async () => {
+ const note = buildNote({ title: "Childless" });
+ const contentEl = document.createElement("div");
+ await renderChildrenList($(contentEl), note, false);
+ expect(contentEl.innerHTML).toBe("");
+ expect(contentEl.classList.contains("text-with-ellipsis")).toBe(false);
+ });
+
+ it("renders at most the first 10 children", async () => {
+ const children = Array.from({ length: 12 }, (_, i) => ({ title: `C${i}` }));
+ const note = buildNote({ title: "Big parent", children });
+ const contentEl = document.createElement("div");
+ await renderChildrenList($(contentEl), note, false);
+ expect(contentEl.querySelectorAll("a").length).toBe(10);
+ expect(contentEl.classList.contains("text-with-ellipsis")).toBe(true);
+ });
+});
+
+describe("rewriteMermaidDiagramsInContainer", () => {
+ it("does nothing when there are no mermaid code blocks", async () => {
+ const container = document.createElement("div");
+ container.innerHTML = `<pre><code class="language-js">x</code></pre>`;
+ await rewriteMermaidDiagramsInContainer(container);
+ expect(container.querySelector("div.mermaid-diagram")).toBeNull();
+ expect(container.querySelector("pre")).not.toBeNull();
+ });
+
+ it("converts mermaid pre/code blocks into mermaid-diagram divs", async () => {
+ const container = document.createElement("div");
+ container.innerHTML = `<pre><code class="language-mermaid">graph TD;A--&gt;B;</code></pre>`;
+ await rewriteMermaidDiagramsInContainer(container);
+ const div = container.querySelector("div.mermaid-diagram");
+ expect(div).not.toBeNull();
+ expect(div?.innerHTML).toContain("graph TD;");
+ expect(container.querySelector("pre")).toBeNull();
+ });
+
+ it("uses an empty body when the code element is missing", async () => {
+ const container = document.createElement("div");
+ // A <pre> matched by :has(code[...]) but where querySelector("code") returns
+ // the matched code (with no inner content) -> innerHTML falls back to "".
+ container.innerHTML = `<pre><code class="language-mermaid"></code></pre>`;
+ await rewriteMermaidDiagramsInContainer(container);
+ const div = container.querySelector("div.mermaid-diagram");
+ expect(div).not.toBeNull();
+ expect(div?.innerHTML).toBe("");
+ });
+});
+
+describe("applyInlineMermaid", () => {
+ beforeEach(() => {
+ mermaidRunImpl = () => {};
+ mermaidInitialize.mockClear();
+ });
+
+ function makeContainer(sources: string[]) {
+ const container = document.createElement("div");
+ for (const source of sources) {
+ const div = document.createElement("div");
+ div.className = "mermaid-diagram";
+ div.textContent = source;
+ container.appendChild(div);
+ }
+ return container;
+ }
+
+ it("clears stored position state and returns when there are no diagrams", async () => {
+ const container = document.createElement("div");
+ // Should not throw and should not import/initialize mermaid.
+ await applyInlineMermaid(container);
+ expect(mermaidInitialize).not.toHaveBeenCalled();
+ });
+
+ it("renders a pending diagram and caches the produced SVG", async () => {
+ const container = makeContainer(["graph A"]);
+ mermaidRunImpl = ({ nodes }) => {
+ for (const node of nodes) {
+ node.innerHTML = "<svg>A</svg>";
+ node.setAttribute("data-processed", "true");
+ }
+ };
+ await applyInlineMermaid(container);
+ expect(mermaidInitialize).toHaveBeenCalledTimes(1);
+ const visible = container.querySelector("div.mermaid-diagram") as HTMLElement;
+ expect(visible.innerHTML).toBe("<svg>A</svg>");
+ expect(visible.getAttribute("data-processed")).toBe("true");
+ // Offscreen render container is cleaned up.
+ expect(document.body.querySelectorAll("div").length).toBe(0);
+ });
+
+ it("paints cached SVG without re-running mermaid on a second pass", async () => {
+ const container = makeContainer(["graph CACHE"]);
+ let runCount = 0;
+ mermaidRunImpl = ({ nodes }) => {
+ runCount++;
+ for (const node of nodes) {
+ node.innerHTML = "<svg>CACHE</svg>";
+ node.setAttribute("data-processed", "true");
+ }
+ };
+ await applyInlineMermaid(container);
+ expect(runCount).toBe(1);
+
+ // Reset the visible node so we can observe the cached repaint.
+ const node = container.querySelector("div.mermaid-diagram") as HTMLElement;
+ node.removeAttribute("data-processed");
+ node.innerHTML = "graph CACHE";
+ mermaidInitialize.mockClear();
+
+ await applyInlineMermaid(container);
+ // No new render: cache hit short-circuits and pending stays empty.
+ expect(runCount).toBe(1);
+ expect(mermaidInitialize).not.toHaveBeenCalled();
+ expect(node.innerHTML).toBe("<svg>CACHE</svg>");
+ expect(node.getAttribute("data-processed")).toBe("true");
+ });
+
+ it("shows the previous SVG as a placeholder while the new diagram renders", async () => {
+ const container = makeContainer(["graph V1"]);
+ mermaidRunImpl = ({ nodes }) => {
+ for (const node of nodes) {
+ node.innerHTML = `<svg>${node.textContent}</svg>`;
+ node.setAttribute("data-processed", "true");
+ }
+ };
+ await applyInlineMermaid(container);
+
+ // Edit the diagram source in place; the old SVG should be used as the
+ // positional placeholder for the new (uncached) source.
+ const node = container.querySelector("div.mermaid-diagram") as HTMLElement;
+ const previousSvg = node.innerHTML;
+ node.textContent = "graph V2";
+
+ let placeholderDuringRun = "";
+ mermaidRunImpl = ({ nodes }) => {
+ placeholderDuringRun = node.innerHTML;
+ for (const clone of nodes) {
+ clone.innerHTML = `<svg>${clone.textContent}</svg>`;
+ clone.setAttribute("data-processed", "true");
+ }
+ };
+ await applyInlineMermaid(container);
+ expect(placeholderDuringRun).toBe(previousSvg);
+ expect(node.innerHTML).toBe("<svg>graph V2</svg>");
+ });
+
+ it("evicts cache entries whose source is no longer present", async () => {
+ const container = makeContainer(["graph KEEP", "graph DROP"]);
+ mermaidRunImpl = ({ nodes }) => {
+ for (const node of nodes) {
+ node.innerHTML = `<svg>${node.textContent}</svg>`;
+ node.setAttribute("data-processed", "true");
+ }
+ };
+ await applyInlineMermaid(container);
+
+ // Remove the second diagram so its cached source must be evicted.
+ container.querySelectorAll("div.mermaid-diagram")[1].remove();
+ // First node is now a cache hit (its source is unchanged); reset to verify.
+ const remaining = container.querySelector("div.mermaid-diagram") as HTMLElement;
+ remaining.removeAttribute("data-processed");
+ remaining.innerHTML = "graph KEEP";
+
+ await applyInlineMermaid(container);
+ expect(remaining.innerHTML).toBe("<svg>graph KEEP</svg>");
+ });
+
+ it("logs but does not throw when mermaid.run rejects", async () => {
+ const error = vi.spyOn(console, "error").mockImplementation(() => {});
+ const container = makeContainer(["graph BOOM"]);
+ mermaidRunImpl = () => {
+ throw new Error("mermaid failed");
+ };
+ await applyInlineMermaid(container);
+ expect(error).toHaveBeenCalled();
+ error.mockRestore();
+ });
+
+ it("leaves the visible node untouched when the offscreen clone was not processed", async () => {
+ const container = makeContainer(["graph SKIP"]);
+ mermaidRunImpl = () => {
+ // Render succeeds but never marks the clone as processed.
+ };
+ await applyInlineMermaid(container);
+ const node = container.querySelector("div.mermaid-diagram") as HTMLElement;
+ // Visible node keeps its original source text; no SVG was applied.
+ expect(node.getAttribute("data-processed")).toBeNull();
+ expect(node.innerHTML).toBe("graph SKIP");
+ });
});
diff --git a/apps/client/src/services/content_renderer_text.ts b/apps/client/src/services/content_renderer_text.ts
index 283340ecc2..35ffc8fc66 100644
--- a/apps/client/src/services/content_renderer_text.ts
+++ b/apps/client/src/services/content_renderer_text.ts
@@ -107,6 +107,7 @@ export async function rewriteMermaidDiagramsInContainer(container: HTMLDivElemen
for (const mermaidBlock of mermaidBlocks) {
const div = document.createElement("div");
div.classList.add("mermaid-diagram");
+ /* v8 ignore next -- defensive fallback: the `:has(code[...])` selector guarantees a `<code>` child whose innerHTML is always a string */
div.innerHTML = mermaidBlock.querySelector("code")?.innerHTML ?? "";
mermaidBlock.replaceWith(div);
nodes.push(div);
@@ -150,6 +151,7 @@ export async function applyInlineMermaid(container: HTMLDivElement) {
const pending: Array<{ visible: HTMLElement; source: string }> = [];
const seenSources = new Set<string>();
for (const [ index, node ] of nodes.entries()) {
+ /* v8 ignore next -- defensive fallback: textContent on an HTMLElement is always a string */
const source = (node.textContent ?? "").trim();
seenSources.add(source);
diff --git a/apps/client/src/services/css_class_manager.spec.ts b/apps/client/src/services/css_class_manager.spec.ts
index b49e8c0ab2..eb87f0b4dc 100644
--- a/apps/client/src/services/css_class_manager.spec.ts
+++ b/apps/client/src/services/css_class_manager.spec.ts
@@ -1,6 +1,8 @@
import { describe, expect, it } from "vitest";
+import $ from "jquery";
-import { getReadableTextColor } from "./css_class_manager";
+import cssClassManager, { getHue, getReadableTextColor, parseColor } from "./css_class_manager";
+import Color from "color";
describe("getReadableTextColor", () => {
it("doesn't crash for invalid color", () => {
@@ -11,4 +13,111 @@ describe("getReadableTextColor", () => {
expect(getReadableTextColor("Blue"))
.toBe(getReadableTextColor("blue"));
});
+
+ it("returns black text for a light background and white text for a dark one", () => {
+ expect(getReadableTextColor("#ffffff")).toBe("#000");
+ expect(getReadableTextColor("#000000")).toBe("#fff");
+ });
+});
+
+describe("parseColor", () => {
+ it("parses a valid color", () => {
+ const parsed = parseColor("#ff0000");
+ expect(parsed).toBeDefined();
+ expect(parsed!.hex().toLowerCase()).toBe("#ff0000");
+ });
+
+ it("returns undefined for an invalid color (caught exception)", () => {
+ expect(parseColor("not-a-color")).toBeUndefined();
+ });
+});
+
+describe("getHue", () => {
+ it("returns a hue for a saturated color", () => {
+ const hue = getHue(Color("#ff0000"));
+ expect(hue).toBeDefined();
+ // Red sits at hue 0.
+ expect(hue).toBe(0);
+ });
+
+ it("returns undefined for a grayscale color (no saturation)", () => {
+ expect(getHue(Color("#808080"))).toBeUndefined();
+ });
+});
+
+describe("createClassForColor", () => {
+ function styleCount() {
+ return $("head").find("style").length;
+ }
+
+ it("returns empty string for null, empty and whitespace-only input", () => {
+ expect(cssClassManager.createClassForColor(null)).toBe("");
+ expect(cssClassManager.createClassForColor("")).toBe("");
+ expect(cssClassManager.createClassForColor(" ")).toBe("");
+ });
+
+ it("returns empty string for an unparseable color", () => {
+ expect(cssClassManager.createClassForColor("definitely-not-a-color")).toBe("");
+ });
+
+ it("registers a saturated color, injects a <style>, and adds the with-hue class", () => {
+ const before = styleCount();
+ const result = cssClassManager.createClassForColor("#123456");
+
+ expect(result).toContain("use-note-color");
+ expect(result).toContain("color-123456");
+ expect(result).toContain("with-hue");
+ // A new <style> element was appended for this freshly-registered color.
+ expect(styleCount()).toBe(before + 1);
+
+ // The injected style references the registered class and the custom-color CSS vars.
+ const html = $("head").find("style").last().html() ?? "";
+ expect(html).toContain(".color-123456");
+ expect(html).toContain("--original-custom-color: #123456");
+ expect(html).toContain("--custom-color-hue:");
+ });
+
+ it("does not re-inject a <style> for an already-registered color", () => {
+ // First registration. Color#hex() upper-cases hex digits, so the class follows suit.
+ cssClassManager.createClassForColor("#abcdef");
+ const after = styleCount();
+
+ // Second call with the same color must reuse the existing registration.
+ const result = cssClassManager.createClassForColor("#abcdef");
+ expect(result).toContain("color-ABCDEF");
+ expect(styleCount()).toBe(after);
+ });
+
+ it("registers a grayscale color without the with-hue class and emits an unset hue", () => {
+ const result = cssClassManager.createClassForColor("#777777");
+
+ expect(result).toContain("use-note-color");
+ expect(result).toContain("color-777777");
+ expect(result).not.toContain("with-hue");
+
+ const styleForGray = $("head")
+ .find("style")
+ .filter((_, el) => ($(el).html() ?? "").includes(".color-777777"))
+ .first()
+ .html() ?? "";
+ expect(styleForGray).toContain("--custom-color-hue: unset");
+ });
+
+ it("adjusts lightness for both a very light and a very dark color", () => {
+ // Very light color: dark-theme min-lightness clamp kicks in (Math.max picks the min).
+ const light = cssClassManager.createClassForColor("#fefefe");
+ expect(light).toContain("color-FEFEFE");
+
+ // Very dark color: light-theme max-lightness clamp kicks in (Math.min picks the max).
+ const dark = cssClassManager.createClassForColor("#010101");
+ expect(dark).toContain("color-010101");
+
+ const darkHtml = $("head")
+ .find("style")
+ .filter((_, el) => ($(el).html() ?? "").includes(".color-010101"))
+ .first()
+ .html() ?? "";
+ expect(darkHtml).toContain("--light-theme-custom-color:");
+ expect(darkHtml).toContain("--dark-theme-custom-color:");
+ });
});
diff --git a/apps/client/src/services/date_notes.spec.ts b/apps/client/src/services/date_notes.spec.ts
new file mode 100644
index 0000000000..a1dc5dc69a
--- /dev/null
+++ b/apps/client/src/services/date_notes.spec.ts
@@ -0,0 +1,206 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+import { buildNote } from "../test/easy-froca";
+import dateNotes from "./date_notes.js";
+import server from "./server.js";
+import ws from "./ws.js";
+
+// The global ws mock from setup.ts does not define waitForMaxKnownEntityChangeId, so provide it.
+ws.waitForMaxKnownEntityChangeId = vi.fn(async () => {});
+
+describe("date_notes", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ ws.waitForMaxKnownEntityChangeId = vi.fn(async () => {});
+ });
+
+ it("getInboxNote resolves the note returned by the server", async () => {
+ const note = buildNote({ title: "Inbox" });
+ server.get = vi.fn(async () => ({ noteId: note.noteId })) as typeof server.get;
+
+ const result = await dateNotes.getInboxNote();
+
+ expect(server.get).toHaveBeenCalledWith(
+ expect.stringMatching(/^special-notes\/inbox\/\d{4}-\d{2}-\d{2}$/),
+ "date-note"
+ );
+ expect(result).toBe(note);
+ });
+
+ it("getTodayNote resolves today's day note", async () => {
+ const note = buildNote({ title: "Today" });
+ server.get = vi.fn(async () => ({ noteId: note.noteId })) as typeof server.get;
+
+ const result = await dateNotes.getTodayNote();
+
+ expect(server.get).toHaveBeenCalledWith(
+ expect.stringMatching(/^special-notes\/days\/\d{4}-\d{2}-\d{2}$/),
+ "date-note"
+ );
+ expect(ws.waitForMaxKnownEntityChangeId).toHaveBeenCalled();
+ expect(result).toBe(note);
+ });
+
+ it("getDayNote omits calendarRootId when not provided", async () => {
+ const note = buildNote({ title: "Day" });
+ server.get = vi.fn(async () => ({ noteId: note.noteId })) as typeof server.get;
+
+ const result = await dateNotes.getDayNote("2025-05-29");
+
+ expect(server.get).toHaveBeenCalledWith("special-notes/days/2025-05-29", "date-note");
+ expect(result).toBe(note);
+ });
+
+ it("getDayNote appends calendarRootId when provided", async () => {
+ const note = buildNote({ title: "Day in root" });
+ server.get = vi.fn(async () => ({ noteId: note.noteId })) as typeof server.get;
+
+ const result = await dateNotes.getDayNote("2025-05-29", "rootXYZ");
+
+ expect(server.get).toHaveBeenCalledWith(
+ "special-notes/days/2025-05-29?calendarRootId=rootXYZ",
+ "date-note"
+ );
+ expect(result).toBe(note);
+ });
+
+ it("getWeekFirstDayNote queries week-first-day endpoint", async () => {
+ const note = buildNote({ title: "Week first day" });
+ server.get = vi.fn(async () => ({ noteId: note.noteId })) as typeof server.get;
+
+ const result = await dateNotes.getWeekFirstDayNote("2025-05-29");
+
+ expect(server.get).toHaveBeenCalledWith("special-notes/week-first-day/2025-05-29", "date-note");
+ expect(result).toBe(note);
+ });
+
+ it("getWeekNote queries weeks endpoint", async () => {
+ const note = buildNote({ title: "Week" });
+ server.get = vi.fn(async () => ({ noteId: note.noteId })) as typeof server.get;
+
+ const result = await dateNotes.getWeekNote("2025-W22");
+
+ expect(server.get).toHaveBeenCalledWith("special-notes/weeks/2025-W22", "date-note");
+ expect(result).toBe(note);
+ });
+
+ it("getMonthNote queries months endpoint", async () => {
+ const note = buildNote({ title: "Month" });
+ server.get = vi.fn(async () => ({ noteId: note.noteId })) as typeof server.get;
+
+ const result = await dateNotes.getMonthNote("2025-05");
+
+ expect(server.get).toHaveBeenCalledWith("special-notes/months/2025-05", "date-note");
+ expect(result).toBe(note);
+ });
+
+ it("getQuarterNote queries quarters endpoint", async () => {
+ const note = buildNote({ title: "Quarter" });
+ server.get = vi.fn(async () => ({ noteId: note.noteId })) as typeof server.get;
+
+ const result = await dateNotes.getQuarterNote("2025-Q2");
+
+ expect(server.get).toHaveBeenCalledWith("special-notes/quarters/2025-Q2", "date-note");
+ expect(result).toBe(note);
+ });
+
+ it("getYearNote queries years endpoint", async () => {
+ const note = buildNote({ title: "Year" });
+ server.get = vi.fn(async () => ({ noteId: note.noteId })) as typeof server.get;
+
+ const result = await dateNotes.getYearNote("2025");
+
+ expect(server.get).toHaveBeenCalledWith("special-notes/years/2025", "date-note");
+ expect(result).toBe(note);
+ });
+
+ it("createSqlConsole posts and resolves the note", async () => {
+ const note = buildNote({ title: "SQL console" });
+ server.post = vi.fn(async () => ({ noteId: note.noteId })) as typeof server.post;
+
+ const result = await dateNotes.createSqlConsole();
+
+ expect(server.post).toHaveBeenCalledWith("special-notes/sql-console");
+ expect(result).toBe(note);
+ });
+
+ it("createSearchNote posts with default empty opts", async () => {
+ const note = buildNote({ title: "Search" });
+ server.post = vi.fn(async () => ({ noteId: note.noteId })) as typeof server.post;
+
+ const result = await dateNotes.createSearchNote();
+
+ expect(server.post).toHaveBeenCalledWith("special-notes/search-note", {});
+ expect(result).toBe(note);
+ });
+
+ it("createSearchNote posts with provided opts", async () => {
+ const note = buildNote({ title: "Search with opts" });
+ server.post = vi.fn(async () => ({ noteId: note.noteId })) as typeof server.post;
+
+ const result = await dateNotes.createSearchNote({ searchString: "foo" });
+
+ expect(server.post).toHaveBeenCalledWith("special-notes/search-note", { searchString: "foo" });
+ expect(result).toBe(note);
+ });
+
+ it("createLlmChat posts and resolves the note", async () => {
+ const note = buildNote({ title: "LLM chat" });
+ server.post = vi.fn(async () => ({ noteId: note.noteId })) as typeof server.post;
+
+ const result = await dateNotes.createLlmChat();
+
+ expect(server.post).toHaveBeenCalledWith("special-notes/llm-chat");
+ expect(result).toBe(note);
+ });
+
+ it("getMostRecentLlmChat returns null when the server has no chat", async () => {
+ server.get = vi.fn(async () => null) as typeof server.get;
+
+ const result = await dateNotes.getMostRecentLlmChat();
+
+ expect(result).toBeNull();
+ expect(ws.waitForMaxKnownEntityChangeId).not.toHaveBeenCalled();
+ });
+
+ it("getMostRecentLlmChat resolves the note when one exists", async () => {
+ const note = buildNote({ title: "Recent chat" });
+ server.get = vi.fn(async () => ({ noteId: note.noteId })) as typeof server.get;
+
+ const result = await dateNotes.getMostRecentLlmChat();
+
+ expect(server.get).toHaveBeenCalledWith("special-notes/most-recent-llm-chat");
+ expect(ws.waitForMaxKnownEntityChangeId).toHaveBeenCalled();
+ expect(result).toBe(note);
+ });
+
+ it("getOrCreateLlmChat resolves the note", async () => {
+ const note = buildNote({ title: "Persistent chat" });
+ server.get = vi.fn(async () => ({ noteId: note.noteId })) as typeof server.get;
+
+ const result = await dateNotes.getOrCreateLlmChat();
+
+ expect(server.get).toHaveBeenCalledWith("special-notes/get-or-create-llm-chat");
+ expect(result).toBe(note);
+ });
+
+ it("getRecentLlmChats uses the default limit and returns the list", async () => {
+ const chats = [{ noteId: "a", title: "A", dateModified: "2025-05-29" }];
+ server.get = vi.fn(async () => chats) as typeof server.get;
+
+ const result = await dateNotes.getRecentLlmChats();
+
+ expect(server.get).toHaveBeenCalledWith("special-notes/recent-llm-chats?limit=10");
+ expect(result).toBe(chats);
+ });
+
+ it("getRecentLlmChats honours an explicit limit", async () => {
+ const chats = [{ noteId: "b", title: "B", dateModified: "2025-05-29" }];
+ server.get = vi.fn(async () => chats) as typeof server.get;
+
+ const result = await dateNotes.getRecentLlmChats(3);
+
+ expect(server.get).toHaveBeenCalledWith("special-notes/recent-llm-chats?limit=3");
+ expect(result).toBe(chats);
+ });
+});
diff --git a/apps/client/src/services/debounce.spec.ts b/apps/client/src/services/debounce.spec.ts
new file mode 100644
index 0000000000..e2bf560a0b
--- /dev/null
+++ b/apps/client/src/services/debounce.spec.ts
@@ -0,0 +1,141 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+import debounce from "./debounce.js";
+
+// The source types the returned function with no declared params (it forwards `arguments`),
+// so widen it to a variadic callable for the tests.
+type Debounced = ((...args: any[]) => any) & { clear(): void; flush(): void };
+
+describe("debounce", () => {
+ beforeEach(() => {
+ vi.useFakeTimers();
+ });
+
+ afterEach(() => {
+ vi.useRealTimers();
+ });
+
+ it("defers a trailing call until the wait elapses after the last invocation", () => {
+ const fn = vi.fn();
+ const debounced = debounce(fn, 100) as Debounced;
+
+ debounced("a");
+ // Re-invoking before the wait elapses keeps deferring (reschedule branch in `later`).
+ vi.advanceTimersByTime(60);
+ debounced("b");
+ vi.advanceTimersByTime(60);
+ expect(fn).not.toHaveBeenCalled();
+
+ // Now let the full wait elapse from the last invocation.
+ vi.advanceTimersByTime(100);
+ expect(fn).toHaveBeenCalledTimes(1);
+ expect(fn).toHaveBeenCalledWith("b");
+ });
+
+ it("preserves `this` context and returns the previous trailing result", () => {
+ const ctx = { value: 42 };
+ const fn = vi.fn(function (this: typeof ctx, n: number) {
+ return this.value + n;
+ });
+ const debounced = debounce(fn, 100) as Debounced;
+
+ // First trailing invocation: nothing computed yet, returns undefined.
+ expect(debounced.call(ctx, 1)).toBeUndefined();
+ vi.advanceTimersByTime(100);
+ expect(fn).toHaveLastReturnedWith(43);
+ expect(fn.mock.contexts[0]).toBe(ctx);
+
+ // Subsequent invocation returns the previously stored result.
+ expect(debounced.call(ctx, 10)).toBe(43);
+ vi.advanceTimersByTime(100);
+ expect(fn).toHaveLastReturnedWith(52);
+ });
+
+ it("invokes on the leading edge when `immediate` is true and does not re-fire on trailing", () => {
+ const fn = vi.fn((x: string) => x.toUpperCase());
+ const debounced = debounce(fn, 100, true) as Debounced;
+
+ // Leading call fires synchronously (callNow branch) and returns the result.
+ expect(debounced("hi")).toBe("HI");
+ expect(fn).toHaveBeenCalledTimes(1);
+
+ // While the timer is pending, further calls do not fire (callNow=false because timeout set).
+ debounced("again");
+ expect(fn).toHaveBeenCalledTimes(1);
+
+ // Trailing `later` clears the timeout but does NOT call func because immediate is true.
+ vi.advanceTimersByTime(100);
+ expect(fn).toHaveBeenCalledTimes(1);
+
+ // After the timer cleared, a new call fires on the leading edge again.
+ expect(debounced("third")).toBe("THIRD");
+ expect(fn).toHaveBeenCalledTimes(2);
+ });
+
+ it("defaults the wait to 100ms when called with a nullish wait", () => {
+ const fn = vi.fn();
+ // Force the `null == waitMs` branch (the type says number, but runtime guards null/undefined).
+ const debounced = debounce(fn, null as unknown as number) as Debounced;
+
+ debounced();
+ vi.advanceTimersByTime(99);
+ expect(fn).not.toHaveBeenCalled();
+ vi.advanceTimersByTime(1);
+ expect(fn).toHaveBeenCalledTimes(1);
+ });
+
+ it("clear() cancels a pending trailing call and is a no-op when nothing is pending", () => {
+ const fn = vi.fn();
+ const debounced = debounce(fn, 100) as Debounced;
+
+ debounced();
+ debounced.clear();
+ vi.advanceTimersByTime(100);
+ expect(fn).not.toHaveBeenCalled();
+
+ // No pending timer -> clear() takes the falsy branch and does nothing.
+ expect(() => debounced.clear()).not.toThrow();
+ expect(fn).not.toHaveBeenCalled();
+ });
+
+ it("flush() invokes immediately with the latest args and is a no-op when nothing is pending", () => {
+ const fn = vi.fn((x: number) => x * 2);
+ const debounced = debounce(fn, 100) as Debounced;
+
+ debounced(5);
+ expect(debounced.flush()).toBeUndefined(); // flush returns nothing
+ expect(fn).toHaveBeenCalledTimes(1);
+ expect(fn).toHaveBeenCalledWith(5);
+
+ // Timer was cleared by flush, so advancing does not re-fire.
+ vi.advanceTimersByTime(100);
+ expect(fn).toHaveBeenCalledTimes(1);
+
+ // Nothing pending -> flush() falsy branch, no-op.
+ debounced.flush();
+ expect(fn).toHaveBeenCalledTimes(1);
+ });
+
+ it("reschedules in `later` when the system clock jumps backwards (last < 0)", () => {
+ const fn = vi.fn();
+ const debounced = debounce(fn, 100) as Debounced;
+
+ const nowSpy = vi.spyOn(Date, "now");
+ // timestamp recorded at invocation time = 1000.
+ nowSpy.mockReturnValue(1000);
+ debounced("x");
+
+ // When `later` runs, Date.now() returns an earlier value -> last = -500 (< 0),
+ // which fails the `last >= 0` check, so func still fires (else branch).
+ nowSpy.mockReturnValue(500);
+ vi.advanceTimersByTime(100);
+ expect(fn).toHaveBeenCalledTimes(1);
+ expect(fn).toHaveBeenCalledWith("x");
+
+ nowSpy.mockRestore();
+ });
+
+ it("exposes itself as `.debounce` for ES module interop", () => {
+ expect(debounce.debounce).toBe(debounce);
+ });
+});
diff --git a/apps/client/src/services/debounce.ts b/apps/client/src/services/debounce.ts
index 4f16cc190d..74d0f6a326 100644
--- a/apps/client/src/services/debounce.ts
+++ b/apps/client/src/services/debounce.ts
@@ -28,6 +28,7 @@ function debounce<T>(func: (...args: any[]) => T, waitMs: number, immediate: boo
} else {
timeout = null;
if (!immediate) {
+ /* v8 ignore next -- `|| []` is a defensive fallback: `args` is always non-null here because `debounced` (re)assigns it before this runs */
result = func.apply(context, args || []);
context = args = null;
}
@@ -41,6 +42,7 @@ function debounce<T>(func: (...args: any[]) => T, waitMs: number, immediate: boo
const callNow = immediate && !timeout;
if (!timeout) timeout = setTimeout(later, waitMs);
if (callNow) {
+ /* v8 ignore next -- `|| []` is a defensive fallback: `args` was just assigned `arguments` above and is always truthy here */
result = func.apply(context, args || []);
context = args = null;
}
@@ -57,6 +59,7 @@ function debounce<T>(func: (...args: any[]) => T, waitMs: number, immediate: boo
debounced.flush = function () {
if (timeout) {
+ /* v8 ignore next -- `|| []` is a defensive fallback: a live `timeout` implies `debounced` set `args` and no fire has nulled it yet */
result = func.apply(context, args || []);
context = args = null;
diff --git a/apps/client/src/services/dialog.spec.ts b/apps/client/src/services/dialog.spec.ts
new file mode 100644
index 0000000000..3248b0ffa1
--- /dev/null
+++ b/apps/client/src/services/dialog.spec.ts
@@ -0,0 +1,235 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import $ from "jquery";
+
+// --- Mocks (hoisted above imports) ---
+
+// Spies are created via vi.hoisted so the vi.mock factories (which are also
+// hoisted) can safely reference them.
+const { modalShow, modalHide, getOrCreateInstance, triggerCommand, saveFocusedElement, focusSavedElement, updateDisplayedShortcuts } = vi.hoisted(() => {
+ const modalShow = vi.fn();
+ const modalHide = vi.fn();
+ return {
+ modalShow,
+ modalHide,
+ getOrCreateInstance: vi.fn(() => ({ show: modalShow, hide: modalHide })),
+ triggerCommand: vi.fn(),
+ saveFocusedElement: vi.fn(),
+ focusSavedElement: vi.fn(),
+ updateDisplayedShortcuts: vi.fn()
+ };
+});
+
+vi.mock("bootstrap", () => ({
+ Modal: { getOrCreateInstance }
+}));
+
+vi.mock("../components/app_context.js", () => ({
+ default: { triggerCommand }
+}));
+
+vi.mock("./focus.js", () => ({ saveFocusedElement, focusSavedElement }));
+
+vi.mock("./keyboard_actions.js", () => ({
+ default: { updateDisplayedShortcuts }
+}));
+
+// Imports AFTER vi.mock calls.
+import dialogService, { closeActiveDialog, openDialog } from "./dialog.js";
+
+function makeDialog() {
+ // A real jQuery-wrapped element so `.on("hidden.bs.modal", ...)` works
+ // and we can trigger the handler to exercise its body.
+ return $("<div class='modal'></div>");
+}
+
+describe("dialog service", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ glob.activeDialog = null;
+ });
+
+ describe("openDialog", () => {
+ it("closes the active dialog, sets the new one, saves focus, shows the modal and updates shortcuts", async () => {
+ const previous = makeDialog();
+ glob.activeDialog = previous;
+
+ const $dialog = makeDialog();
+ const config = { backdrop: false };
+ const result = await openDialog($dialog, true, config);
+
+ // previous active dialog hidden via closeActiveDialog
+ expect(modalHide).toHaveBeenCalledTimes(1);
+ // new dialog becomes the active one
+ expect(glob.activeDialog).toBe($dialog);
+ expect(saveFocusedElement).toHaveBeenCalledTimes(1);
+ // modal created with the provided config and shown
+ expect(getOrCreateInstance).toHaveBeenCalledWith($dialog[0], config);
+ expect(modalShow).toHaveBeenCalledTimes(1);
+ expect(updateDisplayedShortcuts).toHaveBeenCalledWith($dialog);
+ expect(result).toBe($dialog);
+ });
+
+ it("does not close or replace the active dialog when closeActDialog is false", async () => {
+ const existing = makeDialog();
+ glob.activeDialog = existing;
+
+ const $dialog = makeDialog();
+ await openDialog($dialog, false);
+
+ // closeActiveDialog branch skipped
+ expect(modalHide).not.toHaveBeenCalled();
+ expect(glob.activeDialog).toBe(existing);
+ // config omitted -> getOrCreateInstance called with undefined config
+ expect(getOrCreateInstance).toHaveBeenCalledWith($dialog[0], undefined);
+ expect(saveFocusedElement).toHaveBeenCalledTimes(1);
+ });
+
+ it("refocuses the saved element on hide when there is no active dialog", async () => {
+ const $dialog = makeDialog();
+ await openDialog($dialog, false);
+
+ // glob.activeDialog is null -> first part of the OR is truthy
+ $dialog.trigger("hidden.bs.modal");
+
+ expect(focusSavedElement).toHaveBeenCalledTimes(1);
+ });
+
+ it("refocuses on hide when the hidden dialog is the active dialog", async () => {
+ const $dialog = makeDialog();
+ // closeActDialog=true makes this dialog the active one
+ await openDialog($dialog, true);
+ expect(glob.activeDialog).toBe($dialog);
+
+ $dialog.trigger("hidden.bs.modal");
+
+ expect(focusSavedElement).toHaveBeenCalledTimes(1);
+ });
+
+ it("does NOT refocus on hide when a different dialog is active", async () => {
+ const $dialog = makeDialog();
+ await openDialog($dialog, false);
+
+ // a different dialog is the active one -> both OR conditions false
+ glob.activeDialog = makeDialog();
+ $dialog.trigger("hidden.bs.modal");
+
+ expect(focusSavedElement).not.toHaveBeenCalled();
+ });
+
+ it("closes the autocomplete dropdown on hide", async () => {
+ const $dialog = makeDialog();
+ await openDialog($dialog, false);
+
+ // `"autocomplete" in $autocompleteEl` is true for a jQuery object only if the
+ // autocomplete plugin is registered. Register a stub on the jQuery prototype so
+ // the branch is taken and the plugin is invoked.
+ const autocomplete = vi.fn();
+ ($.fn as any).autocomplete = autocomplete;
+
+ $dialog.trigger("hidden.bs.modal");
+
+ expect(autocomplete).toHaveBeenCalledWith("close");
+
+ delete ($.fn as any).autocomplete;
+ });
+
+ it("skips closing autocomplete when the plugin is not registered", async () => {
+ const $dialog = makeDialog();
+ await openDialog($dialog, false);
+
+ // Ensure no autocomplete plugin is present so the `in` check is false.
+ delete ($.fn as any).autocomplete;
+
+ // Should not throw.
+ expect(() => $dialog.trigger("hidden.bs.modal")).not.toThrow();
+ });
+ });
+
+ describe("closeActiveDialog", () => {
+ it("hides the active dialog and clears the reference", () => {
+ const $dialog = makeDialog();
+ glob.activeDialog = $dialog;
+
+ closeActiveDialog();
+
+ expect(getOrCreateInstance).toHaveBeenCalledWith($dialog[0]);
+ expect(modalHide).toHaveBeenCalledTimes(1);
+ expect(glob.activeDialog).toBeNull();
+ });
+
+ it("does nothing when there is no active dialog", () => {
+ glob.activeDialog = null;
+
+ closeActiveDialog();
+
+ expect(getOrCreateInstance).not.toHaveBeenCalled();
+ expect(modalHide).not.toHaveBeenCalled();
+ });
+ });
+
+ describe("dialog command wrappers", () => {
+ it("info triggers showInfoDialog and resolves with the callback value, merging extra props", async () => {
+ triggerCommand.mockImplementation((_name, data: any) => data.callback("info-result"));
+
+ const promise = dialogService.info("hello", { okLabel: "Got it" } as any);
+ await expect(promise).resolves.toBe("info-result");
+
+ expect(triggerCommand).toHaveBeenCalledTimes(1);
+ const [name, data] = triggerCommand.mock.calls[0];
+ expect(name).toBe("showInfoDialog");
+ expect(data.message).toBe("hello");
+ expect(data.okLabel).toBe("Got it");
+ expect(typeof data.callback).toBe("function");
+ });
+
+ it("info works without extra props", async () => {
+ triggerCommand.mockImplementation((_name, data: any) => data.callback(undefined));
+
+ await expect(dialogService.info("plain")).resolves.toBeUndefined();
+ const [, data] = triggerCommand.mock.calls[0];
+ expect(data.message).toBe("plain");
+ });
+
+ it("confirm resolves true only when the result is confirmed", async () => {
+ // Confirmed result
+ triggerCommand.mockImplementationOnce((_name, data: any) => data.callback({ confirmed: true, isDeleteNoteChecked: false }));
+ await expect(dialogService.confirm("sure?")).resolves.toBe(true);
+
+ const [name, data] = triggerCommand.mock.calls[0];
+ expect(name).toBe("showConfirmDialog");
+ expect(data.message).toBe("sure?");
+
+ // Not-confirmed object result
+ triggerCommand.mockImplementationOnce((_name, d: any) => d.callback({ confirmed: false, isDeleteNoteChecked: true }));
+ await expect(dialogService.confirm("sure?")).resolves.toBe(false);
+
+ // Falsy result (dialog dismissed) -> x && x.confirmed short-circuits to the falsy value
+ triggerCommand.mockImplementationOnce((_name, d: any) => d.callback(false));
+ await expect(dialogService.confirm("sure?")).resolves.toBe(false);
+ });
+
+ it("confirmDeleteNoteBoxWithNote triggers the delete-box command and resolves with the callback value", async () => {
+ const callbackResult = { confirmed: true, isDeleteNoteChecked: true };
+ triggerCommand.mockImplementation((_name, data: any) => data.callback(callbackResult));
+
+ await expect(dialogService.confirmDeleteNoteBoxWithNote("My note")).resolves.toBe(callbackResult);
+
+ const [name, data] = triggerCommand.mock.calls[0];
+ expect(name).toBe("showConfirmDeleteNoteBoxWithNoteDialog");
+ expect(data.title).toBe("My note");
+ expect(typeof data.callback).toBe("function");
+ });
+
+ it("prompt triggers showPromptDialog with merged props and resolves with the callback value", async () => {
+ triggerCommand.mockImplementation((_name, data: any) => data.callback("typed text"));
+
+ await expect(dialogService.prompt({ title: "Name?", defaultValue: "x" } as any)).resolves.toBe("typed text");
+
+ const [name, data] = triggerCommand.mock.calls[0];
+ expect(name).toBe("showPromptDialog");
+ expect(data.title).toBe("Name?");
+ expect(data.defaultValue).toBe("x");
+ expect(typeof data.callback).toBe("function");
+ });
+ });
+});
diff --git a/apps/client/src/services/doc_renderer.spec.ts b/apps/client/src/services/doc_renderer.spec.ts
index 6874e2b227..11086b3880 100644
--- a/apps/client/src/services/doc_renderer.spec.ts
+++ b/apps/client/src/services/doc_renderer.spec.ts
@@ -1,6 +1,40 @@
-import { describe, expect, it } from "vitest";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import $ from "jquery";
-import { isValidDocName } from "./doc_renderer.js";
+vi.mock("./i18n.js", () => ({
+ getCurrentLanguage: () => mockedLanguage
+}));
+vi.mock("./syntax_highlight.js", () => ({
+ formatCodeBlocks: (arg: unknown) => formatCodeBlocksMock(arg)
+}));
+vi.mock("../widgets/type_widgets/text/read_only_helper.js", () => ({
+ applyReferenceLinks: (arg: unknown) => applyReferenceLinksMock(arg)
+}));
+
+import renderDoc, { isValidDocName } from "./doc_renderer.js";
+
+let mockedLanguage = "en";
+const formatCodeBlocksMock = vi.fn((_arg?: unknown) => {});
+const applyReferenceLinksMock = vi.fn(async (_arg?: unknown) => {});
+
+/** Builds a minimal FNote-like object with the given docName label. */
+function fakeNote(docName: string | null) {
+ return { getLabelValue: (name: string) => (name === "docName" ? docName : null) } as any;
+}
+
+/**
+ * Overrides jQuery's `.load(url, cb)` so we can drive the callback deterministically.
+ * The handler receives the requested url and the jQuery element so it can inject HTML.
+ */
+function stubLoad(handler: (url: string, $el: JQuery<HTMLElement>) => { status?: string } | void) {
+ return vi.spyOn($.fn, "load").mockImplementation(function (this: JQuery<HTMLElement>, url: any, cb?: any) {
+ const result = handler(url, this) ?? {};
+ const status = result.status ?? "success";
+ // jQuery invokes the callback with (responseText, status, xhr).
+ cb?.call(this, this.html(), status, {});
+ return this;
+ } as any);
+}
describe("isValidDocName", () => {
it("accepts valid docNames", () => {
@@ -29,3 +63,91 @@ describe("isValidDocName", () => {
expect(isValidDocName("%2e%2e%2f%2e%2e%2fapi")).toBe(false);
});
});
+
+describe("renderDoc", () => {
+ beforeEach(() => {
+ mockedLanguage = "en";
+ formatCodeBlocksMock.mockClear();
+ applyReferenceLinksMock.mockClear();
+ (window as any).glob = { isStandalone: false, isDev: false, assetPath: "assets" };
+ });
+
+ afterEach(() => {
+ vi.restoreAllMocks();
+ });
+
+ it("resolves with an empty container when the note has no docName (load is never called)", async () => {
+ const loadSpy = stubLoad(() => {});
+ const $content = await renderDoc(fakeNote(null));
+ expect($content.length).toBe(1);
+ expect(loadSpy).not.toHaveBeenCalled();
+ });
+
+ it("resolves with an empty container and logs when the docName is invalid", async () => {
+ const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {});
+ const loadSpy = stubLoad(() => {});
+ const $content = await renderDoc(fakeNote("../etc/passwd"));
+ expect($content.length).toBe(1);
+ expect(loadSpy).not.toHaveBeenCalled();
+ expect(errorSpy).toHaveBeenCalledWith(expect.stringContaining("Invalid docName"));
+ });
+
+ it("loads the localized doc, rewrites relative image src, and runs post-processing", async () => {
+ mockedLanguage = "de";
+ const loadSpy = stubLoad((_url, $el) => {
+ $el.html(`<img src="pic.png"><a class="reference-link">x</a>`);
+ });
+
+ const $content = await renderDoc(fakeNote("Quick Start"));
+
+ // URL is base/doc_notes/<lang>/<docName with %20>.html
+ expect(loadSpy.mock.calls[0][0]).toBe("assets/doc_notes/de/Quick%20Start.html");
+ // The relative image src is rewritten to be prefixed with the doc directory.
+ expect($content.find("img").attr("src")).toBe("assets/doc_notes/de/pic.png");
+ expect(formatCodeBlocksMock).toHaveBeenCalledTimes(1);
+ expect(applyReferenceLinksMock).toHaveBeenCalledTimes(1);
+ });
+
+ it("forces English for User Guide docs regardless of the current language", async () => {
+ mockedLanguage = "fr";
+ const loadSpy = stubLoad(() => {});
+ await renderDoc(fakeNote("User Guide/Quick Start"));
+ expect(loadSpy.mock.calls[0][0]).toBe("assets/doc_notes/en/User%20Guide/Quick%20Start.html");
+ });
+
+ it("falls back to the English doc when the localized load errors", async () => {
+ mockedLanguage = "de";
+ const requested: string[] = [];
+ const loadSpy = stubLoad((url) => {
+ requested.push(url);
+ // First (German) request errors; the English fallback succeeds.
+ return url.includes("/de/") ? { status: "error" } : {};
+ });
+
+ const $content = await renderDoc(fakeNote("Quick Start"));
+
+ expect(requested).toEqual([
+ "assets/doc_notes/de/Quick%20Start.html",
+ "assets/doc_notes/en/Quick%20Start.html"
+ ]);
+ expect($content.length).toBe(1);
+ expect(loadSpy).toHaveBeenCalledTimes(2);
+ // processContent runs for the fallback url.
+ expect(formatCodeBlocksMock).toHaveBeenCalledTimes(1);
+ expect(applyReferenceLinksMock).toHaveBeenCalledTimes(1);
+ });
+
+ it("uses the server-assets base path in standalone mode", async () => {
+ (window as any).glob = { isStandalone: true, isDev: false, assetPath: "assets" };
+ const loadSpy = stubLoad(() => {});
+ await renderDoc(fakeNote("Quick Start"));
+ expect(loadSpy.mock.calls[0][0]).toBe("server-assets/doc_notes/en/Quick%20Start.html");
+ });
+
+ it("uses the parent of assetPath in dev mode", async () => {
+ (window as any).glob = { isStandalone: false, isDev: true, assetPath: "assets" };
+ const loadSpy = stubLoad(() => {});
+ await renderDoc(fakeNote("Quick Start"));
+ expect(loadSpy.mock.calls[0][0]).toBe("assets/../doc_notes/en/Quick%20Start.html");
+ });
+});
diff --git a/apps/client/src/services/doc_renderer.ts b/apps/client/src/services/doc_renderer.ts
index a926ee223a..bdb08fdfa0 100644
--- a/apps/client/src/services/doc_renderer.ts
+++ b/apps/client/src/services/doc_renderer.ts
@@ -28,6 +28,7 @@ export default function renderDoc(note: FNote) {
if (status === "error") {
const fallbackUrl = getUrl(docName, "en");
+ /* v8 ignore next 8 -- the else branch is unreachable: fallbackUrl only differs from the primary url by language, so if the primary url was valid (we got here from a successful .load call) the "en" fallback url is valid too and never null */
if (fallbackUrl) {
$content.load(fallbackUrl, async () => {
await processContent(fallbackUrl, $content);
diff --git a/apps/client/src/services/experimental_features.spec.ts b/apps/client/src/services/experimental_features.spec.ts
new file mode 100644
index 0000000000..fd70995279
--- /dev/null
+++ b/apps/client/src/services/experimental_features.spec.ts
@@ -0,0 +1,126 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+// Shared, mutable control state for the utils mock. `vi.hoisted` runs before
+// the hoisted `vi.mock` factory, so the factory can safely reference it.
+const ctrl = vi.hoisted(() => ({ standalone: false, mobile: false }));
+
+// Partial-mock ./utils so we can flip `isStandalone` (a const in the target,
+// read here as a live getter) and `isMobile` at runtime, while keeping the
+// rest of the real module intact (e.g. `isShare` used by options.ts).
+vi.mock("./utils.js", async (orig) => {
+ const actual = (await orig()) as Record<string, unknown>;
+ return {
+ ...actual,
+ isMobile: () => ctrl.mobile,
+ get isStandalone() {
+ return ctrl.standalone;
+ }
+ };
+});
+
+// `enabledFeatures` is module-level cached on first read of getEnabledFeatures,
+// so each scenario re-imports a fresh module copy. The fresh copy binds to a
+// fresh `options` singleton, so we re-import and spy on THAT instance.
+async function freshModule(stored: unknown, isNewLayout: boolean) {
+ vi.resetModules();
+ const options = (await import("./options.js")).default;
+ vi.spyOn(options, "get").mockReturnValue(
+ typeof stored === "string" ? stored : JSON.stringify(stored)
+ );
+ vi.spyOn(options, "is").mockReturnValue(isNewLayout);
+ const mod = (await import("./experimental_features.js")) as typeof import("./experimental_features.js");
+ return { mod, options };
+}
+
+describe("experimental_features", () => {
+ beforeEach(() => {
+ ctrl.standalone = false;
+ ctrl.mobile = false;
+ vi.restoreAllMocks();
+ });
+
+ it("lists all features when not standalone, hides llm in standalone", async () => {
+ const { mod } = await freshModule([], false);
+
+ ctrl.standalone = false;
+ expect(mod.getAvailableExperimentalFeatures().map((f) => f.id)).toEqual(["new-layout", "llm"]);
+
+ ctrl.standalone = true;
+ expect(mod.getAvailableExperimentalFeatures().map((f) => f.id)).toEqual(["new-layout"]);
+ });
+
+ it("new-layout is enabled via mobile or the newLayout option", async () => {
+ // neither mobile nor option -> disabled
+ const { mod } = await freshModule([], false);
+ ctrl.mobile = false;
+ expect(mod.isExperimentalFeatureEnabled("new-layout")).toBe(false);
+
+ // mobile short-circuits to enabled
+ ctrl.mobile = true;
+ expect(mod.isExperimentalFeatureEnabled("new-layout")).toBe(true);
+
+ // not mobile but the option is true -> enabled
+ const opt = await freshModule([], true);
+ ctrl.mobile = false;
+ expect(opt.mod.isExperimentalFeatureEnabled("new-layout")).toBe(true);
+ });
+
+ it("llm is always disabled in standalone mode", async () => {
+ const { mod } = await freshModule(["llm"], false);
+ ctrl.standalone = true;
+ expect(mod.isExperimentalFeatureEnabled("llm")).toBe(false);
+ });
+
+ it("non-standalone llm enablement is driven by the persisted feature set", async () => {
+ ctrl.standalone = false;
+
+ const enabled = await freshModule(["llm"], false);
+ expect(enabled.mod.isExperimentalFeatureEnabled("llm")).toBe(true);
+
+ const disabled = await freshModule([], false);
+ expect(disabled.mod.isExperimentalFeatureEnabled("llm")).toBe(false);
+ });
+
+ it("drops new-layout from the persisted set and re-derives it separately", async () => {
+ ctrl.standalone = false;
+ ctrl.mobile = false;
+
+ // new-layout in the stored set is stripped; only llm survives, and
+ // with the option off it is not re-added
+ const stripped = await freshModule(["new-layout", "llm"], false);
+ expect(stripped.mod.getEnabledExperimentalFeatureIds()).toEqual(["llm"]);
+
+ // newLayout option true re-adds "new-layout"
+ const readded = await freshModule(["llm"], true);
+ expect(readded.mod.getEnabledExperimentalFeatureIds().sort()).toEqual(["llm", "new-layout"]);
+ });
+
+ it("adds new-layout via mobile and filters llm out in standalone", async () => {
+ const { mod } = await freshModule(["llm"], false);
+ ctrl.standalone = true;
+ ctrl.mobile = true;
+ // mobile -> new-layout added; standalone -> llm removed
+ expect(mod.getEnabledExperimentalFeatureIds()).toEqual(["new-layout"]);
+ });
+
+ it("warns and treats the set as empty when persisted JSON is invalid", async () => {
+ ctrl.standalone = false;
+ ctrl.mobile = false;
+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
+ const { mod } = await freshModule("not-json", false);
+ expect(mod.getEnabledExperimentalFeatureIds()).toEqual([]);
+ expect(warn).toHaveBeenCalled();
+ });
+
+ it("toggleExperimentalFeature adds/removes a feature and persists the set", async () => {
+ ctrl.standalone = false;
+ const { mod, options } = await freshModule([], false);
+ const save = vi.spyOn(options, "save").mockResolvedValue(undefined);
+
+ await mod.toggleExperimentalFeature("llm", true);
+ expect(save).toHaveBeenLastCalledWith("experimentalFeatures", JSON.stringify(["llm"]));
+
+ await mod.toggleExperimentalFeature("llm", false);
+ expect(save).toHaveBeenLastCalledWith("experimentalFeatures", JSON.stringify([]));
+ });
+});
diff --git a/apps/client/src/services/file_watcher.spec.ts b/apps/client/src/services/file_watcher.spec.ts
new file mode 100644
index 0000000000..00296926d3
--- /dev/null
+++ b/apps/client/src/services/file_watcher.spec.ts
@@ -0,0 +1,105 @@
+import type { WebSocketMessage } from "@triliumnext/commons";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+// Capture the callback that file_watcher registers via ws.subscribeToMessages
+// at module load. The global setup mock discards it, so we provide our own.
+// These are wrapped in vi.hoisted so they exist when the hoisted vi.mock
+// factories below reference them.
+const { wsState, triggerEvent } = vi.hoisted(() => ({
+ wsState: {
+ subscribedCallback: undefined as
+ | ((message: WebSocketMessage) => Promise<void> | void)
+ | undefined
+ },
+ triggerEvent: vi.fn()
+}));
+
+vi.mock("./ws.js", () => ({
+ default: {
+ subscribeToMessages(callback: (message: WebSocketMessage) => void) {
+ wsState.subscribedCallback = callback;
+ }
+ }
+}));
+
+vi.mock("../components/app_context.js", () => ({
+ default: { triggerEvent }
+}));
+
+// Import AFTER the mocks are declared (vi.mock is hoisted).
+import fileWatcher from "./file_watcher.js";
+
+function makeUpdate(entityType: string, entityId: string): WebSocketMessage {
+ return {
+ type: "openedFileUpdated",
+ entityType,
+ entityId,
+ lastModifiedMs: 1234,
+ filePath: `/tmp/${entityId}`
+ } as WebSocketMessage;
+}
+
+describe("file_watcher", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it("registers a ws message subscriber on load", () => {
+ expect(typeof wsState.subscribedCallback).toBe("function");
+ });
+
+ it("ignores messages that are not openedFileUpdated", async () => {
+ await wsState.subscribedCallback!({ type: "ping" } as WebSocketMessage);
+ expect(triggerEvent).not.toHaveBeenCalled();
+ });
+
+ it("stores the update, triggers the event, and exposes it via getFileModificationStatus", async () => {
+ await wsState.subscribedCallback!(makeUpdate("notes", "noteA"));
+
+ expect(triggerEvent).toHaveBeenCalledWith("openedFileUpdated", {
+ entityType: "notes",
+ entityId: "noteA",
+ lastModifiedMs: 1234,
+ filePath: "/tmp/noteA"
+ });
+
+ const status = fileWatcher.getFileModificationStatus("notes", "noteA");
+ expect(status).toMatchObject({ entityType: "notes", entityId: "noteA" });
+ });
+
+ it("handles both notes and attachments entity types independently", async () => {
+ await wsState.subscribedCallback!(makeUpdate("attachments", "attB"));
+ expect(fileWatcher.getFileModificationStatus("attachments", "attB")).toMatchObject({
+ entityId: "attB"
+ });
+ // notes bucket is unaffected.
+ expect(fileWatcher.getFileModificationStatus("notes", "attB")).toBeUndefined();
+ });
+
+ it("fileModificationUploaded removes a stored status", async () => {
+ await wsState.subscribedCallback!(makeUpdate("notes", "noteC"));
+ expect(fileWatcher.getFileModificationStatus("notes", "noteC")).toBeDefined();
+
+ fileWatcher.fileModificationUploaded("notes", "noteC");
+ expect(fileWatcher.getFileModificationStatus("notes", "noteC")).toBeUndefined();
+ });
+
+ it("ignoreModification removes a stored status", async () => {
+ await wsState.subscribedCallback!(makeUpdate("attachments", "attD"));
+ expect(fileWatcher.getFileModificationStatus("attachments", "attD")).toBeDefined();
+
+ fileWatcher.ignoreModification("attachments", "attD");
+ expect(fileWatcher.getFileModificationStatus("attachments", "attD")).toBeUndefined();
+ });
+
+ it("throws on an unrecognized entity type via the public API", () => {
+ expect(() => fileWatcher.getFileModificationStatus("bogus", "x")).toThrow(/Unrecognized type 'bogus'/);
+ expect(() => fileWatcher.fileModificationUploaded("bogus", "x")).toThrow(/should be 'notes' or 'attachments'/);
+ expect(() => fileWatcher.ignoreModification("bogus", "x")).toThrow(/Unrecognized type/);
+ });
+
+ it("propagates the unrecognized-type error from the ws handler", async () => {
+ await expect(wsState.subscribedCallback!(makeUpdate("bogus", "x"))).rejects.toThrow(/Unrecognized type 'bogus'/);
+ expect(triggerEvent).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/client/src/services/focus.spec.ts b/apps/client/src/services/focus.spec.ts
new file mode 100644
index 0000000000..1094e65089
--- /dev/null
+++ b/apps/client/src/services/focus.spec.ts
@@ -0,0 +1,69 @@
+import { afterEach, describe, expect, it, vi } from "vitest";
+import $ from "jquery";
+
+import { focusSavedElement, saveFocusedElement } from "./focus.js";
+
+afterEach(() => {
+ document.body.innerHTML = "";
+ vi.restoreAllMocks();
+});
+
+describe("focus service", () => {
+ it("does nothing when no element was saved", () => {
+ // Nothing focused -> $(":focus") is empty, so the saved element is falsy and focusSavedElement returns early.
+ saveFocusedElement();
+ expect(() => focusSavedElement()).not.toThrow();
+ });
+
+ it("restores focus to a plain saved element", () => {
+ const $input = $("<input type='text'>").appendTo(document.body);
+ const el = $input[0] as HTMLInputElement;
+ el.focus();
+ expect(document.activeElement).toBe(el);
+
+ saveFocusedElement();
+
+ // Move focus elsewhere, then restore it.
+ const $other = $("<input type='text'>").appendTo(document.body);
+ ($other[0] as HTMLInputElement).focus();
+ expect(document.activeElement).toBe($other[0]);
+
+ focusSavedElement();
+ expect(document.activeElement).toBe(el);
+
+ // After restoring, the saved element is cleared -> calling again is a no-op.
+ ($other[0] as HTMLInputElement).focus();
+ focusSavedElement();
+ expect(document.activeElement).toBe($other[0]);
+ });
+
+ it("focuses the CKEditor instance when the saved element is a ck element", () => {
+ const focusSpy = vi.fn();
+ const editorInstance = { editing: { view: { focus: focusSpy } } };
+
+ const $editable = $("<div class='ck-editor__editable'>").appendTo(document.body);
+ // jQuery .prop() reads from the DOM property bag.
+ $editable.prop("ckeditorInstance", editorInstance);
+ // The focused element carries the "ck" class and lives inside the editable.
+ const $ck = $("<div class='ck' tabindex='0'>").appendTo($editable);
+ ($ck[0] as HTMLElement).focus();
+
+ saveFocusedElement();
+ focusSavedElement();
+
+ expect(focusSpy).toHaveBeenCalledTimes(1);
+ });
+
+ it("logs when the ck element has no resolvable CKEditor instance", () => {
+ const logSpy = vi.spyOn(console, "log").mockImplementation(() => {});
+
+ // A ck element with no .ck-editor__editable ancestor -> editor lookup yields undefined.
+ const $ck = $("<div class='ck' tabindex='0'>").appendTo(document.body);
+ ($ck[0] as HTMLElement).focus();
+
+ saveFocusedElement();
+ focusSavedElement();
+
+ expect(logSpy).toHaveBeenCalledWith("Could not find CKEditor instance to focus last element");
+ });
+});
diff --git a/apps/client/src/services/froca.spec.ts b/apps/client/src/services/froca.spec.ts
new file mode 100644
index 0000000000..f0dee33d5c
--- /dev/null
+++ b/apps/client/src/services/froca.spec.ts
@@ -0,0 +1,545 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+import appContext from "../components/app_context.js";
+import FNote from "../entities/fnote.js";
+import { buildNote } from "../test/easy-froca";
+import froca from "./froca";
+import server from "./server.js";
+
+// `logError` / `logInfo` are window globals referenced by froca; ensure they exist.
+(globalThis as any).logError = (globalThis as any).logError ?? (() => {});
+(globalThis as any).logInfo = (globalThis as any).logInfo ?? (() => {});
+
+const realServerGet = server.get;
+const realServerPost = server.post;
+const realServerGetSilent = server.getWithSilentNotFound;
+const realTriggerEvent = appContext.triggerEvent;
+
+beforeEach(() => {
+ vi.restoreAllMocks();
+ // Keep appContext side-effects out of these unit tests.
+ appContext.triggerEvent = vi.fn(async () => []) as typeof appContext.triggerEvent;
+});
+
+afterEach(() => {
+ server.get = realServerGet;
+ server.post = realServerPost;
+ server.getWithSilentNotFound = realServerGetSilent;
+ appContext.triggerEvent = realTriggerEvent;
+});
+
+describe("loadInitialTree", () => {
+ it("returns early when the database is not initialized", async () => {
+ (globalThis as any).glob.dbInitialized = false;
+ server.get = vi.fn(async () => {
+ throw new Error("should not be called");
+ }) as typeof server.get;
+
+ await expect(froca.loadInitialTree()).resolves.toBeUndefined();
+ expect(server.get).not.toHaveBeenCalled();
+ });
+
+ it("clears and re-populates the cache from the tree endpoint when initialized", async () => {
+ (globalThis as any).glob.dbInitialized = true;
+ const noteId = "init-tree-note";
+ server.get = vi.fn(async () => ({
+ notes: [{ noteId, title: "Root", type: "text", mime: "text/html", isProtected: false, blobId: "" }],
+ branches: [],
+ attributes: []
+ })) as typeof server.get;
+
+ await froca.loadInitialTree();
+
+ expect(server.get).toHaveBeenCalledWith("tree");
+ expect(froca.notes[noteId]).toBeInstanceOf(FNote);
+ (globalThis as any).glob.dbInitialized = false;
+ });
+});
+
+describe("loadSubTree", () => {
+ it("fetches the subtree and returns the requested note", async () => {
+ const noteId = "subtree-target";
+ server.get = vi.fn(async () => ({
+ notes: [{ noteId, title: "Sub", type: "text", mime: "text/html", isProtected: false, blobId: "" }],
+ branches: [],
+ attributes: []
+ })) as typeof server.get;
+
+ const note = await froca.loadSubTree(noteId);
+
+ expect(server.get).toHaveBeenCalledWith(`tree?subTreeNoteId=${noteId}`);
+ expect(note).toBe(froca.notes[noteId]);
+ });
+});
+
+describe("addResp", () => {
+ function row(noteId: string, type = "text") {
+ return { noteId, title: noteId, type, mime: "text/html", isProtected: false, blobId: "" } as any;
+ }
+
+ it("creates new notes and wires branches + attributes + relation target", () => {
+ const parentId = "ar-parent";
+ const childId = "ar-child";
+ const targetId = "ar-target";
+
+ froca.addResp({
+ notes: [row(parentId), row(childId), row(targetId)],
+ branches: [
+ {
+ branchId: `${parentId}-${childId}`,
+ noteId: childId,
+ parentNoteId: parentId,
+ notePosition: 10,
+ fromSearchNote: false
+ } as any
+ ],
+ attributes: [
+ { attributeId: "ar-attr", noteId: childId, type: "label", name: "color", value: "red", position: 0, isInheritable: false } as any,
+ { attributeId: "ar-rel", noteId: childId, type: "relation", name: "link", value: targetId, position: 1, isInheritable: false } as any
+ ]
+ });
+
+ const parent = froca.notes[parentId];
+ const child = froca.notes[childId];
+ const target = froca.notes[targetId];
+
+ expect(parent.children).toContain(childId);
+ expect(child.parents).toContain(parentId);
+ expect(child.attributes).toContain("ar-attr");
+ expect(child.attributes).toContain("ar-rel");
+ expect(target.targetRelations).toContain("ar-rel");
+ });
+
+ it("is idempotent for attributes and relation targets already tracked", () => {
+ const noteId = "ar-idem";
+ const targetId = "ar-idem-target";
+ froca.addResp({ notes: [row(noteId), row(targetId)], branches: [], attributes: [] });
+
+ const attrRows = [
+ { attributeId: "ar-idem-attr", noteId, type: "label", name: "c", value: "v", position: 0, isInheritable: false } as any,
+ { attributeId: "ar-idem-rel", noteId, type: "relation", name: "r", value: targetId, position: 1, isInheritable: false } as any
+ ];
+
+ froca.addResp({ notes: [], branches: [], attributes: attrRows });
+ froca.addResp({ notes: [], branches: [], attributes: attrRows });
+
+ const note = froca.notes[noteId];
+ const target = froca.notes[targetId];
+ expect(note.attributes.filter((a) => a === "ar-idem-attr")).toHaveLength(1);
+ expect(target.targetRelations.filter((a) => a === "ar-idem-rel")).toHaveLength(1);
+ });
+
+ it("ignores branches/attributes whose related notes are not loaded", () => {
+ froca.addResp({
+ notes: [],
+ branches: [
+ { branchId: "orphan-branch", noteId: "ghost-child", parentNoteId: "ghost-parent", notePosition: 0, fromSearchNote: false } as any
+ ],
+ attributes: [
+ { attributeId: "orphan-attr", noteId: "ghost-note", type: "relation", name: "r", value: "ghost-target", position: 0, isInheritable: false } as any
+ ]
+ });
+
+ expect(froca.branches["orphan-branch"]).toBeDefined();
+ // No note was wired up since neither parent nor child are loaded.
+ expect(froca.notes["ghost-child"]).toBeUndefined();
+ });
+
+ it("rebuilds children and real parents for an existing non-search note, preserving virtual parents", () => {
+ // Build the real parent -> existing -> child structure as one tree so references stay stable.
+ const realParent = buildNote({
+ id: "ar-existing-realparent",
+ title: "RealParent",
+ children: [
+ {
+ id: "ar-existing",
+ title: "Existing",
+ children: [{ id: "ar-existing-child", title: "Child" }]
+ }
+ ]
+ });
+ const note = froca.notes["ar-existing"];
+ expect(note.children).toContain("ar-existing-child");
+ expect(note.parents).toContain(realParent.noteId);
+
+ // Add a virtual (search) parent branch manually.
+ const searchParent = buildNote({ id: "ar-existing-searchparent", title: "SearchParent" });
+ const virtBranchId = "virt-ar-existing-searchparent-ar-existing";
+ froca.addResp({
+ notes: [],
+ branches: [
+ {
+ branchId: virtBranchId,
+ noteId: "ar-existing",
+ parentNoteId: searchParent.noteId,
+ notePosition: 10,
+ fromSearchNote: true
+ } as any
+ ],
+ attributes: []
+ });
+ expect(note.parents).toContain(searchParent.noteId);
+
+ // Re-send the existing note: children should be wiped, real parent removed, virtual parent kept.
+ froca.addResp({
+ notes: [{ noteId: "ar-existing", title: "Existing v2", type: "text", mime: "text/html", isProtected: false, blobId: "" } as any],
+ branches: [],
+ attributes: []
+ });
+
+ expect(note.title).toBe("Existing v2");
+ expect(note.children).toEqual([]);
+ expect(note.parents).not.toContain(realParent.noteId);
+ expect(note.parents).toContain(searchParent.noteId);
+ });
+
+ it("skips child cleanup for a child id with no loaded note object", () => {
+ const note = buildNote({ id: "ar-dangling", title: "Dangling" });
+ // Inject a child id that has no backing note in the cache.
+ note.children = ["ar-dangling-ghost"];
+ note.childToBranch = { "ar-dangling-ghost": "ar-dangling-ghost-branch" };
+
+ froca.addResp({
+ notes: [{ noteId: "ar-dangling", title: "Dangling v2", type: "text", mime: "text/html", isProtected: false, blobId: "" } as any],
+ branches: [],
+ attributes: []
+ });
+
+ expect(note.children).toEqual([]);
+ expect(froca.notes["ar-dangling-ghost"]).toBeUndefined();
+ });
+
+ it("does not wipe children for an existing search note", () => {
+ const searchNote = buildNote({
+ id: "ar-search",
+ title: "Saved search",
+ type: "search",
+ children: [{ id: "ar-search-result", title: "Result" }]
+ });
+ expect(searchNote.children).toContain("ar-search-result");
+
+ froca.addResp({
+ notes: [{ noteId: "ar-search", title: "Saved search v2", type: "search", mime: "text/html", isProtected: false, blobId: "" } as any],
+ branches: [],
+ attributes: []
+ });
+
+ expect(searchNote.children).toContain("ar-search-result");
+ });
+
+ it("drops a real parent whose branch entry is missing", () => {
+ const note = buildNote({
+ id: "ar-missing-branch",
+ title: "Note",
+ children: [{ id: "ar-missing-branch-child", title: "Child" }]
+ });
+ const child = froca.notes["ar-missing-branch-child"];
+ // Remove the branch object but keep the childToBranch mapping so `!branch` is hit.
+ const branchId = note.childToBranch["ar-missing-branch-child"];
+ delete froca.branches[branchId];
+
+ froca.addResp({
+ notes: [{ noteId: "ar-missing-branch-child", title: "Child v2", type: "text", mime: "text/html", isProtected: false, blobId: "" } as any],
+ branches: [],
+ attributes: []
+ });
+
+ expect(child.parents).not.toContain("ar-missing-branch");
+ });
+});
+
+describe("reloadNotes", () => {
+ it("returns early for an empty list without hitting the server", async () => {
+ server.post = vi.fn(async () => ({ notes: [], branches: [], attributes: [] })) as typeof server.post;
+ await froca.reloadNotes([]);
+ expect(server.post).not.toHaveBeenCalled();
+ });
+
+ it("dedupes ids, posts to tree/load, and triggers notesReloaded", async () => {
+ server.post = vi.fn(async () => ({
+ notes: [{ noteId: "reload-1", title: "R", type: "text", mime: "text/html", isProtected: false, blobId: "" }],
+ branches: [],
+ attributes: []
+ })) as typeof server.post;
+
+ await froca.reloadNotes(["reload-1", "reload-1"]);
+
+ expect(server.post).toHaveBeenCalledWith("tree/load", { noteIds: ["reload-1"] });
+ expect(appContext.triggerEvent).toHaveBeenCalledWith("notesReloaded", { noteIds: ["reload-1"] });
+ });
+});
+
+describe("loadSearchNote", () => {
+ it("returns undefined for a missing note or a non-search note", async () => {
+ await expect(froca.loadSearchNote("none")).resolves.toBeUndefined();
+
+ const text = buildNote({ id: "ls-text", title: "Text", type: "text" });
+ await expect(froca.loadSearchNote(text.noteId)).resolves.toBeUndefined();
+ });
+
+ it("throws when the server returns a non-array search result", async () => {
+ const search = buildNote({ id: "ls-bad", title: "Search", type: "search" });
+ server.get = vi.fn(async () => ({ searchResultNoteIds: "boom", highlightedTokens: [], error: null })) as typeof server.get;
+ await expect(froca.loadSearchNote(search.noteId)).rejects.toThrow(/failed/);
+ });
+
+ it("populates virtual child branches from search results", async () => {
+ const search = buildNote({ id: "ls-ok", title: "Search", type: "search" });
+ const result = buildNote({ id: "ls-result", title: "Result", type: "text" });
+ // Pre-seed a stale virtual child to verify it gets reset.
+ search.children = ["stale"];
+ search.childToBranch = { stale: "virt-stale" };
+
+ server.get = vi.fn(async () => ({
+ searchResultNoteIds: [result.noteId],
+ highlightedTokens: ["token"],
+ error: null
+ })) as typeof server.get;
+
+ const out = await froca.loadSearchNote(search.noteId);
+
+ expect(out).toEqual({ error: null });
+ expect(search.searchResultsLoaded).toBe(true);
+ expect(search.highlightedTokens).toEqual(["token"]);
+ expect(search.children).toContain(result.noteId);
+ expect(search.children).not.toContain("stale");
+ });
+
+ it("tolerates the note disappearing from the cache mid-load", async () => {
+ const search = buildNote({ id: "ls-gone", title: "Search", type: "search" });
+ const result = buildNote({ id: "ls-gone-result", title: "Result", type: "text" });
+
+ server.get = vi.fn(async () => {
+ // Simulate the note being evicted from froca during the request.
+ delete froca.notes["ls-gone"];
+ return { searchResultNoteIds: [result.noteId], highlightedTokens: [], error: "oops" };
+ }) as typeof server.get;
+
+ const out = await froca.loadSearchNote(search.noteId);
+ expect(out).toEqual({ error: "oops" });
+ expect(froca.notes["ls-gone"].searchResultsLoaded).toBe(true);
+ });
+});
+
+describe("getNotesFromCache", () => {
+ it("returns cached notes, traces and drops unknown ids, and stays silent when asked", () => {
+ const note = buildNote({ id: "gfc-note", title: "N" });
+ const trace = vi.spyOn(console, "trace").mockImplementation(() => {});
+
+ const found = froca.getNotesFromCache([note.noteId, "gfc-missing"]);
+ expect(found).toEqual([note]);
+ expect(trace).toHaveBeenCalled();
+
+ trace.mockClear();
+ const silent = froca.getNotesFromCache(["gfc-missing-2"], true);
+ expect(silent).toEqual([]);
+ expect(trace).not.toHaveBeenCalled();
+ });
+});
+
+describe("getNotes / getNote / noteExists / getNoteFromCache", () => {
+ it("getNotes returns [] for empty input", async () => {
+ await expect(froca.getNotes([])).resolves.toEqual([]);
+ });
+
+ it("getNotes reloads missing ids, dedupes, and filters unknowns", async () => {
+ const known = buildNote({ id: "gn-known", title: "Known" });
+ server.post = vi.fn(async () => ({
+ notes: [{ noteId: "gn-loaded", title: "Loaded", type: "text", mime: "text/html", isProtected: false, blobId: "" }],
+ branches: [],
+ attributes: []
+ })) as typeof server.post;
+ const trace = vi.spyOn(console, "trace").mockImplementation(() => {});
+
+ const notes = await froca.getNotes([known.noteId, "gn-loaded", "gn-loaded", "gn-unresolved"]);
+
+ expect(server.post).toHaveBeenCalledWith("tree/load", { noteIds: ["gn-loaded", "gn-unresolved"] });
+ expect(notes.map((n) => n.noteId).sort()).toEqual(["gn-known", "gn-loaded"]);
+ expect(trace).toHaveBeenCalled();
+ });
+
+ it("getNotes silently drops unknowns when silentNotFoundError is set", async () => {
+ server.post = vi.fn(async () => ({ notes: [], branches: [], attributes: [] })) as typeof server.post;
+ const trace = vi.spyOn(console, "trace").mockImplementation(() => {});
+ const notes = await froca.getNotes(["gn-silent"], true);
+ expect(notes).toEqual([]);
+ expect(trace).not.toHaveBeenCalled();
+ });
+
+ it("noteExists reflects whether the note resolves", async () => {
+ const note = buildNote({ id: "ne-yes", title: "Yes" });
+ server.post = vi.fn(async () => ({ notes: [], branches: [], attributes: [] })) as typeof server.post;
+ await expect(froca.noteExists(note.noteId)).resolves.toBe(true);
+ await expect(froca.noteExists("ne-no")).resolves.toBe(false);
+ });
+
+ it("getNote handles 'none', falsy ids, and real ids", async () => {
+ const trace = vi.spyOn(console, "trace").mockImplementation(() => {});
+ await expect(froca.getNote("none")).resolves.toBeNull();
+ await expect(froca.getNote("")).resolves.toBeNull();
+ expect(trace).toHaveBeenCalledTimes(2);
+
+ const note = buildNote({ id: "gn-real", title: "Real" });
+ await expect(froca.getNote(note.noteId)).resolves.toBe(note);
+ });
+
+ it("getNoteFromCache throws on empty id and returns the cached note otherwise", () => {
+ expect(() => froca.getNoteFromCache("")).toThrow(/Empty noteId/);
+ const note = buildNote({ id: "gnfc", title: "Cached" });
+ expect(froca.getNoteFromCache(note.noteId)).toBe(note);
+ });
+});
+
+describe("getBranches / getBranch", () => {
+ it("returns existing branches and filters/handles missing ones", () => {
+ const note = buildNote({
+ id: "gb-parent",
+ title: "Parent",
+ children: [{ id: "gb-child", title: "Child" }]
+ });
+ const branchId = note.childToBranch["gb-child"];
+ const logErrorSpy = vi.spyOn(globalThis as any, "logError").mockImplementation(() => {});
+
+ const branches = froca.getBranches([branchId, "gb-missing"]);
+ expect(branches).toHaveLength(1);
+ expect(branches[0].branchId).toBe(branchId);
+ expect(logErrorSpy).toHaveBeenCalledTimes(1);
+
+ logErrorSpy.mockClear();
+ const silent = froca.getBranches(["gb-missing-2"], true);
+ expect(silent).toEqual([]);
+ expect(logErrorSpy).not.toHaveBeenCalled();
+ });
+});
+
+describe("getBranchId", () => {
+ it("short-circuits the root note", async () => {
+ await expect(froca.getBranchId("anything", "root")).resolves.toBe("none_root");
+ });
+
+ it("resolves the parent->branch mapping for a real child", async () => {
+ const note = buildNote({
+ id: "gbi-parent",
+ title: "Parent",
+ children: [{ id: "gbi-child", title: "Child" }]
+ });
+ const expected = froca.notes["gbi-child"].parentToBranch["gbi-parent"];
+ server.post = vi.fn(async () => ({ notes: [], branches: [], attributes: [] })) as typeof server.post;
+ await expect(froca.getBranchId("gbi-parent", "gbi-child")).resolves.toBe(expected);
+ });
+
+ it("logs and returns null when the child cannot be found", async () => {
+ server.post = vi.fn(async () => ({ notes: [], branches: [], attributes: [] })) as typeof server.post;
+ const logErrorSpy = vi.spyOn(globalThis as any, "logError").mockImplementation(() => {});
+ await expect(froca.getBranchId("gbi-p", "gbi-ghost")).resolves.toBeNull();
+ expect(logErrorSpy).toHaveBeenCalled();
+ });
+});
+
+describe("getAttachment / getAttachmentsForNote / processAttachmentRows", () => {
+ function attRow(attachmentId: string, ownerId = "att-owner") {
+ return {
+ attachmentId,
+ ownerId,
+ role: "file",
+ mime: "text/plain",
+ title: "att",
+ dateModified: "2025-01-01",
+ utcDateModified: "2025-01-01",
+ utcDateScheduledForErasureSince: "2025-01-01",
+ contentLength: 1
+ } as any;
+ }
+
+ it("returns a cached attachment without hitting the server", async () => {
+ froca.attachments["cached-att"] = { attachmentId: "cached-att" } as any;
+ server.getWithSilentNotFound = vi.fn(async () => {
+ throw new Error("should not be called");
+ }) as typeof server.getWithSilentNotFound;
+
+ const att = await froca.getAttachment("cached-att");
+ expect(att).toBe(froca.attachments["cached-att"]);
+ });
+
+ it("loads all attachments for a note and links them to the owner note", async () => {
+ const owner = buildNote({ id: "att-owner", title: "Owner" });
+ server.getWithSilentNotFound = vi.fn(async () => [attRow("loaded-att", owner.noteId)]) as typeof server.getWithSilentNotFound;
+
+ const att = await froca.getAttachment("loaded-att");
+ expect(att?.attachmentId).toBe("loaded-att");
+ expect(server.getWithSilentNotFound).toHaveBeenCalledWith("attachments/loaded-att/all");
+ expect(owner.attachments?.map((a) => a.attachmentId)).toContain("loaded-att");
+ });
+
+ it("does not link attachments when the load returns nothing", async () => {
+ server.getWithSilentNotFound = vi.fn(async () => []) as typeof server.getWithSilentNotFound;
+ const att = await froca.getAttachment("empty-load-att");
+ expect(att).toBeUndefined();
+ });
+
+ it("returns null on not-found when silentNotFoundError is set, otherwise rethrows", async () => {
+ server.getWithSilentNotFound = vi.fn(async () => {
+ throw new Error("404");
+ }) as typeof server.getWithSilentNotFound;
+
+ await expect(froca.getAttachment("missing-att", true)).resolves.toBeNull();
+ await expect(froca.getAttachment("missing-att")).rejects.toThrow("404");
+ });
+
+ it("getAttachmentsForNote maps the rows", async () => {
+ server.get = vi.fn(async () => [attRow("for-note-att")]) as typeof server.get;
+ const out = await froca.getAttachmentsForNote("att-owner");
+ expect(server.get).toHaveBeenCalledWith("notes/att-owner/attachments");
+ expect(out.map((a) => a.attachmentId)).toEqual(["for-note-att"]);
+ });
+
+ it("processAttachmentRows updates existing rows and creates new ones", () => {
+ const first = froca.processAttachmentRows([attRow("proc-att")]);
+ expect(first[0].title).toBe("att");
+
+ const updatedRow = { ...attRow("proc-att"), title: "updated" };
+ const second = froca.processAttachmentRows([updatedRow]);
+ expect(second[0]).toBe(first[0]); // same instance, updated in place
+ expect(second[0].title).toBe("updated");
+ });
+});
+
+describe("getBlob", () => {
+ it("fetches and caches the blob promise, and serves a second call from cache", async () => {
+ server.get = vi.fn(async () => ({ blobId: "blob-1", content: "hi", contentLength: 2 })) as typeof server.get;
+
+ const blob1 = await froca.getBlob("notes", "blob-note");
+ const blob2 = await froca.getBlob("notes", "blob-note");
+
+ expect(server.get).toHaveBeenCalledTimes(1);
+ expect(server.get).toHaveBeenCalledWith("notes/blob-note/blob");
+ expect(blob1).not.toBeNull();
+ expect(blob2).toBe(blob1);
+ });
+
+ it("clears the cached blob promise after the cleanup timeout fires", async () => {
+ vi.useFakeTimers();
+ try {
+ server.get = vi.fn(async () => ({ blobId: "blob-2", content: "x", contentLength: 1 })) as typeof server.get;
+
+ await froca.getBlob("notes", "blob-cleanup");
+ // The .then() that schedules the cleanup setTimeout runs on a microtask.
+ await vi.advanceTimersByTimeAsync(1000);
+
+ expect(froca.blobPromises["notes-blob-cleanup"]).toBeNull();
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it("returns null and logs when the blob request fails", async () => {
+ server.get = vi.fn(async () => {
+ throw new Error("blob boom");
+ }) as typeof server.get;
+ const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {});
+
+ const blob = await froca.getBlob("notes", "blob-fail");
+ expect(blob).toBeNull();
+ expect(errorSpy).toHaveBeenCalled();
+ });
+});
diff --git a/apps/client/src/services/froca_updater.spec.ts b/apps/client/src/services/froca_updater.spec.ts
new file mode 100644
index 0000000000..3e68813fc7
--- /dev/null
+++ b/apps/client/src/services/froca_updater.spec.ts
@@ -0,0 +1,725 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+import appContext from "../components/app_context.js";
+import FAttachment from "../entities/fattachment.js";
+import FAttribute from "../entities/fattribute.js";
+import FBranch from "../entities/fbranch.js";
+import type { EntityChange } from "../server_types.js";
+import froca from "./froca.js";
+import frocaUpdater from "./froca_updater.js";
+import noteAttributeCache from "./note_attribute_cache.js";
+import options from "./options.js";
+import utils from "./utils.js";
+import { buildNote } from "../test/easy-froca.js";
+
+function ec(overrides: Partial<EntityChange>): EntityChange {
+ return {
+ entityName: "notes",
+ entityId: "x",
+ hash: "h",
+ isSynced: false,
+ isErased: false,
+ ...overrides
+ } as EntityChange;
+}
+
+let triggerSpy: ReturnType<typeof vi.fn>;
+let reloadSpy: ReturnType<typeof vi.fn>;
+let reloadNotesSpy: ReturnType<typeof vi.fn>;
+let invalidateSpy: ReturnType<typeof vi.fn>;
+
+beforeEach(() => {
+ triggerSpy = vi.fn(async () => []);
+ appContext.triggerEvent = triggerSpy as typeof appContext.triggerEvent;
+
+ reloadSpy = vi.fn();
+ utils.reloadFrontendApp = reloadSpy as typeof utils.reloadFrontendApp;
+
+ reloadNotesSpy = vi.fn(async () => {});
+ froca.reloadNotes = reloadNotesSpy as typeof froca.reloadNotes;
+
+ invalidateSpy = vi.spyOn(noteAttributeCache, "invalidate") as unknown as ReturnType<typeof vi.fn>;
+});
+
+afterEach(() => {
+ vi.restoreAllMocks();
+});
+
+const process = (changes: EntityChange[]) => frocaUpdater.processEntityChanges(changes);
+
+describe("froca_updater - empty / no-op handling", () => {
+ it("does nothing (no event) when there are no meaningful changes", async () => {
+ // blobs is a NOOP and produces an empty LoadResults
+ await process([ec({ entityName: "blobs", entityId: "blob1", entity: { isDeleted: false } as any })]);
+ expect(triggerSpy).not.toHaveBeenCalled();
+ expect(invalidateSpy).not.toHaveBeenCalled();
+ });
+
+ it("throws a wrapped error for an unknown entityName", async () => {
+ await expect(process([ec({ entityName: "weird" as any, entityId: "z" })]))
+ .rejects.toThrow(/Unknown entityName 'weird'/);
+ });
+});
+
+describe("froca_updater - note changes", () => {
+ it("ignores a note change for a note not in froca", async () => {
+ await process([ec({ entityName: "notes", entityId: "not-loaded-note", entity: {} as any })]);
+ expect(triggerSpy).not.toHaveBeenCalled();
+ });
+
+ it("triggers a full reload when an in-froca note is erased", async () => {
+ const note = buildNote({ title: "Erasable" });
+ await process([ec({ entityName: "notes", entityId: note.noteId, isErased: true })]);
+ expect(reloadSpy).toHaveBeenCalledTimes(1);
+ // event still fires because addNote populated the load results
+ expect(triggerSpy).toHaveBeenCalledTimes(1);
+ expect(note.noteId in froca.notes).toBe(true); // not deleted, early return
+ });
+
+ it("deletes the note from froca when marked deleted", async () => {
+ const note = buildNote({ title: "Doomed" });
+ await process([ec({ entityName: "notes", entityId: note.noteId, entity: { isDeleted: true } as any })]);
+ expect(note.noteId in froca.notes).toBe(false);
+ expect(triggerSpy).toHaveBeenCalledTimes(1);
+ });
+
+ it("updates a note and registers content change when blobId changes and protection is unchanged", async () => {
+ const note = buildNote({ title: "Old" });
+ note.blobId = "oldBlob";
+ froca.blobPromises[`${note.noteId}-content`] = Promise.resolve(null as any);
+ froca.blobPromises["unrelated-key"] = Promise.resolve(null as any);
+
+ const row = {
+ noteId: note.noteId,
+ title: "New",
+ isProtected: false,
+ type: "text",
+ mime: "text/html",
+ blobId: "newBlob"
+ };
+ await process([ec({ entityName: "notes", entityId: note.noteId, componentId: "comp-x", entity: row as any })]);
+
+ expect(note.title).toBe("New");
+ expect(note.blobId).toBe("newBlob");
+ // blob promise key including the noteId is cleared, unrelated one remains
+ expect(`${note.noteId}-content` in froca.blobPromises).toBe(false);
+ expect("unrelated-key" in froca.blobPromises).toBe(true);
+ expect(triggerSpy).toHaveBeenCalledTimes(1);
+ });
+
+ it("does not register content change when protection status changed", async () => {
+ const note = buildNote({ title: "Prot" });
+ note.blobId = "oldBlob";
+ note.isProtected = false;
+ const row = {
+ noteId: note.noteId,
+ title: "Prot",
+ isProtected: true,
+ type: "text",
+ mime: "text/html",
+ blobId: "newBlob2"
+ };
+ await process([ec({ entityName: "notes", entityId: note.noteId, componentId: "comp-y", entity: row as any })]);
+ expect(note.isProtected).toBe(true);
+ expect(note.blobId).toBe("newBlob2");
+ });
+
+ it("updates a note without componentId (no content registration branch)", async () => {
+ const note = buildNote({ title: "NoComp" });
+ note.blobId = "b1";
+ const row = {
+ noteId: note.noteId,
+ title: "NoComp",
+ isProtected: false,
+ type: "text",
+ mime: "text/html",
+ blobId: "b2"
+ };
+ await process([ec({ entityName: "notes", entityId: note.noteId, entity: row as any })]);
+ expect(note.blobId).toBe("b2");
+ });
+});
+
+describe("froca_updater - branch changes", () => {
+ it("triggers a full reload when an in-froca branch is erased", async () => {
+ const parent = buildNote({ title: "P", children: [{ title: "C" }] });
+ const branchId = `${parent.noteId}_${parent.children[0]}`;
+ await process([ec({ entityName: "branches", entityId: branchId, isErased: true })]);
+ expect(reloadSpy).toHaveBeenCalledTimes(1);
+ });
+
+ it("removes a deleted branch and unlinks parent/child", async () => {
+ const parent = buildNote({ title: "Par", children: [{ title: "Chi" }] });
+ const childId = parent.children[0];
+ const branchId = `${parent.noteId}_${childId}`;
+ const child = froca.notes[childId];
+
+ await process([ec({
+ entityName: "branches",
+ entityId: branchId,
+ componentId: "comp-b",
+ entity: { isDeleted: true } as any
+ })]);
+
+ expect(branchId in froca.branches).toBe(false);
+ expect(parent.children.includes(childId)).toBe(false);
+ expect(childId in parent.childToBranch).toBe(false);
+ expect(child.parents.includes(parent.noteId)).toBe(false);
+ expect(parent.noteId in child.parentToBranch).toBe(false);
+ // branch change => attribute-related => invalidate cache + event
+ expect(invalidateSpy).toHaveBeenCalled();
+ expect(triggerSpy).toHaveBeenCalledTimes(1);
+ });
+
+ it("returns early for a deleted branch that is not loaded", async () => {
+ await process([ec({
+ entityName: "branches",
+ entityId: "unknown-branch",
+ entity: { isDeleted: true } as any
+ })]);
+ expect(triggerSpy).not.toHaveBeenCalled();
+ });
+
+ it("updates an existing branch", async () => {
+ const parent = buildNote({ title: "UP", children: [{ title: "UC" }] });
+ const childId = parent.children[0];
+ const branchId = `${parent.noteId}_${childId}`;
+ const row = {
+ branchId,
+ noteId: childId,
+ parentNoteId: parent.noteId,
+ notePosition: 999,
+ fromSearchNote: false,
+ prefix: "pref"
+ };
+ await process([ec({ entityName: "branches", entityId: branchId, entity: row as any })]);
+ expect(froca.branches[branchId].notePosition).toBe(999);
+ expect(froca.branches[branchId].prefix).toBe("pref");
+ });
+
+ it("creates a new branch when both child and parent notes are present", async () => {
+ const parent = buildNote({ title: "NewParent" });
+ const child = buildNote({ title: "NewChild" });
+ const branchId = `new_${child.noteId}`;
+ const row = {
+ branchId,
+ noteId: child.noteId,
+ parentNoteId: parent.noteId,
+ notePosition: 10,
+ fromSearchNote: false
+ };
+ await process([ec({ entityName: "branches", entityId: branchId, componentId: "c1", entity: row as any })]);
+
+ expect(branchId in froca.branches).toBe(true);
+ expect(child.parents.includes(parent.noteId)).toBe(true);
+ expect(parent.children.includes(child.noteId)).toBe(true);
+ });
+
+ it("fetches the parent note via froca.getNote when child exists but parent is missing", async () => {
+ const child = buildNote({ title: "OrphanChild" });
+ const fetchedParent = buildNote({ title: "FetchedParent" });
+ const getNoteSpy = vi.spyOn(froca, "getNote").mockResolvedValue(fetchedParent);
+
+ const branchId = `fetch_${child.noteId}`;
+ const row = {
+ branchId,
+ noteId: child.noteId,
+ parentNoteId: "missing-parent-id",
+ notePosition: 0,
+ fromSearchNote: false
+ };
+ await process([ec({ entityName: "branches", entityId: branchId, entity: row as any })]);
+
+ expect(getNoteSpy).toHaveBeenCalledWith("missing-parent-id");
+ expect(branchId in froca.branches).toBe(true);
+ expect(fetchedParent.children.includes(child.noteId)).toBe(true);
+ });
+
+ it("does not create a branch when neither child nor parent note is present", async () => {
+ const branchId = "ghost-branch";
+ const row = {
+ branchId,
+ noteId: "ghost-child",
+ parentNoteId: "ghost-parent",
+ notePosition: 0,
+ fromSearchNote: false
+ };
+ // root child guard: only fetches parent when childNote exists; here it doesn't
+ await process([ec({ entityName: "branches", entityId: branchId, entity: row as any })]);
+ expect(branchId in froca.branches).toBe(false);
+ });
+
+ it("reloads the parent note when a new branch references an unloaded parent", async () => {
+ const child = buildNote({ title: "ReloadChild" });
+ // parent not in froca => missingNoteIds path
+ const branchId = `reload_${child.noteId}`;
+ const row = {
+ branchId,
+ noteId: child.noteId,
+ parentNoteId: "absent-parent",
+ notePosition: 0,
+ fromSearchNote: false
+ };
+ // avoid the getNote fetch path by stubbing it to return null so branch isn't created via parent
+ vi.spyOn(froca, "getNote").mockResolvedValue(null);
+ await process([ec({ entityName: "branches", entityId: branchId, entity: row as any })]);
+ expect(reloadNotesSpy).toHaveBeenCalledWith(["absent-parent"]);
+ });
+});
+
+describe("froca_updater - note reordering", () => {
+ it("updates branch positions and sorts affected parents", async () => {
+ const parent = buildNote({ title: "RP", children: [{ title: "RC1" }, { title: "RC2" }] });
+ const b1 = `${parent.noteId}_${parent.children[0]}`;
+ const b2 = `${parent.noteId}_${parent.children[1]}`;
+ const sortSpy = vi.spyOn(parent, "sortChildren");
+
+ await process([ec({
+ entityName: "note_reordering",
+ entityId: parent.noteId,
+ componentId: "comp-r",
+ positions: { [b1]: 50, [b2]: 5, "ghost-branch-id": 1 }
+ })]);
+
+ expect(froca.branches[b1].notePosition).toBe(50);
+ expect(froca.branches[b2].notePosition).toBe(5);
+ expect(sortSpy).toHaveBeenCalled();
+ expect(triggerSpy).toHaveBeenCalledTimes(1);
+ });
+
+ it("handles a reordering with no componentId and parent note absent", async () => {
+ const orphanBranchParent = buildNote({ title: "OBP", children: [{ title: "OBC" }] });
+ const b = `${orphanBranchParent.noteId}_${orphanBranchParent.children[0]}`;
+ // remove the parent note from froca so the sort branch is skipped
+ delete froca.notes[orphanBranchParent.noteId];
+ await process([ec({
+ entityName: "note_reordering",
+ entityId: orphanBranchParent.noteId,
+ positions: { [b]: 7 }
+ })]);
+ expect(froca.branches[b].notePosition).toBe(7);
+ });
+});
+
+describe("froca_updater - revisions / options / etapi_tokens", () => {
+ it("adds a revision and fires the event", async () => {
+ await process([ec({ entityName: "revisions", entityId: "rev1", noteId: "n1", componentId: "c" })]);
+ expect(triggerSpy).toHaveBeenCalledTimes(1);
+ });
+
+ it("sets an option and records it, but skips openNoteContexts noise", async () => {
+ const setSpy = vi.spyOn(options, "set").mockImplementation(() => {});
+ await process([
+ ec({ entityName: "options", entityId: "o1", entity: { name: "openNoteContexts", value: "[]" } as any }),
+ ec({ entityName: "options", entityId: "o2", entity: { name: "eraseEntitiesAfterTimeInSeconds", value: "10" } as any })
+ ]);
+ expect(setSpy).toHaveBeenCalledTimes(1);
+ expect(setSpy).toHaveBeenCalledWith("eraseEntitiesAfterTimeInSeconds", "10");
+ expect(triggerSpy).toHaveBeenCalledTimes(1);
+ });
+
+ it("marks etapi token changes", async () => {
+ await process([ec({ entityName: "etapi_tokens", entityId: "tok1", entity: { isDeleted: false } as any })]);
+ expect(triggerSpy).toHaveBeenCalledTimes(1);
+ });
+});
+
+describe("froca_updater - attribute changes", () => {
+ it("triggers a full reload when an in-froca attribute is erased", async () => {
+ const note = buildNote({ title: "AttrNote", "#color": "red" });
+ const attrId = note.attributes[0];
+ await process([ec({ entityName: "attributes", entityId: attrId, isErased: true })]);
+ expect(reloadSpy).toHaveBeenCalledTimes(1);
+ });
+
+ it("removes a deleted relation attribute and unlinks source + target", async () => {
+ const target = buildNote({ title: "Target" });
+ const source = buildNote({ title: "Source", [`~mylink`]: target.noteId } as any);
+ const attrId = source.attributes[0];
+ const attr = froca.attributes[attrId];
+ // Wire the target relation manually (easy-froca does not).
+ target.targetRelations.push(attrId);
+
+ await process([ec({
+ entityName: "attributes",
+ entityId: attrId,
+ componentId: "comp-a",
+ entity: { isDeleted: true } as any
+ })]);
+
+ expect(attrId in froca.attributes).toBe(false);
+ expect(source.attributes.includes(attrId)).toBe(false);
+ expect(target.targetRelations.includes(attrId)).toBe(false);
+ expect(invalidateSpy).toHaveBeenCalled();
+ expect(triggerSpy).toHaveBeenCalledTimes(1);
+
+ // The deleted attr was captured before deletion; type was relation.
+ expect(attr.type).toBe("relation");
+ });
+
+ it("returns early for a deleted attribute that is not loaded", async () => {
+ await process([ec({
+ entityName: "attributes",
+ entityId: "unknown-attr",
+ entity: { isDeleted: true } as any
+ })]);
+ expect(triggerSpy).not.toHaveBeenCalled();
+ });
+
+ it("updates an existing attribute", async () => {
+ const note = buildNote({ title: "UpdAttr", "#size": "small" });
+ const attrId = note.attributes[0];
+ const row = {
+ attributeId: attrId,
+ noteId: note.noteId,
+ type: "label",
+ name: "size",
+ value: "large",
+ isInheritable: false,
+ position: 0
+ };
+ await process([ec({ entityName: "attributes", entityId: attrId, entity: row as any })]);
+ expect(froca.attributes[attrId].value).toBe("large");
+ });
+
+ it("creates a new label attribute linked to its source note", async () => {
+ const note = buildNote({ title: "NewLabelHost" });
+ const attrId = "brand-new-attr";
+ const row = {
+ attributeId: attrId,
+ noteId: note.noteId,
+ type: "label",
+ name: "fresh",
+ value: "v",
+ isInheritable: false,
+ position: 0
+ };
+ await process([ec({ entityName: "attributes", entityId: attrId, componentId: "c", entity: row as any })]);
+ expect(attrId in froca.attributes).toBe(true);
+ expect(note.attributes.includes(attrId)).toBe(true);
+
+ // Re-processing the same create must not duplicate the id in source.attributes.
+ await process([ec({ entityName: "attributes", entityId: attrId, componentId: "c", entity: row as any })]);
+ expect(note.attributes.filter((a) => a === attrId).length).toBe(1);
+ });
+
+ it("creates a new relation attribute linked to source and target", async () => {
+ const source = buildNote({ title: "RelSource" });
+ const target = buildNote({ title: "RelTarget" });
+ const attrId = "brand-new-relation";
+ const row = {
+ attributeId: attrId,
+ noteId: source.noteId,
+ type: "relation",
+ name: "rel",
+ value: target.noteId,
+ isInheritable: false,
+ position: 0
+ };
+ await process([ec({ entityName: "attributes", entityId: attrId, entity: row as any })]);
+ expect(source.attributes.includes(attrId)).toBe(true);
+ expect(target.targetRelations.includes(attrId)).toBe(true);
+
+ // Re-processing must not duplicate in targetRelations either (attribute now exists => update path).
+ const attr = froca.attributes[attrId];
+ // force the "new" branch again by deleting then re-adding while keeping links
+ delete froca.attributes[attrId];
+ await process([ec({ entityName: "attributes", entityId: attrId, entity: row as any })]);
+ expect(target.targetRelations.filter((a) => a === attrId).length).toBe(1);
+ expect(attr.name).toBe("rel");
+ });
+
+ it("does nothing when neither source nor target note is loaded", async () => {
+ const attrId = "orphan-attr";
+ const row = {
+ attributeId: attrId,
+ noteId: "absent-source",
+ type: "label",
+ name: "x",
+ value: "y",
+ isInheritable: false,
+ position: 0
+ };
+ await process([ec({ entityName: "attributes", entityId: attrId, entity: row as any })]);
+ expect(attrId in froca.attributes).toBe(false);
+ });
+
+ it("reloads target note for a new inherit/template relation pointing to an unloaded note", async () => {
+ const source = buildNote({ title: "TplSource" });
+ const attrId = "tpl-attr";
+ const row = {
+ attributeId: attrId,
+ noteId: source.noteId,
+ type: "relation",
+ name: "template",
+ value: "unloaded-template-target",
+ isInheritable: false,
+ position: 0
+ };
+ await process([ec({ entityName: "attributes", entityId: attrId, entity: row as any })]);
+ expect(reloadNotesSpy).toHaveBeenCalledWith(["unloaded-template-target"]);
+ });
+
+ it("skips erased entities in the missing-note ancestor scan", async () => {
+ // attribute relation 'inherit' but with no entity (erased) must not push to missingNoteIds
+ const note = buildNote({ title: "ErasedAttrHost", "~inherit": "target-loaded" });
+ const attrId = note.attributes[0];
+ await process([ec({ entityName: "attributes", entityId: attrId, isErased: true, entity: undefined })]);
+ // erased + not in froca attributes? It IS in froca via buildNote, so reload triggered.
+ // But entity is undefined => ancestor scan 'continue' branch is exercised.
+ expect(reloadNotesSpy).not.toHaveBeenCalled();
+ });
+});
+
+describe("froca_updater - attachment changes", () => {
+ it("triggers a full reload when an in-froca attachment is erased", async () => {
+ const note = buildNote({ title: "AttHost" });
+ const att = new FAttachment(froca, {
+ attachmentId: "att-erase",
+ ownerId: note.noteId,
+ role: "file",
+ mime: "text/plain",
+ title: "a",
+ dateModified: "",
+ utcDateModified: "",
+ utcDateScheduledForErasureSince: "",
+ contentLength: 0
+ });
+ froca.attachments[att.attachmentId] = att;
+
+ await process([ec({ entityName: "attachments", entityId: att.attachmentId, isErased: true })]);
+ expect(reloadSpy).toHaveBeenCalledTimes(1);
+ });
+
+ it("removes a deleted attachment from its owner note", async () => {
+ const note = buildNote({ title: "AttOwner" });
+ const att = new FAttachment(froca, {
+ attachmentId: "att-del",
+ ownerId: note.noteId,
+ role: "file",
+ mime: "text/plain",
+ title: "a",
+ dateModified: "",
+ utcDateModified: "",
+ utcDateScheduledForErasureSince: "",
+ contentLength: 0
+ });
+ froca.attachments[att.attachmentId] = att;
+ note.attachments = [att];
+
+ await process([ec({
+ entityName: "attachments",
+ entityId: att.attachmentId,
+ entity: { attachmentId: att.attachmentId, isDeleted: true } as any
+ })]);
+
+ expect("att-del" in froca.attachments).toBe(false);
+ expect(note.attachments?.some((a) => a.attachmentId === "att-del")).toBe(false);
+ expect(triggerSpy).toHaveBeenCalledTimes(1);
+ });
+
+ it("returns early for a deleted attachment that is not loaded", async () => {
+ await process([ec({
+ entityName: "attachments",
+ entityId: "unknown-att",
+ entity: { attachmentId: "unknown-att", isDeleted: true } as any
+ })]);
+ expect(triggerSpy).not.toHaveBeenCalled();
+ });
+
+ it("updates an existing attachment", async () => {
+ const note = buildNote({ title: "AttUpd" });
+ const att = new FAttachment(froca, {
+ attachmentId: "att-upd",
+ ownerId: note.noteId,
+ role: "file",
+ mime: "text/plain",
+ title: "old",
+ dateModified: "",
+ utcDateModified: "",
+ utcDateScheduledForErasureSince: "",
+ contentLength: 0
+ });
+ froca.attachments[att.attachmentId] = att;
+
+ await process([ec({
+ entityName: "attachments",
+ entityId: "att-upd",
+ entity: {
+ attachmentId: "att-upd",
+ ownerId: note.noteId,
+ role: "file",
+ mime: "text/plain",
+ title: "new",
+ dateModified: "",
+ utcDateModified: "",
+ utcDateScheduledForErasureSince: "",
+ contentLength: 5
+ } as any
+ })]);
+ expect(froca.attachments["att-upd"].title).toBe("new");
+ });
+
+ it("creates a new attachment on its owner note when not previously loaded", async () => {
+ const note = buildNote({ title: "AttCreate" });
+ note.attachments = [];
+ await process([ec({
+ entityName: "attachments",
+ entityId: "att-create",
+ entity: {
+ attachmentId: "att-create",
+ ownerId: note.noteId,
+ role: "file",
+ mime: "text/plain",
+ title: "created",
+ dateModified: "",
+ utcDateModified: "",
+ utcDateScheduledForErasureSince: "",
+ contentLength: 1
+ } as any
+ })]);
+ expect(note.attachments?.some((a) => a.attachmentId === "att-create")).toBe(true);
+ });
+
+ it("handles a new attachment whose owner note is absent (no crash, still records row)", async () => {
+ await process([ec({
+ entityName: "attachments",
+ entityId: "att-noowner",
+ entity: {
+ attachmentId: "att-noowner",
+ ownerId: "absent-owner",
+ role: "file",
+ mime: "text/plain",
+ title: "x",
+ dateModified: "",
+ utcDateModified: "",
+ utcDateScheduledForErasureSince: "",
+ contentLength: 0
+ } as any
+ })]);
+ expect(triggerSpy).toHaveBeenCalledTimes(1);
+ });
+});
+
+describe("froca_updater - branch coverage edge cases", () => {
+ it("updates a note without registering content when blobId is unchanged", async () => {
+ const note = buildNote({ title: "SameBlob" });
+ note.blobId = "stable-blob";
+ const row = {
+ noteId: note.noteId,
+ title: "SameBlobRenamed",
+ isProtected: false,
+ type: "text",
+ mime: "text/html",
+ blobId: "stable-blob"
+ };
+ await process([ec({ entityName: "notes", entityId: note.noteId, componentId: "comp-same", entity: row as any })]);
+ expect(note.title).toBe("SameBlobRenamed");
+ expect(note.blobId).toBe("stable-blob");
+ });
+
+ it("deletes a branch with no loaded child/parent notes and no componentId", async () => {
+ const branchId = "lonely-branch";
+ froca.branches[branchId] = new FBranch(froca, {
+ branchId,
+ noteId: "no-such-child",
+ parentNoteId: "no-such-parent",
+ notePosition: 0,
+ fromSearchNote: false
+ });
+ await process([ec({
+ entityName: "branches",
+ entityId: branchId,
+ entity: { isDeleted: true } as any
+ })]);
+ expect(branchId in froca.branches).toBe(false);
+ });
+
+ it("deletes a relation attribute whose source/target notes are unloaded and has no componentId", async () => {
+ const attrId = "lonely-attr";
+ froca.attributes[attrId] = new FAttribute(froca, {
+ attributeId: attrId,
+ noteId: "no-such-source",
+ type: "relation",
+ name: "rel",
+ value: "no-such-target",
+ isInheritable: false,
+ position: 0
+ });
+ await process([ec({
+ entityName: "attributes",
+ entityId: attrId,
+ entity: { isDeleted: true } as any
+ })]);
+ expect(attrId in froca.attributes).toBe(false);
+ });
+
+ it("deletes a label attribute (no target relation) keeping source unlink optional", async () => {
+ const attrId = "lonely-label";
+ froca.attributes[attrId] = new FAttribute(froca, {
+ attributeId: attrId,
+ noteId: "no-such-source-2",
+ type: "label",
+ name: "lbl",
+ value: "v",
+ isInheritable: false,
+ position: 0
+ });
+ await process([ec({
+ entityName: "attributes",
+ entityId: attrId,
+ componentId: "c",
+ entity: { isDeleted: true } as any
+ })]);
+ expect(attrId in froca.attributes).toBe(false);
+ });
+
+ it("deletes an attachment whose owner note has no attachments array", async () => {
+ const note = buildNote({ title: "NoAttArray" });
+ note.attachments = null;
+ const att = new FAttachment(froca, {
+ attachmentId: "att-noarray",
+ ownerId: note.noteId,
+ role: "file",
+ mime: "text/plain",
+ title: "a",
+ dateModified: "",
+ utcDateModified: "",
+ utcDateScheduledForErasureSince: "",
+ contentLength: 0
+ });
+ froca.attachments[att.attachmentId] = att;
+ await process([ec({
+ entityName: "attachments",
+ entityId: "att-noarray",
+ entity: { attachmentId: "att-noarray", isDeleted: true } as any
+ })]);
+ expect("att-noarray" in froca.attachments).toBe(false);
+ });
+
+ it("records an attachment row even when there is no entity payload", async () => {
+ // not erased, not deleted, attachment not loaded, and ec.entity is undefined
+ await process([ec({ entityName: "attachments", entityId: "att-noentity" })]);
+ expect(triggerSpy).toHaveBeenCalledTimes(1);
+ });
+});
+
+describe("froca_updater - missing-note ancestor reload", () => {
+ it("reloads the parent note when a branch references an unloaded parent", async () => {
+ const child = buildNote({ title: "MissChild" });
+ const branchId = `miss_${child.noteId}`;
+ vi.spyOn(froca, "getNote").mockResolvedValue(null);
+ await process([ec({
+ entityName: "branches",
+ entityId: branchId,
+ entity: {
+ branchId,
+ noteId: child.noteId,
+ parentNoteId: "totally-absent-parent",
+ notePosition: 0,
+ fromSearchNote: false
+ } as any
+ })]);
+ expect(reloadNotesSpy).toHaveBeenCalledWith(["totally-absent-parent"]);
+ });
+});
diff --git a/apps/client/src/services/frontend_script_api.spec.ts b/apps/client/src/services/frontend_script_api.spec.ts
new file mode 100644
index 0000000000..485a9c4629
--- /dev/null
+++ b/apps/client/src/services/frontend_script_api.spec.ts
@@ -0,0 +1,493 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+import appContext from "../components/app_context.js";
+import type FNote from "../entities/fnote.js";
+import { buildNote } from "../test/easy-froca.js";
+import dateNotesService from "./date_notes.js";
+import dialogService from "./dialog.js";
+import FrontendScriptApi, { type Api, type Entity } from "./frontend_script_api.js";
+import { preactAPI } from "./frontend_script_api_preact.js";
+import froca from "./froca.js";
+import linkService from "./link.js";
+import noteTooltipService from "./note_tooltip.js";
+import protectedSessionService from "./protected_session.js";
+import searchService from "./search.js";
+import server from "./server.js";
+import shortcutService from "./shortcuts.js";
+import toastService from "./toast.js";
+import utils from "./utils.js";
+import ws from "./ws.js";
+
+// The global ws mock from setup.ts does not define waitForMaxKnownEntityChangeId.
+ws.waitForMaxKnownEntityChangeId = vi.fn(async () => {}) as typeof ws.waitForMaxKnownEntityChangeId;
+
+function makeApi(opts: { startNote?: FNote; currentNote?: FNote; originEntity?: Entity | null; $container?: JQuery<HTMLElement> | null } = {}): Api {
+ const startNote = opts.startNote ?? buildNote({ title: "Start" });
+ const currentNote = opts.currentNote ?? buildNote({ title: "Current" });
+ return new FrontendScriptApi(startNote, currentNote, opts.originEntity ?? null, opts.$container ?? null);
+}
+
+/** A tabManager stub; assigned onto the singleton appContext per-test. */
+function setTabManager(stub: Record<string, unknown>) {
+ (appContext as unknown as { tabManager: unknown }).tabManager = stub;
+}
+
+afterEach(() => {
+ vi.restoreAllMocks();
+});
+
+describe("FrontendScriptApi constructor", () => {
+ it("wires up notes, the dayjs lib, widget classes and the preact API", () => {
+ const startNote = buildNote({ title: "Start" });
+ const currentNote = buildNote({ title: "Current" });
+ const originEntity = { noteId: "origin1" };
+ const $container = {} as JQuery<HTMLElement>;
+
+ const api = new FrontendScriptApi(startNote, currentNote, originEntity, $container);
+
+ expect(api.startNote).toBe(startNote);
+ expect(api.currentNote).toBe(currentNote);
+ expect(api.originEntity).toBe(originEntity);
+ expect(api.$container).toBe($container);
+ expect(api.dayjs).toBeTypeOf("function");
+ expect(api.preact).toBe(preactAPI);
+ // Passthrough references should point at the underlying service functions.
+ expect(api.formatDateISO).toBe(utils.formatDateISO);
+ expect(api.parseDate).toBe(utils.parseDate);
+ expect(api.randomString).toBe(utils.randomString);
+ expect(api.formatSize).toBe(utils.formatSize);
+ expect(api.formatNoteSize).toBe(utils.formatSize);
+ expect(api.createLink).toBe(linkService.createLink);
+ expect(api.createNoteLink).toBe(linkService.createLink);
+ expect(api.setupElementTooltip).toBe(noteTooltipService.setupElementTooltip);
+ expect(api.bindGlobalShortcut).toBe(shortcutService.bindGlobalShortcut);
+ expect(api.waitUntilSynced).toBe(ws.waitForMaxKnownEntityChangeId);
+ expect(api.getTodayNote).toBe(dateNotesService.getTodayNote);
+ expect(api.getDayNote).toBe(dateNotesService.getDayNote);
+ expect(api.getWeekFirstDayNote).toBe(dateNotesService.getWeekFirstDayNote);
+ expect(api.getWeekNote).toBe(dateNotesService.getWeekNote);
+ expect(api.getMonthNote).toBe(dateNotesService.getMonthNote);
+ expect(api.getQuarterNote).toBe(dateNotesService.getQuarterNote);
+ expect(api.getYearNote).toBe(dateNotesService.getYearNote);
+ expect(api.showMessage).toBe(toastService.showMessage);
+ expect(api.showError).toBe(toastService.showError);
+ expect(api.showInfoDialog).toBe(dialogService.info);
+ expect(api.showConfirmDialog).toBe(dialogService.confirm);
+ expect(api.showPromptDialog).toBe(dialogService.prompt);
+ });
+
+ it("defaults originEntity and $container to null", () => {
+ const api = new FrontendScriptApi(buildNote({ title: "S" }), buildNote({ title: "C" }), undefined as unknown as null, undefined as unknown as null);
+ expect(api.originEntity).toBeNull();
+ expect(api.$container).toBeNull();
+ });
+});
+
+describe("note activation / tabs / splits", () => {
+ it("activateNote sets the note on the active context", async () => {
+ const setNote = vi.fn(async () => {});
+ setTabManager({ getActiveContext: () => ({ setNote }) });
+ await makeApi().activateNote("root");
+ expect(setNote).toHaveBeenCalledWith("root");
+ });
+
+ it("activateNote is a no-op when there is no active context", async () => {
+ setTabManager({ getActiveContext: () => undefined });
+ await expect(makeApi().activateNote("root")).resolves.toBeUndefined();
+ });
+
+ it("activateNewNote waits for sync, sets note and focuses the title", async () => {
+ const setNote = vi.fn(async () => {});
+ setTabManager({ getActiveContext: () => ({ setNote }) });
+ const triggerEvent = vi.spyOn(appContext, "triggerEvent").mockResolvedValue(undefined as never);
+
+ await makeApi().activateNewNote("root");
+
+ expect(ws.waitForMaxKnownEntityChangeId).toHaveBeenCalled();
+ expect(setNote).toHaveBeenCalledWith("root");
+ expect(triggerEvent).toHaveBeenCalledWith("focusAndSelectTitle", {});
+ });
+
+ it("openTabWithNote opens a hoisted tab and focuses the title when activate=true", async () => {
+ const openTabWithNoteWithHoisting = vi.fn(async () => {});
+ setTabManager({ openTabWithNoteWithHoisting });
+ const triggerEvent = vi.spyOn(appContext, "triggerEvent").mockResolvedValue(undefined as never);
+
+ await makeApi().openTabWithNote("root", true);
+
+ expect(openTabWithNoteWithHoisting).toHaveBeenCalledWith("root", { activate: true });
+ expect(triggerEvent).toHaveBeenCalledWith("focusAndSelectTitle", {});
+ });
+
+ it("openTabWithNote does not focus the title when activate=false", async () => {
+ const openTabWithNoteWithHoisting = vi.fn(async () => {});
+ setTabManager({ openTabWithNoteWithHoisting });
+ const triggerEvent = vi.spyOn(appContext, "triggerEvent").mockResolvedValue(undefined as never);
+
+ await makeApi().openTabWithNote("root", false);
+
+ expect(openTabWithNoteWithHoisting).toHaveBeenCalledWith("root", { activate: false });
+ expect(triggerEvent).not.toHaveBeenCalled();
+ });
+
+ it("openSplitWithNote derives the ntxId from the last sub context and focuses on activate", async () => {
+ const subContexts = [{ ntxId: "a" }, { ntxId: "last" }];
+ setTabManager({ getActiveContext: () => ({ getSubContexts: () => subContexts }) });
+ const triggerCommand = vi.spyOn(appContext, "triggerCommand").mockResolvedValue(undefined as never);
+ const triggerEvent = vi.spyOn(appContext, "triggerEvent").mockResolvedValue(undefined as never);
+
+ await makeApi().openSplitWithNote("root", true);
+
+ expect(triggerCommand).toHaveBeenCalledWith("openNewNoteSplit", { ntxId: "last", notePath: "root" });
+ expect(triggerEvent).toHaveBeenCalledWith("focusAndSelectTitle", {});
+ });
+
+ it("openSplitWithNote falls back to an empty ntxId when there is no active context and does not focus on activate=false", async () => {
+ setTabManager({ getActiveContext: () => undefined });
+ const triggerCommand = vi.spyOn(appContext, "triggerCommand").mockResolvedValue(undefined as never);
+ const triggerEvent = vi.spyOn(appContext, "triggerEvent").mockResolvedValue(undefined as never);
+
+ await makeApi().openSplitWithNote("root", false);
+
+ expect(triggerCommand).toHaveBeenCalledWith("openNewNoteSplit", { ntxId: undefined, notePath: "root" });
+ expect(triggerEvent).not.toHaveBeenCalled();
+ });
+});
+
+describe("addButtonToToolbar", () => {
+ it("warns about deprecation and PUTs the launcher with a stringified action", async () => {
+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
+ // The global server mock only defines get/post, so assign put directly.
+ const put = (server.put = vi.fn(async () => undefined) as typeof server.put);
+ const action = () => {};
+
+ await makeApi().addButtonToToolbar({ title: "T", action, id: "btn1", icon: "time", shortcut: "alt+t" });
+
+ expect(warn).toHaveBeenCalled();
+ expect(put).toHaveBeenCalledWith("special-notes/api-script-launcher", {
+ action: action.toString(),
+ title: "T",
+ id: "btn1",
+ icon: "time",
+ shortcut: "alt+t"
+ });
+ });
+});
+
+describe("runOnBackend / __runOnBackendInner", () => {
+ beforeEach(() => vi.clearAllMocks());
+
+ it("serializes a sync function, posts it, waits for sync and returns the result", async () => {
+ const post = vi.spyOn(server, "post").mockResolvedValue({ success: true, executionResult: 42 } as never);
+ const start = buildNote({ title: "S" });
+ const current = buildNote({ title: "C" });
+ const origin = { noteId: "originX" };
+ const api = makeApi({ startNote: start, currentNote: current, originEntity: origin });
+
+ function myFunc() {}
+ const result = await api.runOnBackend(myFunc, ["plain", () => {}]);
+
+ expect(result).toBe(42);
+ expect(ws.waitForMaxKnownEntityChangeId).toHaveBeenCalled();
+ const body = (post.mock.calls[0][1]) as Record<string, unknown>;
+ expect(post.mock.calls[0][0]).toBe("script/exec");
+ expect(body.script).toBe(myFunc.toString());
+ expect(body.transactional).toBe(true);
+ expect(body.startNoteId).toBe(start.noteId);
+ expect(body.currentNoteId).toBe(current.noteId);
+ expect(body.originEntityName).toBe("notes");
+ expect(body.originEntityId).toBe("originX");
+ // prepareParams serializes nested functions and leaves primitives untouched.
+ const params = body.params as unknown[];
+ expect(params[0]).toBe("plain");
+ expect(params[1]).toMatch(/^!@#Function: /);
+ });
+
+ it("passes originEntityId as null when there is no origin entity", async () => {
+ const post = vi.spyOn(server, "post").mockResolvedValue({ success: true, executionResult: null } as never);
+ await makeApi({ originEntity: null }).runOnBackend("function f(){}", []);
+ const body = post.mock.calls[0][1] as Record<string, unknown>;
+ expect(body.originEntityId).toBeNull();
+ });
+
+ it("warns and still runs when passed an async function reference", async () => {
+ vi.spyOn(server, "post").mockResolvedValue({ success: true, executionResult: 1 } as never);
+ const showError = vi.spyOn(toastService, "showError").mockImplementation(() => undefined as never);
+ const asyncFn = async () => {};
+ await makeApi().runOnBackend(asyncFn, []);
+ expect(showError).toHaveBeenCalled();
+ });
+
+ it("warns when passed an async function as a string", async () => {
+ vi.spyOn(server, "post").mockResolvedValue({ success: true, executionResult: 1 } as never);
+ const showError = vi.spyOn(toastService, "showError").mockImplementation(() => undefined as never);
+ await makeApi().runOnBackend("async function f(){}", []);
+ expect(showError).toHaveBeenCalled();
+ });
+
+ it("does not warn for a plain sync function and defaults params to an empty array", async () => {
+ const post = vi.spyOn(server, "post").mockResolvedValue({ success: true, executionResult: 1 } as never);
+ const showError = vi.spyOn(toastService, "showError").mockImplementation(() => undefined as never);
+ // Call with no params arg to exercise the `params = []` default.
+ await (makeApi().runOnBackend as (func: () => void) => Promise<unknown>)(() => {});
+ expect(showError).not.toHaveBeenCalled();
+ expect((post.mock.calls[0][1] as Record<string, unknown>).params).toEqual([]);
+ });
+
+ it("throws a server error when the execution reports failure", async () => {
+ vi.spyOn(server, "post").mockResolvedValue({ success: false, error: "boom" } as never);
+ await expect(makeApi().runOnBackend("function f(){}", [])).rejects.toThrow("server error: boom");
+ });
+});
+
+describe("runAsyncOnBackendWithManualTransactionHandling", () => {
+ beforeEach(() => vi.clearAllMocks());
+
+ it("warns when passed a sync function reference, then runs non-transactionally", async () => {
+ const post = vi.spyOn(server, "post").mockResolvedValue({ success: true, executionResult: 7 } as never);
+ const showError = vi.spyOn(toastService, "showError").mockImplementation(() => undefined as never);
+
+ function syncFn() {}
+ const result = await makeApi().runAsyncOnBackendWithManualTransactionHandling(syncFn, []);
+
+ expect(result).toBe(7);
+ expect(showError).toHaveBeenCalled();
+ expect((post.mock.calls[0][1] as Record<string, unknown>).transactional).toBe(false);
+ });
+
+ it("warns when passed a sync function as a string", async () => {
+ vi.spyOn(server, "post").mockResolvedValue({ success: true, executionResult: 1 } as never);
+ const showError = vi.spyOn(toastService, "showError").mockImplementation(() => undefined as never);
+ await makeApi().runAsyncOnBackendWithManualTransactionHandling("function f(){}", []);
+ expect(showError).toHaveBeenCalled();
+ });
+
+ it("does not warn for an async function and defaults params to an empty array", async () => {
+ const post = vi.spyOn(server, "post").mockResolvedValue({ success: true, executionResult: 1 } as never);
+ const showError = vi.spyOn(toastService, "showError").mockImplementation(() => undefined as never);
+ // Call with no params arg to exercise the `params = []` default.
+ await (makeApi().runAsyncOnBackendWithManualTransactionHandling as (func: () => Promise<void>) => Promise<unknown>)(async () => {});
+ expect(showError).not.toHaveBeenCalled();
+ expect((post.mock.calls[0][1] as Record<string, unknown>).params).toEqual([]);
+ });
+
+ it("prepareParams returns the params unchanged when falsy", async () => {
+ const post = vi.spyOn(server, "post").mockResolvedValue({ success: true, executionResult: 1 } as never);
+ // Passing null params exercises the `if (!params) return params;` early-return branch.
+ await makeApi().runAsyncOnBackendWithManualTransactionHandling("async () => {}", null as unknown as unknown[]);
+ expect((post.mock.calls[0][1] as Record<string, unknown>).params).toBeNull();
+ });
+});
+
+describe("search", () => {
+ it("searchForNotes delegates to the search service", async () => {
+ const note = buildNote({ title: "Hit" });
+ vi.spyOn(searchService, "searchForNotes").mockResolvedValue([note]);
+ expect(await makeApi().searchForNotes("#x")).toEqual([note]);
+ });
+
+ it("searchForNote returns the first match", async () => {
+ const note = buildNote({ title: "Hit" });
+ vi.spyOn(searchService, "searchForNotes").mockResolvedValue([note]);
+ expect(await makeApi().searchForNote("#x")).toBe(note);
+ });
+
+ it("searchForNote returns null when there are no matches", async () => {
+ vi.spyOn(searchService, "searchForNotes").mockResolvedValue([]);
+ expect(await makeApi().searchForNote("#x")).toBeNull();
+ });
+});
+
+describe("froca passthroughs", () => {
+ it("getNote / getNotes / reloadNotes delegate to froca", async () => {
+ const note = buildNote({ title: "N" });
+ const getNote = vi.spyOn(froca, "getNote").mockResolvedValue(note);
+ const getNotes = vi.spyOn(froca, "getNotes").mockResolvedValue([note]);
+ const reloadNotes = vi.spyOn(froca, "reloadNotes").mockResolvedValue(undefined);
+ const api = makeApi();
+
+ expect(await api.getNote(note.noteId)).toBe(note);
+ // default silentNotFoundError -> false
+ expect(await api.getNotes([note.noteId], undefined as unknown as boolean)).toEqual([note]);
+ expect(getNotes).toHaveBeenCalledWith([note.noteId], false);
+ // explicit silentNotFoundError -> true
+ await api.getNotes([note.noteId], true);
+ expect(getNotes).toHaveBeenLastCalledWith([note.noteId], true);
+ await api.reloadNotes([note.noteId]);
+ expect(getNote).toHaveBeenCalled();
+ expect(reloadNotes).toHaveBeenCalledWith([note.noteId]);
+ });
+
+ it("getInstanceName reads from window.glob", () => {
+ window.glob.instanceName = "inst-A";
+ expect(makeApi().getInstanceName()).toBe("inst-A");
+ });
+});
+
+describe("commands and events", () => {
+ it("triggerCommand / triggerEvent / addTextToActiveContextEditor / refreshIncludedNote dispatch via appContext", () => {
+ const triggerCommand = vi.spyOn(appContext, "triggerCommand").mockReturnValue(undefined as never);
+ const triggerEvent = vi.spyOn(appContext, "triggerEvent").mockReturnValue(undefined as never);
+ const api = makeApi();
+
+ api.triggerCommand("jumpToNote" as never, { foo: 1 } as never);
+ expect(triggerCommand).toHaveBeenCalledWith("jumpToNote", { foo: 1 });
+
+ api.triggerEvent("noteSwitched" as never, { bar: 2 } as never);
+ expect(triggerEvent).toHaveBeenCalledWith("noteSwitched", { bar: 2 });
+
+ api.addTextToActiveContextEditor("hello");
+ expect(triggerCommand).toHaveBeenCalledWith("addTextToActiveEditor", { text: "hello" });
+
+ api.refreshIncludedNote("incl1");
+ expect(triggerEvent).toHaveBeenCalledWith("refreshIncludedNote", { noteId: "incl1" });
+ });
+
+ it("getActiveNoteDetailWidget resolves through the executeInActiveNoteDetailWidget command callback", async () => {
+ const widget = { kind: "detail" };
+ vi.spyOn(appContext, "triggerCommand").mockImplementation(((_name: string, data: { callback: (w: unknown) => void }) => {
+ data.callback(widget);
+ return undefined;
+ }) as never);
+ expect(await makeApi().getActiveNoteDetailWidget()).toBe(widget);
+ });
+
+ it("getComponentByEl delegates to appContext.getComponentByEl", () => {
+ const component = { id: "c" };
+ const el = document.createElement("div");
+ vi.spyOn(appContext, "getComponentByEl").mockReturnValue(component as never);
+ expect(makeApi().getComponentByEl(el)).toBe(component);
+ });
+});
+
+describe("active context accessors", () => {
+ it("getActiveContextNote returns the note or throws when absent", () => {
+ const note = buildNote({ title: "Active" });
+ setTabManager({ getActiveContextNote: () => note });
+ expect(makeApi().getActiveContextNote()).toBe(note);
+
+ setTabManager({ getActiveContextNote: () => null });
+ expect(() => makeApi().getActiveContextNote()).toThrow("No active context note found");
+ });
+
+ it("getActiveContext returns the context or throws when absent", () => {
+ const ctx = { id: "ctx" };
+ setTabManager({ getActiveContext: () => ctx });
+ expect(makeApi().getActiveContext()).toBe(ctx);
+
+ setTabManager({ getActiveContext: () => null });
+ expect(() => makeApi().getActiveContext()).toThrow("No active context found");
+ });
+
+ it("getActiveMainContext returns the main context or throws when absent", () => {
+ const ctx = { id: "main" };
+ setTabManager({ getActiveMainContext: () => ctx });
+ expect(makeApi().getActiveMainContext()).toBe(ctx);
+
+ setTabManager({ getActiveMainContext: () => null });
+ expect(() => makeApi().getActiveMainContext()).toThrow("No active main context found");
+ });
+
+ it("getNoteContexts / getMainNoteContexts / getActiveContextNotePath delegate to the tab manager", () => {
+ const noteContexts = [{ a: 1 }];
+ const mainContexts = [{ b: 2 }];
+ setTabManager({
+ getNoteContexts: () => noteContexts,
+ getMainNoteContexts: () => mainContexts,
+ getActiveContextNotePath: () => "root/abc"
+ });
+ const api = makeApi();
+ expect(api.getNoteContexts()).toBe(noteContexts);
+ expect(api.getMainNoteContexts()).toBe(mainContexts);
+ expect(api.getActiveContextNotePath()).toBe("root/abc");
+ });
+
+ it("getActiveContextTextEditor returns the editor or throws when absent", async () => {
+ const editor = { type: "ck" };
+ setTabManager({ getActiveContext: () => ({ getTextEditor: () => Promise.resolve(editor) }) });
+ expect(await makeApi().getActiveContextTextEditor()).toBe(editor);
+
+ // The "no context" guard throws synchronously, before any Promise is returned.
+ setTabManager({ getActiveContext: () => null });
+ expect(() => makeApi().getActiveContextTextEditor()).toThrow("No active context found");
+ });
+
+ it("getActiveContextCodeEditor returns the editor or throws when absent", async () => {
+ const editor = { type: "cm" };
+ setTabManager({ getActiveContext: () => ({ getCodeEditor: () => Promise.resolve(editor) }) });
+ expect(await makeApi().getActiveContextCodeEditor()).toBe(editor);
+
+ setTabManager({ getActiveContext: () => null });
+ expect(() => makeApi().getActiveContextCodeEditor()).toThrow("No active context found");
+ });
+});
+
+describe("protection and hoisting", () => {
+ it("protectNote protects a single note (non-recursively)", async () => {
+ const protectNote = vi.spyOn(protectedSessionService, "protectNote").mockResolvedValue(undefined as never);
+ // The public type over-declares a 3rd arg (typeof protectedSessionService.protectNote); the impl ignores it.
+ await makeApi().protectNote("note1", true, false);
+ expect(protectNote).toHaveBeenCalledWith("note1", true, false);
+ });
+
+ it("protectSubTree protects recursively", async () => {
+ const protectNote = vi.spyOn(protectedSessionService, "protectNote").mockResolvedValue(undefined as never);
+ // The public type over-declares a 3rd arg (typeof protectedSessionService.protectNote); the impl ignores it.
+ await makeApi().protectSubTree("note1", false, true);
+ expect(protectNote).toHaveBeenCalledWith("note1", false, true);
+ });
+
+ it("setHoistedNoteId forwards to the active context when present", () => {
+ const setHoistedNoteId = vi.fn();
+ setTabManager({ getActiveContext: () => ({ setHoistedNoteId }) });
+ makeApi().setHoistedNoteId("note9");
+ expect(setHoistedNoteId).toHaveBeenCalledWith("note9");
+ });
+
+ it("setHoistedNoteId is a no-op when there is no active context", () => {
+ setTabManager({ getActiveContext: () => null });
+ expect(() => makeApi().setHoistedNoteId("note9")).not.toThrow();
+ });
+});
+
+describe("log", () => {
+ beforeEach(() => vi.clearAllMocks());
+
+ it("logs to the console, accumulates messages and schedules a spaced update per note", () => {
+ const startNote = buildNote({ title: "Logger" });
+ const consoleLog = vi.spyOn(console, "log").mockImplementation(() => {});
+ const api = makeApi({ startNote });
+
+ api.log("first", "message");
+ api.log("second");
+
+ const noteId = startNote.noteId;
+ expect(consoleLog).toHaveBeenCalled();
+ // Both messages should be accumulated under the start note's id.
+ expect(api.logMessages[noteId]).toHaveLength(2);
+ expect(api.logMessages[noteId][0]).toContain("first message");
+ // The spaced update instance should be created once and reused across calls.
+ expect(api.logSpacedUpdates[noteId]).toBeDefined();
+ });
+
+ it("flushes accumulated messages via apiLogMessages when the spaced update fires", async () => {
+ vi.useFakeTimers();
+ try {
+ const startNote = buildNote({ title: "Logger2" });
+ vi.spyOn(console, "log").mockImplementation(() => {});
+ const triggerEvent = vi.spyOn(appContext, "triggerEvent").mockReturnValue(undefined as never);
+ const api = makeApi({ startNote });
+ const noteId = startNote.noteId;
+
+ api.log("flushme");
+ // SpacedUpdate.scheduleUpdate schedules a triggerUpdate via setTimeout.
+ await vi.advanceTimersByTimeAsync(2000);
+
+ expect(triggerEvent).toHaveBeenCalledWith("apiLogMessages", { noteId, messages: [expect.stringContaining("flushme")] });
+ // After flushing, the per-note message buffer is reset to empty.
+ expect(api.logMessages[noteId]).toEqual([]);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+});
diff --git a/apps/client/src/services/frontend_script_api_preact.spec.ts b/apps/client/src/services/frontend_script_api_preact.spec.ts
new file mode 100644
index 0000000000..6ffed4f2ee
--- /dev/null
+++ b/apps/client/src/services/frontend_script_api_preact.spec.ts
@@ -0,0 +1,47 @@
+import { Fragment, h } from "preact";
+import { describe, expect, it } from "vitest";
+
+import { preactAPI } from "./frontend_script_api_preact.js";
+
+describe("preactAPI", () => {
+ it("re-exports the core preact primitives and is frozen", () => {
+ expect(preactAPI.h).toBe(h);
+ expect(preactAPI.Fragment).toBe(Fragment);
+ expect(typeof preactAPI.createContext).toBe("function");
+ expect(Object.isFrozen(preactAPI)).toBe(true);
+ });
+
+ it("exposes the bundled widgets and the spread hooks", () => {
+ // A representative widget from each block must be present and a function/component.
+ for (const key of ["ActionButton", "Modal", "FormTextBox", "RightPanelWidget"]) {
+ expect(preactAPI[key as keyof typeof preactAPI]).toBeDefined();
+ }
+ // Spread preact hooks land directly on the object.
+ expect(typeof (preactAPI as Record<string, unknown>).useState).toBe("function");
+ expect(typeof (preactAPI as Record<string, unknown>).useEffect).toBe("function");
+ });
+
+ it("defineWidget tags the definition with the preact-widget type and preserves fields", () => {
+ const render = () => h(Fragment, null);
+ const result = preactAPI.defineWidget({ parent: "right-pane", render, position: 42 });
+
+ expect(result).toEqual({
+ type: "preact-widget",
+ parent: "right-pane",
+ render,
+ position: 42
+ });
+ expect(result.render).toBe(render);
+ });
+
+ it("defineLauncherWidget tags the definition with the preact-launcher-widget type", () => {
+ const render = () => h(Fragment, null);
+ const result = preactAPI.defineLauncherWidget({ render });
+
+ expect(result).toEqual({
+ type: "preact-launcher-widget",
+ render
+ });
+ expect(result.render).toBe(render);
+ });
+});
diff --git a/apps/client/src/services/glob.spec.ts b/apps/client/src/services/glob.spec.ts
new file mode 100644
index 0000000000..c8efcb32c7
--- /dev/null
+++ b/apps/client/src/services/glob.spec.ts
@@ -0,0 +1,215 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+vi.mock("../components/app_context.js", () => ({
+ default: {
+ getComponentByEl: vi.fn((el: unknown) => ({ el })),
+ tabManager: { getActiveContextNote: vi.fn(() => null) }
+ }
+}));
+
+vi.mock("./link.js", () => ({
+ default: {
+ getReferenceLinkTitle: vi.fn(async (href: string) => `async:${href}`),
+ getReferenceLinkTitleSync: vi.fn((href: string) => `sync:${href}`)
+ }
+}));
+
+import appContext from "../components/app_context.js";
+import froca from "./froca.js";
+import glob from "./glob.js";
+import { requireCss } from "./glob.js";
+import linkService from "./link.js";
+import server from "./server.js";
+import ws from "./ws.js";
+
+const getComponentByEl = appContext.getComponentByEl as ReturnType<typeof vi.fn>;
+const getActiveContextNote = appContext.tabManager.getActiveContextNote as ReturnType<typeof vi.fn>;
+const getReferenceLinkTitle = linkService.getReferenceLinkTitle as ReturnType<typeof vi.fn>;
+const getReferenceLinkTitleSync = linkService.getReferenceLinkTitleSync as ReturnType<typeof vi.fn>;
+
+// ws.logError isn't part of the global stub; provide a spy so the error handlers can call it.
+(ws as any).logError = vi.fn();
+
+function resetDom() {
+ document.head.innerHTML = "";
+ document.body.innerHTML = "";
+}
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ (ws as any).logError = vi.fn();
+ resetDom();
+ // Reset the glob object to a known baseline for each test.
+ (window as any).glob = {
+ isMainWindow: true,
+ assetPath: "/assets",
+ appCssNoteIds: []
+ };
+});
+
+afterEach(() => {
+ window.onerror = null;
+});
+
+describe("setupGlobs", () => {
+ it("wires up the glob object with values and delegating helpers", () => {
+ glob.setupGlobs();
+
+ // direct value assignments
+ expect(window.glob.isDesktop).toBeTypeOf("function");
+ expect(window.glob.isMobile).toBeTypeOf("function");
+ expect(window.glob.getHeaders).toBe(server.getHeaders);
+ expect(window.glob.froca).toBe(froca);
+ expect(window.glob.treeCache).toBe(froca);
+ expect(window.glob.appContext).toBe(appContext);
+
+ // delegating lambdas actually call through to the underlying services
+ const el = document.createElement("div");
+ expect(window.glob.getComponentByEl(el)).toEqual({ el });
+ expect(getComponentByEl).toHaveBeenCalledWith(el);
+
+ expect(window.glob.getActiveContextNote()).toBeNull();
+ expect(getActiveContextNote).toHaveBeenCalled();
+ });
+
+ it("delegates reference link title helpers to the link service", async () => {
+ glob.setupGlobs();
+
+ await expect(window.glob.getReferenceLinkTitle("#root/abc")).resolves.toBe("async:#root/abc");
+ expect(getReferenceLinkTitle).toHaveBeenCalledWith("#root/abc");
+
+ expect(window.glob.getReferenceLinkTitleSync("#root/def")).toBe("sync:#root/def");
+ expect(getReferenceLinkTitleSync).toHaveBeenCalledWith("#root/def");
+ });
+
+ it("loads each configured app CSS note that isn't already present", () => {
+ // Pre-seed an existing link so the dedup branch (some => true) is exercised.
+ const existing = document.createElement("link");
+ existing.rel = "stylesheet";
+ existing.href = "/anything/api/notes/download/already";
+ document.head.appendChild(existing);
+
+ window.glob.appCssNoteIds = ["already", "fresh"];
+ glob.setupGlobs();
+
+ const hrefs = Array.from(document.querySelectorAll("head link")).map((l) => (l as HTMLLinkElement).getAttribute("href"));
+ // "already" was present -> not re-added; "fresh" gets appended without asset path prefix.
+ expect(hrefs.filter((h) => h?.endsWith("api/notes/download/already"))).toHaveLength(1);
+ expect(hrefs).toContain("api/notes/download/fresh");
+ });
+
+ it("handles a missing appCssNoteIds list", () => {
+ delete (window.glob as any).appCssNoteIds;
+ glob.setupGlobs();
+ // No css links added from the (absent) list.
+ expect(document.querySelectorAll("head link")).toHaveLength(0);
+ });
+
+ it("opens external anchor links in a new window", () => {
+ glob.setupGlobs();
+
+ const openSpy = vi.spyOn(window, "open").mockReturnValue(null);
+ const $a = window.$('<a class="external" href="https://example.com">x</a>');
+ window.$("body").append($a);
+ $a.trigger("click");
+
+ expect(openSpy).toHaveBeenCalledWith("https://example.com", "_blank");
+ openSpy.mockRestore();
+ });
+});
+
+describe("window.onerror handler", () => {
+ beforeEach(() => glob.setupGlobs());
+
+ it("logs full details for a normal error and serializes the error object", () => {
+ const result = window.onerror!("Some failure", "http://x/app.js", 12, 34, new Error("boom"));
+
+ expect(result).toBe(false);
+ expect((ws as any).logError).toHaveBeenCalledTimes(1);
+ const msg = (ws as any).logError.mock.calls[0][0] as string;
+ expect(msg).toContain("Message: Some failure");
+ expect(msg).toContain("URL: http://x/app.js");
+ expect(msg).toContain("Line: 12");
+ expect(msg).toContain("Column: 34");
+ });
+
+ it("reports no details for a generic 'Script error'", () => {
+ window.onerror!("Script error.", undefined, undefined, undefined, undefined);
+ const msg = (ws as any).logError.mock.calls[0][0] as string;
+ expect(msg).toContain("No details available");
+ });
+
+ it("falls back to toString when the error object cannot be JSON-stringified", () => {
+ const circular: any = {};
+ circular.self = circular;
+ const err: any = new Error("circular");
+ err.toJSON = () => {
+ throw new Error("nope");
+ };
+
+ window.onerror!("circular failure", "u", 1, 2, err);
+ const msg = (ws as any).logError.mock.calls[0][0] as string;
+ // The catch branch stringified the thrown serialization error via toString().
+ expect(msg).toContain("Error object: Error: nope");
+ });
+});
+
+describe("unhandledrejection handler", () => {
+ beforeEach(() => glob.setupGlobs());
+
+ function dispatchRejection(reason: unknown) {
+ const event = new Event("unhandledrejection") as any;
+ event.reason = reason;
+ window.dispatchEvent(event);
+ }
+
+ it("logs full details for a normal rejection", () => {
+ dispatchRejection({ message: "rejected", lineNumber: 5, columnNumber: 6, stack: "stack" });
+ const msg = (ws as any).logError.mock.calls[0][0] as string;
+ expect(msg).toContain("Message: rejected");
+ expect(msg).toContain("Line: 5");
+ expect(msg).toContain("Column: 6");
+ });
+
+ it("reports no details for a script error rejection", () => {
+ dispatchRejection({ message: "Script error" });
+ const msg = (ws as any).logError.mock.calls[0][0] as string;
+ expect(msg).toContain("No details available");
+ });
+
+ it("handles a rejection with no reason message and unserializable reason", () => {
+ const circular: any = {};
+ circular.self = circular;
+ circular.toJSON = () => {
+ throw new Error("bad");
+ };
+ // no .message -> string is undefined -> falls into the details branch
+ dispatchRejection(circular);
+ const msg = (ws as any).logError.mock.calls[0][0] as string;
+ expect(msg).toContain("Error object: Error: bad");
+ });
+});
+
+describe("requireCss", () => {
+ beforeEach(() => {
+ (window as any).glob = { assetPath: "/myassets" };
+ resetDom();
+ });
+
+ it("prepends the asset path by default and appends a stylesheet link", async () => {
+ await requireCss("css/theme.css");
+ const link = document.querySelector("head link") as HTMLLinkElement;
+ expect(link.getAttribute("href")).toBe("/myassets/css/theme.css");
+ });
+
+ it("does not append a duplicate when a matching stylesheet already exists", async () => {
+ const existing = document.createElement("link");
+ existing.rel = "stylesheet";
+ existing.href = "http://host/some/path.css";
+ document.head.appendChild(existing);
+
+ await requireCss("some/path.css", true);
+ // Still just the one link; nothing appended because the existing href ends with the url.
+ expect(document.querySelectorAll("head link")).toHaveLength(1);
+ });
+});
diff --git a/apps/client/src/services/glob.ts b/apps/client/src/services/glob.ts
index 84b644f4ff..a4444afc93 100644
--- a/apps/client/src/services/glob.ts
+++ b/apps/client/src/services/glob.ts
@@ -82,7 +82,7 @@ function setupGlobs() {
});
}
-async function requireCss(url: string, prependAssetPath = true) {
+export async function requireCss(url: string, prependAssetPath = true) {
const cssLinks = Array.from(document.querySelectorAll("link")).map((el) => el.href);
if (!cssLinks.some((l) => l.endsWith(url))) {
diff --git a/apps/client/src/services/hoisted_note.spec.ts b/apps/client/src/services/hoisted_note.spec.ts
new file mode 100644
index 0000000000..6e47759ac9
--- /dev/null
+++ b/apps/client/src/services/hoisted_note.spec.ts
@@ -0,0 +1,199 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+// app_context pulls in a very large module graph; mock it to a tiny tab manager surface.
+const activeContextRef: { current: { hoistedNoteId: string; unhoist: () => Promise<void> } | null } = {
+ current: null
+};
+const unhoistSpy = vi.fn(async () => {});
+
+vi.mock("../components/app_context.js", () => ({
+ default: {
+ tabManager: {
+ getActiveContext: () => activeContextRef.current
+ }
+ }
+}));
+
+const resolveNotePath = vi.fn<(notePath: string, hoistedNoteId?: string) => Promise<string | null>>();
+const getNoteIdFromUrl = vi.fn<(notePath: string) => string | null>();
+vi.mock("./tree.js", () => ({
+ default: {
+ resolveNotePath: (notePath: string, hoistedNoteId?: string) => resolveNotePath(notePath, hoistedNoteId),
+ getNoteIdFromUrl: (notePath: string) => getNoteIdFromUrl(notePath)
+ }
+}));
+
+const confirm = vi.fn<(message: string) => Promise<boolean>>();
+vi.mock("./dialog.js", () => ({
+ default: {
+ confirm: (message: string) => confirm(message)
+ }
+}));
+
+import type NoteContext from "../components/note_context.js";
+import { buildNote } from "../test/easy-froca";
+import hoistedNoteService from "./hoisted_note.js";
+
+function setActiveContext(hoistedNoteId: string | null) {
+ if (hoistedNoteId === null) {
+ activeContextRef.current = null;
+ } else {
+ activeContextRef.current = { hoistedNoteId, unhoist: unhoistSpy };
+ }
+}
+
+/** Minimal Fancytree node stub: only `data.noteId` and `getParent()` are read by the service. */
+function fakeNode(noteId: string, parent?: { data: { noteId: string } }): Fancytree.FancytreeNode {
+ return {
+ data: { noteId },
+ getParent: () => parent
+ } as unknown as Fancytree.FancytreeNode;
+}
+
+describe("hoisted_note service", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ setActiveContext(null);
+ });
+
+ describe("getHoistedNoteId", () => {
+ it("returns the active context's hoisted note id, or root without an active context", () => {
+ setActiveContext("someNote");
+ expect(hoistedNoteService.getHoistedNoteId()).toBe("someNote");
+
+ setActiveContext(null);
+ expect(hoistedNoteService.getHoistedNoteId()).toBe("root");
+ });
+ });
+
+ describe("unhoist", () => {
+ it("delegates to the active context when present and is a no-op otherwise", async () => {
+ setActiveContext("someNote");
+ await hoistedNoteService.unhoist();
+ expect(unhoistSpy).toHaveBeenCalledTimes(1);
+
+ unhoistSpy.mockClear();
+ setActiveContext(null);
+ await hoistedNoteService.unhoist();
+ expect(unhoistSpy).not.toHaveBeenCalled();
+ });
+ });
+
+ describe("isHoistedNode / isTopLevelNode", () => {
+ it("matches root, matches the hoisted note id, and rejects anything else", () => {
+ setActiveContext("hoistedX");
+
+ expect(hoistedNoteService.isHoistedNode(fakeNode("root"))).toBe(true);
+ expect(hoistedNoteService.isHoistedNode(fakeNode("hoistedX"))).toBe(true);
+ expect(hoistedNoteService.isHoistedNode(fakeNode("other"))).toBe(false);
+ });
+
+ it("isTopLevelNode checks the node's parent against the hoisted node", () => {
+ setActiveContext("hoistedX");
+
+ const topLevel = fakeNode("child", { data: { noteId: "hoistedX" } });
+ const deep = fakeNode("child", { data: { noteId: "other" } });
+ expect(hoistedNoteService.isTopLevelNode(topLevel)).toBe(true);
+ expect(hoistedNoteService.isTopLevelNode(deep)).toBe(false);
+ });
+ });
+
+ describe("isHoistedInHiddenSubtree", () => {
+ it("returns false when hoisted on root", async () => {
+ setActiveContext("root");
+ expect(await hoistedNoteService.isHoistedInHiddenSubtree()).toBe(false);
+ });
+
+ it("reflects isHiddenCompletely of the hoisted note", async () => {
+ // A note cloned directly under root is NOT hidden completely.
+ buildNote({ id: "root", title: "Root" });
+ const visible = buildNote({ title: "Visible" });
+ visible.parents.push("root");
+ setActiveContext(visible.noteId);
+ expect(await hoistedNoteService.isHoistedInHiddenSubtree()).toBe(false);
+
+ // A note with no visible parent path is hidden completely.
+ const orphan = buildNote({ title: "Orphan" });
+ setActiveContext(orphan.noteId);
+ expect(await hoistedNoteService.isHoistedInHiddenSubtree()).toBe(true);
+ });
+ });
+
+ describe("checkNoteAccess", () => {
+ function ctx(hoistedNoteId: string): NoteContext {
+ return { hoistedNoteId } as NoteContext;
+ }
+
+ it("returns false when the note path cannot be resolved", async () => {
+ resolveNotePath.mockResolvedValue(null);
+ expect(await hoistedNoteService.checkNoteAccess("nope", ctx("root"))).toBe(false);
+ });
+
+ it("returns true when the resolved path already contains the hoisted note", async () => {
+ resolveNotePath.mockResolvedValue("hoistedX/target");
+ expect(await hoistedNoteService.checkNoteAccess("p", ctx("hoistedX"))).toBe(true);
+ expect(getNoteIdFromUrl).not.toHaveBeenCalled();
+ expect(confirm).not.toHaveBeenCalled();
+ });
+
+ it("returns true (skips the guard) when the path is inside _hidden but not bookmarks", async () => {
+ resolveNotePath.mockResolvedValue("_hidden/something");
+ expect(await hoistedNoteService.checkNoteAccess("p", ctx("hoistedX"))).toBe(true);
+ expect(confirm).not.toHaveBeenCalled();
+ });
+
+ it("returns false when the resolved path yields no note id", async () => {
+ resolveNotePath.mockResolvedValue("foo/bar");
+ getNoteIdFromUrl.mockReturnValue(null);
+ expect(await hoistedNoteService.checkNoteAccess("p", ctx("hoistedX"))).toBe(false);
+ });
+
+ it("prompts and unhoists when the hoisted note is not in the hidden subtree", async () => {
+ const requested = buildNote({ title: "Requested" });
+ // hoisted note cloned only under root -> hasAncestor('_hidden') is false
+ const hoisted = buildNote({ title: "Hoisted" });
+
+ resolveNotePath.mockResolvedValue("foo/bar");
+ getNoteIdFromUrl.mockReturnValue(requested.noteId);
+ confirm.mockResolvedValue(true);
+ setActiveContext(hoisted.noteId);
+
+ const result = await hoistedNoteService.checkNoteAccess("p", ctx(hoisted.noteId));
+ expect(result).toBe(true);
+ expect(confirm).toHaveBeenCalledTimes(1);
+ expect(unhoistSpy).toHaveBeenCalledTimes(1);
+ });
+
+ it("returns false when the user declines the unhoist confirmation", async () => {
+ const requested = buildNote({ title: "Requested" });
+ const hoisted = buildNote({ title: "Hoisted" });
+
+ resolveNotePath.mockResolvedValue("foo/bar");
+ getNoteIdFromUrl.mockReturnValue(requested.noteId);
+ confirm.mockResolvedValue(false);
+
+ const result = await hoistedNoteService.checkNoteAccess("p", ctx(hoisted.noteId));
+ expect(result).toBe(false);
+ expect(unhoistSpy).not.toHaveBeenCalled();
+ });
+
+ it("skips the confirmation when the hoisted note is already inside _hidden", async () => {
+ // hoisted note IS under _hidden -> hasAncestor('_hidden') is true, so the
+ // inner `!hasAncestor('_hidden')` is false; with a non-bookmark path the
+ // OR short-circuits false, the `&&` skips confirm(), and unhoist runs.
+ buildNote({ id: "_hidden", title: "Hidden" });
+ const hoisted = buildNote({ title: "HoistedHidden" });
+ hoisted.parents.push("_hidden");
+ const requested = buildNote({ title: "Target" });
+
+ resolveNotePath.mockResolvedValue("foo/bar");
+ getNoteIdFromUrl.mockReturnValue(requested.noteId);
+ setActiveContext(hoisted.noteId);
+
+ const result = await hoistedNoteService.checkNoteAccess("p", ctx(hoisted.noteId));
+ expect(result).toBe(true);
+ expect(confirm).not.toHaveBeenCalled();
+ expect(unhoistSpy).toHaveBeenCalledTimes(1);
+ });
+ });
+});
diff --git a/apps/client/src/services/i18n.spec.ts b/apps/client/src/services/i18n.spec.ts
index 3216c6cf0c..3b4af5ef74 100644
--- a/apps/client/src/services/i18n.spec.ts
+++ b/apps/client/src/services/i18n.spec.ts
@@ -1,7 +1,27 @@
import { findDuplicateJsonKeys, LOCALES } from "@triliumnext/commons";
import { readFileSync } from "fs";
import { join } from "path";
-import { describe, expect, it } from "vitest";
+import { describe, expect, it, vi } from "vitest";
+
+// Mock the http backend so i18next.init() never hits the network. The real
+// backend would try to fetch translation JSON over HTTP and the awaited init()
+// would hang until the connection fails. Our fake backend resolves read()
+// synchronously with an empty resource bundle.
+vi.mock("i18next-http-backend", () => {
+ class FakeBackend {
+ static type = "backend" as const;
+ type = "backend" as const;
+ init() {
+ // No configuration needed.
+ }
+ read(_language: string, _namespace: string, callback: (err: unknown, data: unknown) => void) {
+ callback(null, {});
+ }
+ }
+ return { default: FakeBackend };
+});
+
+const { getAvailableLocales, getCurrentLanguage, getLocaleById, initLocale, translationsInitializedPromise } = await import("./i18n");
describe("i18n", () => {
it("translations are valid JSON with no duplicate keys", () => {
@@ -18,9 +38,57 @@ describe("i18n", () => {
const duplicates = findDuplicateJsonKeys(translationFile);
expect(
duplicates,
- `Duplicate keys in locale '${locale.id}' at "${translationPath}":\n${
+ `Duplicate keys in locale '${locale.id}' at "${translationPath}":\n${
duplicates.map((d) => ` - "${d.key}" (line ${d.line})`).join("\n")}`
).toEqual([]);
}
});
+
+ describe("getAvailableLocales", () => {
+ it("returns the full LOCALES list", () => {
+ expect(getAvailableLocales()).toBe(LOCALES);
+ });
+ });
+
+ describe("getLocaleById", () => {
+ it("returns null for falsy locale ids", () => {
+ expect(getLocaleById(null)).toBeNull();
+ expect(getLocaleById(undefined)).toBeNull();
+ expect(getLocaleById("")).toBeNull();
+ });
+
+ it("returns the matching locale for a known id", () => {
+ const locale = getLocaleById("en");
+ expect(locale).not.toBeNull();
+ expect(locale?.id).toBe("en");
+ });
+
+ it("returns null for an unknown id", () => {
+ expect(getLocaleById("does-not-exist")).toBeNull();
+ });
+ });
+
+ describe("initLocale", () => {
+ it("initializes i18next with an explicit locale, sets dayjs and resolves the deferred", async () => {
+ (window as any).glob = { ...(window as any).glob, assetPath: "/assets" };
+
+ await initLocale("de");
+
+ expect(getCurrentLanguage()).toBe("de");
+ // The deferred resolves once translations are ready.
+ await expect(translationsInitializedPromise).resolves.toBeUndefined();
+ });
+
+ it("uses the default 'en' locale when called without arguments", async () => {
+ await initLocale();
+ expect(getCurrentLanguage()).toBe("en");
+ });
+ });
+
+ describe("getCurrentLanguage", () => {
+ it("reflects the language i18next was last initialized with", async () => {
+ await initLocale("en");
+ expect(getCurrentLanguage()).toBe("en");
+ });
+ });
});
diff --git a/apps/client/src/services/image.spec.ts b/apps/client/src/services/image.spec.ts
new file mode 100644
index 0000000000..07c891d19d
--- /dev/null
+++ b/apps/client/src/services/image.spec.ts
@@ -0,0 +1,81 @@
+import $ from "jquery";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+import imageService, { copyImageReferenceToClipboard } from "./image.js";
+import toastService from "./toast.js";
+
+describe("copyImageReferenceToClipboard", () => {
+ let execCommandSpy: ReturnType<typeof vi.fn>;
+ let removeAllRangesSpy: ReturnType<typeof vi.fn>;
+
+ beforeEach(() => {
+ // image.ts calls the bare global `logError`, normally installed by ws.ts (which setup.ts mocks).
+ (window as any).logError = vi.fn();
+
+ // happy-dom does not implement execCommand; provide a controllable stub.
+ execCommandSpy = vi.fn(() => true);
+ (document as any).execCommand = execCommandSpy;
+
+ // Track range clean-up performed in the finally block.
+ removeAllRangesSpy = vi.fn();
+ const selection = {
+ removeAllRanges: removeAllRangesSpy,
+ addRange: vi.fn()
+ };
+ vi.spyOn(window, "getSelection").mockReturnValue(selection as unknown as Selection);
+
+ vi.spyOn(toastService, "showMessage").mockImplementation(() => {});
+ });
+
+ afterEach(() => {
+ vi.restoreAllMocks();
+ });
+
+ it("selects the image, copies it and shows a success message, then cleans up", () => {
+ const element = document.createElement("div");
+ document.body.appendChild(element);
+ const $wrapper = $(element);
+
+ copyImageReferenceToClipboard($wrapper);
+
+ // contenteditable is toggled on then removed in the finally block.
+ expect($wrapper.attr("contenteditable")).toBeUndefined();
+ expect(execCommandSpy).toHaveBeenCalledWith("copy");
+ expect(toastService.showMessage).toHaveBeenCalledTimes(1);
+ // Selection was created on the element (selectImage took the happy path) and cleaned up.
+ expect(removeAllRangesSpy).toHaveBeenCalled();
+
+ element.remove();
+ });
+
+ it("reports an error when the copy command fails", () => {
+ execCommandSpy.mockReturnValue(false);
+ const $wrapper = $(document.createElement("div"));
+
+ copyImageReferenceToClipboard($wrapper);
+
+ expect(toastService.showMessage).not.toHaveBeenCalled();
+ expect((window as any).logError).toHaveBeenCalledTimes(1);
+ expect($wrapper.attr("contenteditable")).toBeUndefined();
+ });
+
+ it("does nothing in selectImage when the wrapper has no element", () => {
+ const addRange = vi.fn();
+ (window.getSelection as any).mockReturnValue({
+ removeAllRanges: removeAllRangesSpy,
+ addRange
+ });
+
+ // An empty jQuery wrapper -> .get(0) is undefined -> selectImage early-returns.
+ const $empty = $([] as unknown as HTMLElement);
+
+ copyImageReferenceToClipboard($empty);
+
+ expect(addRange).not.toHaveBeenCalled();
+ expect(execCommandSpy).toHaveBeenCalledWith("copy");
+ });
+
+ it("exposes copyImageReferenceToClipboard on the default export", () => {
+ expect(imageService.copyImageReferenceToClipboard).toBe(copyImageReferenceToClipboard);
+ });
+});
diff --git a/apps/client/src/services/import.spec.ts b/apps/client/src/services/import.spec.ts
new file mode 100644
index 0000000000..d8c7148787
--- /dev/null
+++ b/apps/client/src/services/import.spec.ts
@@ -0,0 +1,255 @@
+import { beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
+
+import type { WebSocketMessage } from "@triliumnext/commons";
+import appContext from "../components/app_context.js";
+import server from "./server.js";
+import toastService from "./toast.js";
+import ws from "./ws.js";
+
+// Capture the message handlers that import.ts registers at module load. The
+// global ws mock's subscribeToMessages is a no-op, so we replace it with a
+// capturing variant BEFORE importing the module under test.
+type MessageHandler = (message: WebSocketMessage) => void | Promise<void>;
+const handlers: MessageHandler[] = [];
+ws.subscribeToMessages = ((cb: MessageHandler) => {
+ handlers.push(cb);
+}) as typeof ws.subscribeToMessages;
+
+let importService: typeof import("./import.js").default;
+let uploadFiles: typeof import("./import.js").uploadFiles;
+
+beforeAll(async () => {
+ const mod = await import("./import.js");
+ importService = mod.default;
+ uploadFiles = mod.uploadFiles;
+ // Two handlers registered at load: importNotes + importAttachments.
+ expect(handlers.length).toBe(2);
+});
+
+// Toast service spies.
+toastService.showError = vi.fn();
+toastService.showPersistent = vi.fn();
+toastService.closePersistent = vi.fn();
+
+// A fake active note context whose setNote we can assert against.
+const setNote = vi.fn(async () => {});
+const getActiveContext = vi.fn(() => ({ setNote }) as any);
+(appContext as any).tabManager = { getActiveContext };
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ getActiveContext.mockReturnValue({ setNote } as any);
+});
+
+describe("uploadFiles", () => {
+ beforeEach(() => {
+ ($ as any).ajax = vi.fn(async () => ({}));
+ server.getHeaders = vi.fn(async () => ({ "x-h": "1" })) as typeof server.getHeaders;
+ });
+
+ it("throws on an unrecognized entity type", async () => {
+ await expect(uploadFiles("bogus", "p1", ["f"], { shrinkImages: false })).rejects.toThrow(
+ "Unrecognized import entity type 'bogus'."
+ );
+ expect(($ as any).ajax).not.toHaveBeenCalled();
+ });
+
+ it("returns early without uploading when there are no files", async () => {
+ const result = await uploadFiles("notes", "p1", [], { shrinkImages: false });
+ expect(result).toBeUndefined();
+ expect(($ as any).ajax).not.toHaveBeenCalled();
+ });
+
+ it("posts one ajax request per file, flagging the last, and forwards options + headers", async () => {
+ await uploadFiles("notes", "parent1", ["a", "b"], {
+ shrinkImages: true,
+ safeImport: "true"
+ });
+
+ const ajax = ($ as any).ajax as ReturnType<typeof vi.fn>;
+ expect(ajax).toHaveBeenCalledTimes(2);
+
+ const first = ajax.mock.calls[0][0];
+ expect(first.url).toContain("notes/parent1/notes-import");
+ expect(first.type).toBe("POST");
+ expect(first.headers).toEqual({ "x-h": "1" });
+ const firstData = first.data as FormData;
+ expect(firstData.get("last")).toBe("false");
+ expect(firstData.get("upload")).toBe("a");
+ expect(firstData.get("shrinkImages")).toBe("true");
+ expect(firstData.get("safeImport")).toBe("true");
+ // taskId is shared across files in the same upload batch.
+ const taskId = firstData.get("taskId");
+ expect(typeof taskId).toBe("string");
+
+ const second = ajax.mock.calls[1][0];
+ const secondData = second.data as FormData;
+ expect(secondData.get("last")).toBe("true");
+ expect(secondData.get("upload")).toBe("b");
+ expect(secondData.get("taskId")).toBe(taskId);
+ });
+
+ it("uses the attachments endpoint for the attachments entity type", async () => {
+ await uploadFiles("attachments", "host1", ["a"], { shrinkImages: false });
+ const first = ($ as any).ajax.mock.calls[0][0];
+ expect(first.url).toContain("notes/host1/attachments-import");
+ });
+
+ it("surfaces an upload error through the toast service via the ajax error callback", async () => {
+ ($ as any).ajax = vi.fn(async (opts: any) => {
+ opts.error({ responseText: "boom" });
+ return {};
+ });
+ await uploadFiles("notes", "p1", ["a"], { shrinkImages: false });
+ expect(toastService.showError).toHaveBeenCalledTimes(1);
+ });
+
+ it("is also reachable through the default export", async () => {
+ await importService.uploadFiles("notes", "p1", ["a"], { shrinkImages: false });
+ expect(($ as any).ajax).toHaveBeenCalledTimes(1);
+ });
+});
+
+// Convenience: invoke both subscribed handlers with a message.
+async function dispatch(message: any) {
+ for (const handler of handlers) {
+ await handler(message);
+ }
+}
+
+describe("importNotes ws handler", () => {
+ const handler = () => handlers[0];
+
+ it("ignores messages without a matching taskType", async () => {
+ await handler()({ type: "taskSucceeded" } as any); // no taskType
+ await handler()({ type: "taskSucceeded", taskType: "importAttachments" } as any); // wrong type
+ expect(toastService.showError).not.toHaveBeenCalled();
+ expect(toastService.showPersistent).not.toHaveBeenCalled();
+ });
+
+ it("closes the toast and shows an error on taskError", async () => {
+ await handler()({ type: "taskError", taskType: "importNotes", taskId: "t1", message: "nope" } as any);
+ expect(toastService.closePersistent).toHaveBeenCalledWith("t1");
+ expect(toastService.showError).toHaveBeenCalledWith("nope");
+ });
+
+ it("shows a persistent progress toast on taskProgressCount", async () => {
+ await handler()({ type: "taskProgressCount", taskType: "importNotes", taskId: "t2", progressCount: 3 } as any);
+ expect(toastService.showPersistent).toHaveBeenCalledTimes(1);
+ const toast = (toastService.showPersistent as any).mock.calls[0][0];
+ expect(toast.id).toBe("t2");
+ expect(toast.icon).toBe("plus");
+ });
+
+ it("shows a success toast and navigates to the imported note when one is returned", async () => {
+ await handler()({
+ type: "taskSucceeded",
+ taskType: "importNotes",
+ taskId: "t3",
+ result: { importedNoteId: "imp1" }
+ } as any);
+ const toast = (toastService.showPersistent as any).mock.calls[0][0];
+ expect(toast.timeout).toBe(5000);
+ expect(setNote).toHaveBeenCalledWith("imp1");
+ });
+
+ it("shows a success toast but does not navigate when there is no imported note id", async () => {
+ await handler()({
+ type: "taskSucceeded",
+ taskType: "importNotes",
+ taskId: "t4",
+ result: {}
+ } as any);
+ expect(toastService.showPersistent).toHaveBeenCalledTimes(1);
+ expect(setNote).not.toHaveBeenCalled();
+ });
+
+ it("tolerates a missing active context on success navigation", async () => {
+ getActiveContext.mockReturnValue(undefined as any);
+ await handler()({
+ type: "taskSucceeded",
+ taskType: "importNotes",
+ taskId: "t5",
+ result: { importedNoteId: "imp2" }
+ } as any);
+ expect(setNote).not.toHaveBeenCalled();
+ });
+
+ it("does nothing for a matching task with an unhandled message type", async () => {
+ await handler()({ type: "ping", taskType: "importNotes", taskId: "t6" } as any);
+ expect(toastService.showError).not.toHaveBeenCalled();
+ expect(toastService.showPersistent).not.toHaveBeenCalled();
+ expect(toastService.closePersistent).not.toHaveBeenCalled();
+ });
+});
+
+describe("importAttachments ws handler", () => {
+ const handler = () => handlers[1];
+
+ it("ignores messages without a matching taskType", async () => {
+ await handler()({ type: "taskSucceeded" } as any); // no taskType
+ await handler()({ type: "taskSucceeded", taskType: "importNotes" } as any); // wrong type
+ expect(toastService.showError).not.toHaveBeenCalled();
+ expect(toastService.showPersistent).not.toHaveBeenCalled();
+ });
+
+ it("closes the toast and shows an error on taskError", async () => {
+ await handler()({ type: "taskError", taskType: "importAttachments", taskId: "a1", message: "bad" } as any);
+ expect(toastService.closePersistent).toHaveBeenCalledWith("a1");
+ expect(toastService.showError).toHaveBeenCalledWith("bad");
+ });
+
+ it("shows a persistent progress toast on taskProgressCount", async () => {
+ await handler()({ type: "taskProgressCount", taskType: "importAttachments", taskId: "a2", progressCount: 1 } as any);
+ expect(toastService.showPersistent).toHaveBeenCalledTimes(1);
+ expect((toastService.showPersistent as any).mock.calls[0][0].id).toBe("a2");
+ });
+
+ it("navigates to the attachments view on success when a parent note id is present", async () => {
+ await handler()({
+ type: "taskSucceeded",
+ taskType: "importAttachments",
+ taskId: "a3",
+ result: { parentNoteId: "par1", importedNoteId: "imp3" }
+ } as any);
+ const toast = (toastService.showPersistent as any).mock.calls[0][0];
+ expect(toast.timeout).toBe(5000);
+ expect(setNote).toHaveBeenCalledWith("imp3", { viewScope: { viewMode: "attachments" } });
+ });
+
+ it("shows a success toast but does not navigate when there is no parent note id", async () => {
+ await handler()({
+ type: "taskSucceeded",
+ taskType: "importAttachments",
+ taskId: "a4",
+ result: {}
+ } as any);
+ expect(toastService.showPersistent).toHaveBeenCalledTimes(1);
+ expect(setNote).not.toHaveBeenCalled();
+ });
+
+ it("tolerates a missing active context on success navigation", async () => {
+ getActiveContext.mockReturnValue(undefined as any);
+ await handler()({
+ type: "taskSucceeded",
+ taskType: "importAttachments",
+ taskId: "a5",
+ result: { parentNoteId: "par2", importedNoteId: "imp4" }
+ } as any);
+ expect(setNote).not.toHaveBeenCalled();
+ });
+
+ it("does nothing for a matching task with an unhandled message type", async () => {
+ await handler()({ type: "ping", taskType: "importAttachments", taskId: "a6" } as any);
+ expect(toastService.showError).not.toHaveBeenCalled();
+ expect(toastService.showPersistent).not.toHaveBeenCalled();
+ expect(toastService.closePersistent).not.toHaveBeenCalled();
+ });
+});
+
+describe("dispatch sanity", () => {
+ it("delivers an unrelated message to both handlers without side effects", async () => {
+ await dispatch({ type: "ping" });
+ expect(toastService.showError).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/client/src/services/in_app_help.spec.ts b/apps/client/src/services/in_app_help.spec.ts
index e19d0a095a..a038ffc8ae 100644
--- a/apps/client/src/services/in_app_help.spec.ts
+++ b/apps/client/src/services/in_app_help.spec.ts
@@ -1,8 +1,10 @@
import { describe, expect, it } from "vitest";
-import { byBookType, byNoteType } from "./in_app_help.js";
+import { byBookType, byNoteType, getHelpUrlForNote } from "./in_app_help.js";
import fs from "fs";
import type { HiddenSubtreeItem } from "@triliumnext/commons";
import path from "path";
+import { buildNote } from "../test/easy-froca.js";
+import type FNote from "../entities/fnote.js";
describe("Help button", () => {
it("All help notes are accessible", () => {
@@ -36,3 +38,51 @@ describe("Help button", () => {
}
});
});
+
+describe("getHelpUrlForNote", () => {
+ it("returns undefined for null/undefined notes", () => {
+ expect(getHelpUrlForNote(null)).toBeUndefined();
+ expect(getHelpUrlForNote(undefined)).toBeUndefined();
+ });
+
+ it("returns the markdown help id for a markdown code note", () => {
+ const note = buildNote({ title: "MD", type: "code" }) as FNote;
+ note.mime = "text/markdown";
+ expect(note.isMarkdown()).toBe(true);
+ expect(getHelpUrlForNote(note)).toBe("6RM1Q7ppFVoj");
+ });
+
+ it("returns the per-note-type help id when one is defined", () => {
+ const note = buildNote({ title: "Mermaid", type: "mermaid" });
+ expect(getHelpUrlForNote(note)).toBe(byNoteType.mermaid);
+ expect(getHelpUrlForNote(note)).toBe("s1aBHPd79XYj");
+ });
+
+ it("returns the calendarRoot help id for a note labelled calendarRoot", () => {
+ // type with a null byNoteType entry so it falls through to the label checks
+ const note = buildNote({ title: "Cal", type: "canvas", "#calendarRoot": "" });
+ expect(getHelpUrlForNote(note)).toBe("l0tKav7yLHGF");
+ });
+
+ it("returns the textSnippet help id for a note labelled textSnippet", () => {
+ const note = buildNote({ title: "Snippet", type: "text", "#textSnippet": "" });
+ expect(getHelpUrlForNote(note)).toBe("pwc194wlRzcH");
+ });
+
+ it("returns the per-book-view help id for a book note with a viewType label", () => {
+ const note = buildNote({ title: "Tbl", type: "book", "#viewType": "table" });
+ expect(getHelpUrlForNote(note)).toBe(byBookType.table);
+ expect(getHelpUrlForNote(note)).toBe("2FvYrpmOXm29");
+ });
+
+ it("falls back to the empty-string lookup for a book note without a viewType label", () => {
+ const note = buildNote({ title: "PlainBook", type: "book" });
+ // no viewType label -> getAttributeValue returns null -> "" -> byBookType[""] is undefined
+ expect(getHelpUrlForNote(note)).toBeUndefined();
+ });
+
+ it("returns undefined for a plain text note with no special labels", () => {
+ const note = buildNote({ title: "Plain", type: "text" });
+ expect(getHelpUrlForNote(note)).toBeUndefined();
+ });
+});
diff --git a/apps/client/src/services/keyboard_actions.spec.ts b/apps/client/src/services/keyboard_actions.spec.ts
new file mode 100644
index 0000000000..881cf5289c
--- /dev/null
+++ b/apps/client/src/services/keyboard_actions.spec.ts
@@ -0,0 +1,274 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+import type { ActionKeyboardShortcut } from "@triliumnext/commons";
+import appContext from "../components/app_context.js";
+
+// `appContext` pulls in a very large dependency graph (CKEditor, CodeMirror,
+// Tabulator, …) and at module-load `keyboard_actions.ts` only needs
+// `triggerCommand` + `tabManager.activeNtxId`. Stub it out.
+vi.mock("../components/app_context.js", () => ({
+ default: {
+ triggerCommand: vi.fn(),
+ tabManager: { activeNtxId: "ntx-active" }
+ }
+}));
+
+type KbModule = typeof import("./keyboard_actions.js");
+type ShortcutsModule = typeof import("./shortcuts.js");
+
+interface LoadedModule {
+ kb: KbModule;
+ /** the SAME shortcuts instance the freshly-loaded keyboard_actions imports */
+ shortcuts: ShortcutsModule["default"];
+}
+
+/**
+ * (Re)load `keyboard_actions.ts` from scratch with a controlled set of actions
+ * returned by `server.get("keyboard-actions")`. The repo is built once at
+ * module-evaluation time, so we must seed the response before importing.
+ *
+ * Because `vi.resetModules()` produces a fresh module graph, spies must be
+ * installed on the freshly imported `shortcuts` instance — that's what the
+ * `beforeKbImport` hook is for (it runs before `keyboard_actions` is imported,
+ * so it can also observe the module-load-time `bindGlobalShortcut` calls).
+ */
+async function loadModule(
+ actions: ActionKeyboardShortcut[],
+ beforeKbImport?: (shortcuts: ShortcutsModule["default"]) => void
+): Promise<LoadedModule> {
+ vi.resetModules();
+
+ // The fresh module graph re-imports server.js (still globally mocked by
+ // setup.ts); override its `get` so the keyboard-actions GET yields our data.
+ const freshServer = (await import("./server.js")).default;
+ freshServer.get = vi.fn(async (url: string) => {
+ if (url === "keyboard-actions") {
+ // clone so the module's in-place filtering doesn't mutate our input
+ return actions.map((a) => ({ ...a, effectiveShortcuts: a.effectiveShortcuts ? [...a.effectiveShortcuts] : a.effectiveShortcuts }));
+ }
+ return [];
+ }) as typeof freshServer.get;
+
+ const shortcuts = (await import("./shortcuts.js")).default;
+ beforeKbImport?.(shortcuts);
+
+ const kb = await import("./keyboard_actions.js");
+ return { kb, shortcuts };
+}
+
+function action(partial: { actionName: string; scope?: string; effectiveShortcuts?: string[] }): ActionKeyboardShortcut {
+ return partial as unknown as ActionKeyboardShortcut;
+}
+
+describe("keyboard_actions", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it("filters out separators and global: shortcuts when building the repo", async () => {
+ const { kb } = await loadModule([
+ action({ actionName: "" }), // separator -> dropped
+ action({ actionName: "doFoo", effectiveShortcuts: ["global:ctrl+g", "ctrl+f"], scope: "text-detail" }),
+ action({ actionName: "noShortcuts" }) // effectiveShortcuts undefined -> defaults to []
+ ]);
+
+ const all = await kb.default.getActions();
+ // separator removed
+ expect(all.map((a) => a.actionName)).toEqual(["doFoo", "noShortcuts"]);
+
+ // global: prefixed shortcut stripped, the plain one kept
+ const foo = kb.getActionSync("doFoo");
+ expect(foo.effectiveShortcuts).toEqual(["ctrl+f"]);
+
+ // undefined effectiveShortcuts normalised to []
+ expect(kb.getActionSync("noShortcuts").effectiveShortcuts).toEqual([]);
+ });
+
+ it("getActionsForScope returns only matching scope", async () => {
+ const { kb } = await loadModule([
+ action({ actionName: "winA", scope: "window", effectiveShortcuts: [] }),
+ action({ actionName: "treeA", scope: "note-tree", effectiveShortcuts: [] }),
+ action({ actionName: "winB", scope: "window", effectiveShortcuts: [] })
+ ]);
+
+ const treeActions = await kb.default.getActionsForScope("note-tree");
+ expect(treeActions.map((a) => a.actionName)).toEqual(["treeA"]);
+ });
+
+ it("binds window-scoped shortcuts globally at module load", async () => {
+ let spy: ReturnType<typeof vi.spyOn> | undefined;
+ const { kb } = await loadModule(
+ [
+ action({ actionName: "winA", scope: "window", effectiveShortcuts: ["ctrl+1", "ctrl+2"] }),
+ action({ actionName: "winNoShortcut", scope: "window" }), // undefined effectiveShortcuts -> [] loop body skipped
+ action({ actionName: "treeA", scope: "note-tree", effectiveShortcuts: ["ctrl+9"] }) // wrong scope -> ignored
+ ],
+ // install the spy on the fresh instance BEFORE keyboard_actions imports
+ (shortcuts) => {
+ spy = vi.spyOn(shortcuts, "bindGlobalShortcut");
+ }
+ );
+
+ // wait for the module-load `getActionsForScope("window").then(...)` to settle
+ await kb.default.getActions();
+ await Promise.resolve();
+
+ expect(spy).toHaveBeenCalledTimes(2);
+ const boundShortcuts = spy!.mock.calls.map((c) => c[0]);
+ expect(boundShortcuts).toEqual(["ctrl+1", "ctrl+2"]);
+
+ // The bound handler routes to appContext.triggerCommand with the active ntx id.
+ const handler = spy!.mock.calls[0][1] as () => void;
+ handler();
+ expect(appContext.triggerCommand).toHaveBeenCalledWith("winA", { ntxId: "ntx-active" });
+
+ spy!.mockRestore();
+ });
+
+ it("setupActionsForElement returns [] for an empty jQuery element", async () => {
+ const { kb } = await loadModule([action({ actionName: "a", scope: "text-detail", effectiveShortcuts: ["ctrl+a"] })]);
+ const $empty = $(); // length 0 -> $el[0] undefined
+ const bindings = await kb.default.setupActionsForElement("text-detail", $empty as any, {} as any, "ntx1");
+ expect(bindings).toEqual([]);
+ });
+
+ it("setupActionsForElement binds each shortcut and wires the command", async () => {
+ const { kb } = await loadModule([
+ action({ actionName: "cmdA", scope: "text-detail", effectiveShortcuts: ["ctrl+a", "ctrl+b"] }),
+ action({ actionName: "cmdNoShortcut", scope: "text-detail" }), // undefined -> inner loop skipped
+ action({ actionName: "other", scope: "note-tree", effectiveShortcuts: ["ctrl+z"] }) // other scope ignored
+ ]);
+
+ const $el = $("<div></div>");
+ const component = { triggerCommand: vi.fn() } as any;
+ const bindings = await kb.default.setupActionsForElement("text-detail", $el as any, component, "ntx1");
+
+ // two shortcuts on cmdA each produced a binding
+ expect(bindings).toHaveLength(2);
+ expect(bindings.map((b) => b.shortcut)).toEqual(["ctrl+a", "ctrl+b"]);
+
+ // invoking the stored handler triggers the action command with the ntxId
+ bindings[0].handler(new KeyboardEvent("keydown"));
+ expect(component.triggerCommand).toHaveBeenCalledWith("cmdA", { ntxId: "ntx1" });
+ });
+
+ it("handles a repo action whose effectiveShortcuts becomes nullish (the ?? [] fallbacks)", async () => {
+ // The loader normalizes effectiveShortcuts to an array, but the repo entry is
+ // shared by reference (getActionSync returns it), so it can be mutated back to
+ // nullish — exercising the defensive `?? []` fallbacks in the reader functions.
+ const { kb } = await loadModule([
+ action({ actionName: "nullable", scope: "text-detail", effectiveShortcuts: ["ctrl+a"] })
+ ]);
+ await kb.default.getActions();
+
+ kb.getActionSync("nullable").effectiveShortcuts = undefined;
+
+ // setupActionsForElement: inner `for ... of (effectiveShortcuts ?? [])` -> no bindings
+ const $el = $("<div></div>");
+ const bindings = await kb.default.setupActionsForElement("text-detail", $el as any, { triggerCommand: vi.fn() } as any, "n");
+ expect(bindings).toEqual([]);
+
+ // updateDisplayedShortcuts: both `(effectiveShortcuts ?? []).join(...)` fallbacks
+ const $container = $(`<div>
+ <kbd data-command="nullable">something</kbd>
+ <span data-trigger-command="nullable"></span>
+ </div>`);
+ kb.default.updateDisplayedShortcuts($container as any);
+ await new Promise((r) => setTimeout(r, 0));
+
+ // empty join + text !== "not set" -> set to ""
+ expect($container.find('kbd[data-command="nullable"]').text()).toBe("");
+ // empty join + no title -> title becomes "" (empty shortcuts)
+ expect($container.find('[data-trigger-command="nullable"]').attr("title")).toBe("");
+ });
+
+ it("setupActionsForElement skips falsy bindings (non-desktop) without pushing", async () => {
+ // override the fresh bindElShortcut to return undefined -> binding falsy -> not pushed
+ let bindSpy: ReturnType<typeof vi.spyOn> | undefined;
+ const { kb } = await loadModule(
+ [action({ actionName: "cmdA", scope: "text-detail", effectiveShortcuts: ["ctrl+a"] })],
+ (shortcuts) => {
+ bindSpy = vi.spyOn(shortcuts, "bindElShortcut").mockReturnValue(undefined as any);
+ }
+ );
+
+ const $el = $("<div></div>");
+ const component = { triggerCommand: vi.fn() } as any;
+ const bindings = await kb.default.setupActionsForElement("text-detail", $el as any, component, null);
+
+ expect(bindSpy).toHaveBeenCalledTimes(1);
+ expect(bindings).toEqual([]);
+ bindSpy!.mockRestore();
+ });
+
+ it("getAction throws for an unknown action by default and is silent when asked", async () => {
+ const { kb } = await loadModule([action({ actionName: "known", scope: "window", effectiveShortcuts: [] })]);
+
+ await expect(kb.default.getAction("known")).resolves.toMatchObject({ actionName: "known" });
+
+ await expect(kb.default.getAction("missing" as never)).rejects.toThrow("Cannot find action 'missing'");
+
+ const debugSpy = vi.spyOn(console, "debug").mockImplementation(() => {});
+ const result = await kb.default.getAction("missing" as never, true);
+ expect(result).toBeUndefined();
+ expect(debugSpy).toHaveBeenCalledWith("Cannot find action 'missing'");
+ debugSpy.mockRestore();
+ });
+
+ it("updateDisplayedShortcuts fills kbd[data-command] text and appends to data-trigger-command title", async () => {
+ const { kb } = await loadModule([
+ action({ actionName: "cmdKbd", scope: "window", effectiveShortcuts: ["ctrl+a", "ctrl+b"] }),
+ action({ actionName: "cmdEmpty", scope: "window", effectiveShortcuts: [] }),
+ action({ actionName: "cmdTrigger", scope: "window", effectiveShortcuts: ["ctrl+t"] }),
+ action({ actionName: "cmdTriggerNoTitle", scope: "window", effectiveShortcuts: ["ctrl+n"] }),
+ action({ actionName: "cmdTriggerAlready", scope: "window", effectiveShortcuts: ["ctrl+x"] })
+ ]);
+ await kb.default.getActions();
+
+ const $container = $(`
+ <div>
+ <kbd data-command="cmdKbd">not set</kbd>
+ <kbd data-command="cmdEmpty">not set</kbd>
+ <kbd data-command="">no name</kbd>
+ <kbd data-command="cmdMissing">not set</kbd>
+ <span data-trigger-command="cmdTrigger" title="My label"></span>
+ <span data-trigger-command="cmdTriggerNoTitle"></span>
+ <span data-trigger-command="cmdTriggerAlready" title="X (ctrl+x)"></span>
+ <span data-trigger-command=""></span>
+ <span data-trigger-command="cmdMissing"></span>
+ </div>
+ `);
+
+ kb.default.updateDisplayedShortcuts($container as any);
+
+ // jQuery .each runs synchronously but the async getAction inside resolves later
+ await new Promise((r) => setTimeout(r, 0));
+
+ expect($container.find('kbd[data-command="cmdKbd"]').text()).toBe("ctrl+a, ctrl+b");
+ // empty shortcuts but text already "not set" -> condition false -> text untouched
+ expect($container.find('kbd[data-command="cmdEmpty"]').text()).toBe("not set");
+ // missing action -> getAction silent returns undefined -> skipped
+ expect($container.find('kbd[data-command="cmdMissing"]').text()).toBe("not set");
+
+ // title with content gets the shortcut appended in parentheses
+ expect($container.find('[data-trigger-command="cmdTrigger"]').attr("title")).toBe("My label (ctrl+t)");
+ // no title -> becomes just the shortcuts
+ expect($container.find('[data-trigger-command="cmdTriggerNoTitle"]').attr("title")).toBe("ctrl+n");
+ // title already includes the shortcut -> early return, unchanged
+ expect($container.find('[data-trigger-command="cmdTriggerAlready"]').attr("title")).toBe("X (ctrl+x)");
+ });
+
+ it("updateDisplayedShortcuts sets text when shortcuts empty but element text differs from 'not set'", async () => {
+ const { kb } = await loadModule([
+ action({ actionName: "cmdEmpty2", scope: "window", effectiveShortcuts: [] })
+ ]);
+ await kb.default.getActions();
+
+ const $container = $(`<div><kbd data-command="cmdEmpty2">something</kbd></div>`);
+ kb.default.updateDisplayedShortcuts($container as any);
+ await new Promise((r) => setTimeout(r, 0));
+
+ // text !== "not set" -> condition true -> text set to "" (empty joined shortcuts)
+ expect($container.find('kbd[data-command="cmdEmpty2"]').text()).toBe("");
+ });
+});
diff --git a/apps/client/src/services/keyboard_actions.ts b/apps/client/src/services/keyboard_actions.ts
index d447a90019..e9d9625a11 100644
--- a/apps/client/src/services/keyboard_actions.ts
+++ b/apps/client/src/services/keyboard_actions.ts
@@ -50,6 +50,7 @@ async function setupActionsForElement(scope: string, $el: JQuery<HTMLElement>, c
getActionsForScope("window").then((actions) => {
for (const action of actions) {
+ /* v8 ignore next -- effectiveShortcuts is always normalized to an array by the loader (line 13) before this resolves, so the ?? [] fallback is unreachable */
for (const shortcut of action.effectiveShortcuts ?? []) {
shortcutService.bindGlobalShortcut(shortcut, () => appContext.triggerCommand(action.actionName, { ntxId: appContext.tabManager.activeNtxId }));
}
diff --git a/apps/client/src/services/link.spec.ts b/apps/client/src/services/link.spec.ts
index eb52c3efc0..7d2e2ef748 100644
--- a/apps/client/src/services/link.spec.ts
+++ b/apps/client/src/services/link.spec.ts
@@ -1,7 +1,76 @@
-import { describe, expect, it } from "vitest";
-import { parseNavigationStateFromUrl } from "./link.js";
+import { beforeEach, describe, expect, it, vi } from "vitest";
-describe("Link", () => {
+import $ from "jquery";
+
+// `link.ts` references the bare global `logError` (normally installed by ws.ts, which setup.ts mocks).
+(globalThis as any).logError = (globalThis as any).logError ?? (() => {});
+
+// We re-mock ws.js here (instead of relying on the global setup stub) so we can supply the named
+// `logError` export that tree.ts (reached via createLink's note-path resolution) calls. We keep the
+// froca-relevant surface (subscribeToMessages / waitForMaxKnownEntityChangeId) intact.
+vi.mock("./ws.js", () => {
+ const noop = () => {};
+ return {
+ default: {
+ subscribeToMessages: noop,
+ waitForMaxKnownEntityChangeId: async () => {},
+ logError: noop
+ },
+ subscribeToMessages: noop,
+ logError: noop
+ };
+});
+
+// Mocks for the heavy / side-effecting collaborators. These avoid pulling in CKEditor / CodeMirror
+// (via note_context) and let us assert on the navigation commands link.ts dispatches.
+const triggerCommand = vi.fn();
+const openTabWithNoteWithHoisting = vi.fn();
+vi.mock("../components/app_context.js", () => ({
+ default: {
+ triggerCommand: (...args: unknown[]) => triggerCommand(...args),
+ tabManager: {
+ openTabWithNoteWithHoisting: (...args: unknown[]) => openTabWithNoteWithHoisting(...args)
+ }
+ }
+}));
+
+const openInCurrentNoteContext = vi.fn();
+vi.mock("../components/note_context.js", () => ({
+ openInCurrentNoteContext: (...args: unknown[]) => openInCurrentNoteContext(...args)
+}));
+
+const openContextMenu = vi.fn();
+vi.mock("../menus/link_context_menu.js", () => ({
+ default: {
+ openContextMenu: (...args: unknown[]) => openContextMenu(...args)
+ }
+}));
+
+const showError = vi.fn();
+vi.mock("./toast.js", () => ({
+ showError: (...args: unknown[]) => showError(...args)
+}));
+
+vi.mock("./i18n.js", () => ({
+ t: (key: string) => key
+}));
+
+import { buildNote } from "../test/easy-froca";
+import froca from "./froca.js";
+import treeService from "./tree.js";
+import linkService, {
+ calculateHash,
+ goToLinkExt,
+ parseNavigationStateFromUrl
+} from "./link.js";
+import utils from "./utils.js";
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ delete (window as any).electronApi;
+});
+
+describe("parseNavigationStateFromUrl", () => {
it("parses plain searchString", () => {
const output = parseNavigationStateFromUrl("http://localhost:8080/#?searchString=hello");
expect(output).toMatchObject({ searchString: "hello" });
@@ -41,4 +110,615 @@ describe("Link", () => {
const output = parseNavigationStateFromUrl("/root/abc123");
expect(output).toStrictEqual({});
});
+
+ it("returns empty object for undefined / no-hash input", () => {
+ expect(parseNavigationStateFromUrl(undefined)).toStrictEqual({});
+ expect(parseNavigationStateFromUrl("no-hash-here")).toStrictEqual({});
+ });
+
+ it("parses all recognised hash params and warns on unknown ones", () => {
+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
+ const output = parseNavigationStateFromUrl(
+ "#root/aaaaaaaaaaaa?ntxId=n1&hoistedNoteId=h1&viewMode=source&attachmentId=att1&bookmark=bm1&popup=1&foo=bar"
+ );
+ expect(output).toMatchObject({
+ notePath: "root/aaaaaaaaaaaa",
+ ntxId: "n1",
+ hoistedNoteId: "h1",
+ openInPopup: true
+ });
+ expect((output as any).viewScope).toMatchObject({
+ viewMode: "source",
+ attachmentId: "att1",
+ bookmark: "bm1"
+ });
+ expect(warn).toHaveBeenCalledWith("Unrecognized hash parameter 'foo'.");
+ warn.mockRestore();
+ });
+
+ it("returns empty object when the note path does not match the id pattern", () => {
+ // hash present at index 0, but the path is too short to be a valid note id
+ expect(parseNavigationStateFromUrl("#ab")).toStrictEqual({});
+ });
+});
+
+describe("calculateHash", () => {
+ it("returns an empty string when there is no note path and no params", () => {
+ expect(calculateHash({} as any)).toBe("");
+ });
+
+ it("builds a hash from the note path only", () => {
+ expect(calculateHash({ notePath: "root/abc" } as any)).toBe("#root/abc");
+ });
+
+ it("appends all relevant params and skips root hoisted note and default view mode", () => {
+ const hash = calculateHash({
+ notePath: "root/abc",
+ ntxId: "n1",
+ hoistedNoteId: "h1",
+ viewScope: { viewMode: "source", attachmentId: "att 1" }
+ } as any);
+ expect(hash).toBe("#root/abc?ntxId=n1&hoistedNoteId=h1&viewMode=source&attachmentId=att%201");
+ });
+
+ it("omits params that are at their defaults", () => {
+ const hash = calculateHash({
+ notePath: "root/abc",
+ hoistedNoteId: "root",
+ viewScope: { viewMode: "default" }
+ } as any);
+ expect(hash).toBe("#root/abc");
+ });
+
+ it("produces only the param string when note path is empty", () => {
+ expect(calculateHash({ ntxId: "n1" } as any)).toBe("#?ntxId=n1");
+ });
+});
+
+describe("getNotePathFromUrl", () => {
+ it("extracts the note path from a hash url and returns null otherwise", () => {
+ expect(linkService.getNotePathFromUrl("https://x.test/#root/abc_123")).toBe("root/abc_123");
+ expect(linkService.getNotePathFromUrl("https://x.test/no-hash")).toBeNull();
+ });
+});
+
+describe("createLink", () => {
+ it("returns a [missing note] span when the note path is empty", async () => {
+ const $el = await linkService.createLink(" ");
+ expect($el.is("span")).toBe(true);
+ expect($el.text()).toBe("[missing note]");
+ });
+
+ it("renders an anchor with the resolved title, prefixing bare paths with root/", async () => {
+ const note = buildNote({ title: "My note" });
+ const $el = await linkService.createLink(note.noteId);
+ const $a = $el.find("a");
+ expect($a.attr("href")).toBe(`#root/${note.noteId}`);
+ expect($a.text()).toBe("My note");
+ // default options: tooltip enabled, not a reference link
+ expect($a.hasClass("no-tooltip-preview")).toBe(false);
+ expect($a.hasClass("reference-link")).toBe(false);
+ });
+
+ it("honours showTooltip=false, referenceLink and showNoteIcon", async () => {
+ const note = buildNote({ title: "Icon note", "#iconClass": "bx bx-star" });
+ const $el = await linkService.createLink(`root/${note.noteId}`, {
+ showTooltip: false,
+ referenceLink: true,
+ showNoteIcon: true
+ });
+ const $a = $el.find("a");
+ expect($a.hasClass("no-tooltip-preview")).toBe(true);
+ expect($a.hasClass("reference-link")).toBe(true);
+ // an icon span is prepended
+ expect($el.children("span.bx").length).toBeGreaterThan(0);
+ });
+
+ it("uses an explicit title without consulting the tree", async () => {
+ const note = buildNote({ title: "Real title" });
+ const $el = await linkService.createLink(`root/${note.noteId}`, { title: "Override" });
+ expect($el.find("a").text()).toBe("Override");
+ });
+
+ it("auto-converts image notes to an <img> element", async () => {
+ const note = buildNote({ title: "Pic", type: "image" });
+ const $el = await linkService.createLink(`root/${note.noteId}`, { autoConvertToImage: true, title: "Pic" });
+ expect($el.is("img")).toBe(true);
+ expect($el.attr("alt")).toBe("Pic");
+ expect($el.attr("src")).toContain(`api/images/${note.noteId}/Pic?`);
+ });
+
+ it("returns a [missing note] span when no note id can be resolved", async () => {
+ // a trailing empty path segment yields an empty noteId
+ const $el = await linkService.createLink("/");
+ expect($el.text()).toBe("[missing note]");
+ });
+
+ it("renders the note path breadcrumb when showNotePath is set for a nested note", async () => {
+ // Build a real tree rooted at "root" so tree resolution can walk the parents.
+ const root = buildNote({
+ id: "root",
+ title: "Root",
+ children: [{ title: "Parent", children: [{ title: "Child" }] }]
+ });
+ const parentId = root.children[0];
+ const parent = froca.getNoteFromCache(parentId)!;
+ const childId = parent.children[0];
+ const $el = await linkService.createLink(`root/${parentId}/${childId}`, { showNotePath: true });
+ // a <small> breadcrumb should be appended alongside the anchor
+ expect($el.find("small").length).toBe(1);
+ expect($el.find("a").length).toBeGreaterThanOrEqual(1);
+ });
+
+ it("renders the home breadcrumb when showNotePath is set for the root note", async () => {
+ buildNote({ id: "root", title: "Root" });
+ const $el = await linkService.createLink("root", { showNotePath: true });
+ expect($el.find("a").length).toBe(1);
+ // root path => single ⌂ segment => a <small> with the home glyph
+ expect($el.find("small").length).toBe(1);
+ });
+
+ it("resolves an attachment title when viewing attachments", async () => {
+ const note = buildNote({ title: "Has attachment" });
+ froca.getAttachment = vi.fn(async () => ({ title: "Attachment title" }) as any);
+ const $el = await linkService.createLink(`root/${note.noteId}`, {
+ viewScope: { viewMode: "attachments", attachmentId: "att-1" }
+ });
+ expect($el.find("a").text()).toBe("Attachment title");
+ expect(froca.getAttachment).toHaveBeenCalledWith("att-1");
+ });
+
+ it("falls back to [missing attachment] when the attachment is absent", async () => {
+ const note = buildNote({ title: "No attachment" });
+ froca.getAttachment = vi.fn(async () => null as any);
+ const $el = await linkService.createLink(`root/${note.noteId}`, {
+ viewScope: { viewMode: "attachments", attachmentId: "att-missing" }
+ });
+ expect($el.find("a").text()).toBe("[missing attachment]");
+ });
+
+ it("uses a source-mode icon when showing the icon for a source view", async () => {
+ const note = buildNote({ title: "Source view" });
+ const $el = await linkService.createLink(`root/${note.noteId}`, {
+ showNoteIcon: true,
+ viewScope: { viewMode: "source" }
+ });
+ expect($el.find("span.bx.bx-code-curly").length).toBe(1);
+ });
+
+ it("uses an attachments-mode icon when showing the icon for an attachments view", async () => {
+ const note = buildNote({ title: "Attachments view" });
+ froca.getAttachment = vi.fn(async () => ({ title: "Att" }) as any);
+ const $el = await linkService.createLink(`root/${note.noteId}`, {
+ showNoteIcon: true,
+ viewScope: { viewMode: "attachments", attachmentId: "att-x" }
+ });
+ expect($el.find("span.bx.bx-file").length).toBe(1);
+ });
+
+ it("renders no icon for a view mode without a dedicated icon", async () => {
+ const note = buildNote({ title: "Help view" });
+ const $el = await linkService.createLink(`root/${note.noteId}`, {
+ showNoteIcon: true,
+ title: "Help view",
+ viewScope: { viewMode: "contextual-help" }
+ });
+ // contextual-help has no icon mapping => no icon span prepended
+ expect($el.children("span.bx").length).toBe(0);
+ });
+
+ it("does not auto-convert image notes when not viewing in default mode", async () => {
+ const note = buildNote({ title: "Pic2", type: "image" });
+ const $el = await linkService.createLink(`root/${note.noteId}`, {
+ autoConvertToImage: true,
+ title: "Pic2",
+ viewScope: { viewMode: "source" }
+ });
+ expect($el.is("img")).toBe(false);
+ });
+
+ it("auto-converts image notes with an empty title", async () => {
+ const note = buildNote({ title: "", type: "canvas" });
+ const $el = await linkService.createLink(`root/${note.noteId}`, {
+ autoConvertToImage: true,
+ title: ""
+ });
+ expect($el.is("img")).toBe(true);
+ expect($el.attr("alt")).toBe("");
+ expect($el.attr("src")).toContain(`api/images/${note.noteId}/?`);
+ });
+
+ it("falls back to an empty breadcrumb when the note path cannot be resolved", async () => {
+ const note = buildNote({ title: "Unresolvable" });
+ const spy = vi.spyOn(treeService, "resolveNotePathToSegments").mockResolvedValue(null);
+ const $el = await linkService.createLink(`root/${note.noteId}`, { showNotePath: true });
+ // resolve returned null => empty segments => getNotePathTitleComponents("") still yields a stub
+ expect($el.find("a").length).toBe(1);
+ expect(spy).toHaveBeenCalled();
+ spy.mockRestore();
+ });
+
+ it("does not render an icon span when the note has no icon", async () => {
+ const note = buildNote({ title: "No icon" });
+ // Force getIcon to return a falsy value so the icon branch is skipped.
+ note.getIcon = (() => "") as typeof note.getIcon;
+ const $el = await linkService.createLink(`root/${note.noteId}`, { showNoteIcon: true });
+ expect($el.children("span.bx").length).toBe(0);
+ expect($el.find("a").length).toBe(1);
+ });
+
+ it("does not auto-convert non-image notes to an <img>", async () => {
+ const note = buildNote({ title: "Plain", type: "text" });
+ const $el = await linkService.createLink(`root/${note.noteId}`, { autoConvertToImage: true });
+ expect($el.is("img")).toBe(false);
+ expect($el.find("a").length).toBe(1);
+ });
+});
+
+describe("goToLinkExt", () => {
+ function leftClick(extra: Record<string, unknown> = {}) {
+ return { type: "click", which: 1, preventDefault: vi.fn(), stopPropagation: vi.fn(), ...extra } as any;
+ }
+
+ it("returns true immediately for data: links without navigating", () => {
+ expect(goToLinkExt(null, "data:text/plain;base64,AAAA")).toBe(true);
+ expect(triggerCommand).not.toHaveBeenCalled();
+ });
+
+ it("opens an internal note path in the current context on a plain left click", () => {
+ const result = goToLinkExt(leftClick(), "#root/aaaaaaaaaaaa");
+ expect(result).toBe(true);
+ expect(openInCurrentNoteContext).toHaveBeenCalled();
+ });
+
+ it("opens in a popup when the url requests it", () => {
+ goToLinkExt(leftClick(), "#root/aaaaaaaaaaaa?popup=1");
+ expect(triggerCommand).toHaveBeenCalledWith("openInPopup", { noteIdOrPath: "root/aaaaaaaaaaaa" });
+ });
+
+ it("opens in a new window on shift+left-click", () => {
+ goToLinkExt(leftClick({ shiftKey: true }), "#root/aaaaaaaaaaaa");
+ expect(triggerCommand).toHaveBeenCalledWith("openInWindow", expect.objectContaining({ notePath: "root/aaaaaaaaaaaa" }));
+ });
+
+ it("opens in a new tab on a middle click", () => {
+ const evt = { type: "auxclick", which: 2, preventDefault: vi.fn(), stopPropagation: vi.fn() } as any;
+ goToLinkExt(evt, "#root/aaaaaaaaaaaa");
+ expect(openTabWithNoteWithHoisting).toHaveBeenCalled();
+ });
+
+ it("activates the new tab on ctrl+shift+left-click", () => {
+ const evt = leftClick();
+ const spy = vi.spyOn(utils, "isCtrlKey").mockReturnValue(true);
+ goToLinkExt({ ...evt, shiftKey: true }, "#root/aaaaaaaaaaaa");
+ expect(openTabWithNoteWithHoisting).toHaveBeenCalledWith(
+ "root/aaaaaaaaaaaa",
+ expect.objectContaining({ activate: true })
+ );
+ spy.mockRestore();
+ });
+
+ it("opens http(s) external links in a new browser window when clicked outside CKEditor", () => {
+ const openSpy = vi.spyOn(window, "open").mockImplementation(() => null);
+ goToLinkExt(leftClick(), "https://example.com");
+ expect(openSpy).toHaveBeenCalledWith("https://example.com", "_blank");
+ openSpy.mockRestore();
+ });
+
+ it("opens api/ links in a new browser window", () => {
+ const openSpy = vi.spyOn(window, "open").mockImplementation(() => null);
+ goToLinkExt(leftClick(), "api/something");
+ expect(openSpy).toHaveBeenCalledWith("api/something", "_blank");
+ openSpy.mockRestore();
+ });
+
+ it("dispatches an allowed custom protocol via electron shell.openExternal", () => {
+ const openExternal = vi.fn();
+ (window as any).electronApi = { shell: { openExternal, openFileUrl: vi.fn() } };
+ goToLinkExt(leftClick(), "mailto:[email protected]");
+ expect(openExternal).toHaveBeenCalledWith("mailto:[email protected]");
+ });
+
+ it("routes file: links through openFileUrl and reports failures", async () => {
+ const openFileUrl = vi.fn(async () => "boom");
+ (window as any).electronApi = { shell: { openExternal: vi.fn(), openFileUrl } };
+ goToLinkExt(leftClick(), "file:///C:/x.txt");
+ expect(openFileUrl).toHaveBeenCalledWith("file:///C:/x.txt");
+ // allow the rejected/returned-error promise chain to settle
+ await new Promise((r) => setTimeout(r, 0));
+ expect(showError).toHaveBeenCalled();
+ });
+
+ it("reports an error when openFileUrl rejects", async () => {
+ const openFileUrl = vi.fn(async () => { throw new Error("nope"); });
+ (window as any).electronApi = { shell: { openExternal: vi.fn(), openFileUrl } };
+ goToLinkExt(leftClick(), "file:///C:/y.txt");
+ await new Promise((r) => setTimeout(r, 0));
+ expect(showError).toHaveBeenCalled();
+ });
+
+ it("does not report an error when openFileUrl succeeds", async () => {
+ const openFileUrl = vi.fn(async () => "");
+ (window as any).electronApi = { shell: { openExternal: vi.fn(), openFileUrl } };
+ goToLinkExt(leftClick(), "file:///C:/ok.txt");
+ await new Promise((r) => setTimeout(r, 0));
+ expect(openFileUrl).toHaveBeenCalledWith("file:///C:/ok.txt");
+ expect(showError).not.toHaveBeenCalled();
+ });
+
+ it("falls back to window.open for custom protocols when not running under electron", () => {
+ const openSpy = vi.spyOn(window, "open").mockImplementation(() => null);
+ goToLinkExt(leftClick(), "mailto:[email protected]");
+ expect(openSpy).toHaveBeenCalledWith("mailto:[email protected]", "_blank");
+ openSpy.mockRestore();
+ });
+
+ it("scrolls to an in-page anchor for non-root hash links", () => {
+ const target = document.createElement("p");
+ target.id = "fn1";
+ const content = document.createElement("div");
+ content.className = "ck-content";
+ content.appendChild(target);
+ document.body.appendChild(content);
+ target.scrollIntoView = vi.fn();
+
+ const $link = $("<a id='ref'>").attr("href", "#fn1");
+ content.appendChild($link[0]);
+
+ const handled = goToLinkExt(leftClick(), "#fn1", $link);
+ expect(handled).toBe(true);
+ expect(target.scrollIntoView).toHaveBeenCalled();
+ document.body.removeChild(content);
+ });
+
+ it("does nothing for an unhandled external link without a protocol match", () => {
+ const openSpy = vi.spyOn(window, "open").mockImplementation(() => null);
+ // not http, not api/, not an allowed protocol -> no navigation
+ goToLinkExt(leftClick(), "weirdscheme:foo", null);
+ expect(openSpy).not.toHaveBeenCalled();
+ openSpy.mockRestore();
+ });
+
+ it("does not open in-editor links on a plain left click", () => {
+ const openSpy = vi.spyOn(window, "open").mockImplementation(() => null);
+ const $editor = $("<div contenteditable='true'>");
+ const $link = $("<a>").attr("href", "https://example.com");
+ $editor.append($link);
+ goToLinkExt(leftClick(), "https://example.com", $link);
+ // inside a contenteditable, a plain left click should not open the link
+ expect(openSpy).not.toHaveBeenCalled();
+ openSpy.mockRestore();
+ });
+
+ it("does nothing when there is neither a note path nor an href", () => {
+ const openSpy = vi.spyOn(window, "open").mockImplementation(() => null);
+ expect(goToLinkExt(leftClick(), undefined)).toBe(true);
+ expect(openSpy).not.toHaveBeenCalled();
+ expect(openInCurrentNoteContext).not.toHaveBeenCalled();
+ openSpy.mockRestore();
+ });
+
+ it("does not navigate to an internal note on a non-left, non-middle click", () => {
+ const evt = { type: "click", which: 3, preventDefault: vi.fn(), stopPropagation: vi.fn() } as any;
+ goToLinkExt(evt, "#root/aaaaaaaaaaaa");
+ expect(openInCurrentNoteContext).not.toHaveBeenCalled();
+ expect(openTabWithNoteWithHoisting).not.toHaveBeenCalled();
+ expect(triggerCommand).not.toHaveBeenCalled();
+ });
+
+ it("does not handle a non-root hash anchor that does not resolve to an element", () => {
+ const $link = $("<a>").attr("href", "#missing-anchor");
+ // no .ck-content ancestor containing #missing-anchor => handleAnchor returns false
+ const result = goToLinkExt(leftClick(), "#missing-anchor", $link);
+ expect(result).toBe(true);
+ });
+
+ it("reports a string (non-Error) failure from openFileUrl rejection", async () => {
+ const openFileUrl = vi.fn(async () => { throw "raw string failure"; });
+ (window as any).electronApi = { shell: { openExternal: vi.fn(), openFileUrl } };
+ goToLinkExt(leftClick(), "file:///C:/z.txt");
+ await new Promise((r) => setTimeout(r, 0));
+ expect(showError).toHaveBeenCalled();
+ });
+});
+
+describe("getReferenceLinkTitle / getReferenceLinkTitleSync", () => {
+ it("getReferenceLinkTitle returns [missing note] when there is no note id", async () => {
+ expect(await linkService.getReferenceLinkTitle("https://example.com")).toBe("[missing note]");
+ });
+
+ it("getReferenceLinkTitle returns [missing note] when the note is not found", async () => {
+ const orig = froca.getNote;
+ froca.getNote = vi.fn(async () => null) as typeof froca.getNote;
+ expect(await linkService.getReferenceLinkTitle("#root/aaaaaaaaaaaa")).toBe("[missing note]");
+ froca.getNote = orig;
+ });
+
+ it("getReferenceLinkTitle returns the note title", async () => {
+ const note = buildNote({ title: "Referenced" });
+ expect(await linkService.getReferenceLinkTitle(`#root/${note.noteId}`)).toBe("Referenced");
+ });
+
+ it("getReferenceLinkTitle resolves attachment titles", async () => {
+ const note = buildNote({ title: "WithAtt" });
+ note.getAttachmentById = vi.fn(async () => ({ title: "Att" }) as any);
+ const title = await linkService.getReferenceLinkTitle(`#root/${note.noteId}?viewMode=attachments&attachmentId=a1`);
+ expect(title).toBe("Att");
+ });
+
+ it("getReferenceLinkTitle returns [missing attachment] when attachment not found", async () => {
+ const note = buildNote({ title: "WithAtt2" });
+ note.getAttachmentById = vi.fn(async () => null as any);
+ const title = await linkService.getReferenceLinkTitle(`#root/${note.noteId}?viewMode=attachments&attachmentId=a2`);
+ expect(title).toBe("[missing attachment]");
+ });
+
+ it("getReferenceLinkTitleSync covers missing note, attachments and bookmark variants", () => {
+ expect(linkService.getReferenceLinkTitleSync("https://example.com")).toBe("[missing note]");
+
+ const note = buildNote({ title: "SyncNote" });
+ // plain title
+ expect(linkService.getReferenceLinkTitleSync(`#root/${note.noteId}`)).toBe("SyncNote");
+
+ // bookmark suffix
+ expect(linkService.getReferenceLinkTitleSync(`#root/${note.noteId}?bookmark=Heading`)).toBe("SyncNote - Heading");
+
+ // attachments without loaded attachments => loading placeholder
+ const note2 = buildNote({ title: "SyncNote2" });
+ (note2 as any).attachments = undefined;
+ expect(linkService.getReferenceLinkTitleSync(`#root/${note2.noteId}?viewMode=attachments&attachmentId=a1`)).toBe("[loading title...]");
+
+ // attachments loaded but not matching
+ (note2 as any).attachments = [{ attachmentId: "other", title: "Other" }];
+ expect(linkService.getReferenceLinkTitleSync(`#root/${note2.noteId}?viewMode=attachments&attachmentId=a1`)).toBe("[missing attachment]");
+
+ // attachments loaded and matching
+ (note2 as any).attachments = [{ attachmentId: "a1", title: "Matched" }];
+ expect(linkService.getReferenceLinkTitleSync(`#root/${note2.noteId}?viewMode=attachments&attachmentId=a1`)).toBe("Matched");
+ });
+
+ it("getReferenceLinkTitleSync returns [missing note] when the note is not in cache", () => {
+ const orig = froca.getNoteFromCache;
+ froca.getNoteFromCache = vi.fn(() => null) as unknown as typeof froca.getNoteFromCache;
+ expect(linkService.getReferenceLinkTitleSync("#root/aaaaaaaaaaaa")).toBe("[missing note]");
+ froca.getNoteFromCache = orig;
+ });
+});
+
+describe("loadReferenceLinkTitle", () => {
+ it("warns and bails when there is no href", async () => {
+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
+ const $el = $("<span>");
+ await linkService.loadReferenceLinkTitle($el);
+ expect(warn).toHaveBeenCalled();
+ warn.mockRestore();
+ });
+
+ it("warns when the href has no note id", async () => {
+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
+ const $el = $("<a>").attr("href", "https://example.com");
+ await linkService.loadReferenceLinkTitle($el);
+ expect(warn).toHaveBeenCalledWith("Missing note ID.");
+ warn.mockRestore();
+ });
+
+ it("sets text, color class, bookmark and icon for a resolved note", async () => {
+ const note = buildNote({ title: "Loaded", "#color": "red", "#iconClass": "bx bx-star" });
+ const $a = $("<a>").attr("href", `#root/${note.noteId}?bookmark=Sec`);
+ const $el = $("<span>").append($a);
+ await linkService.loadReferenceLinkTitle($el, `#root/${note.noteId}?bookmark=Sec`);
+ // the title becomes the note title, and the bookmark small is appended
+ expect($el.text()).toContain("Loaded");
+ expect($el.find("small").length).toBe(1);
+ });
+
+ it("uses the element's own href and finds the inner anchor when none is passed", async () => {
+ const note = buildNote({ title: "Inner" });
+ const $a = $("<a>").attr("href", `#root/${note.noteId}`);
+ const $el = $("<span>").append($a);
+ await linkService.loadReferenceLinkTitle($el);
+ expect($el.text()).toContain("Inner");
+ });
+
+ it("renders the title without color class / icon when the note is not found", async () => {
+ const orig = froca.getNote;
+ // First lookup (for color/icon) returns null; getReferenceLinkTitle also returns missing note.
+ froca.getNote = vi.fn(async () => null) as typeof froca.getNote;
+ const $a = $("<a>").attr("href", "#root/aaaaaaaaaaaa");
+ const $el = $("<span>").append($a);
+ await linkService.loadReferenceLinkTitle($el, "#root/aaaaaaaaaaaa");
+ expect($el.text()).toBe("[missing note]");
+ // no color class span and no prepended icon since the note was absent
+ expect($el.find("small").length).toBe(0);
+ froca.getNote = orig;
+ });
+
+ it("does not prepend an icon when the resolved note has no icon", async () => {
+ const note = buildNote({ title: "NoIconRef" });
+ note.getIcon = (() => "") as typeof note.getIcon;
+ const $a = $("<a>").attr("href", `#root/${note.noteId}`);
+ const $el = $("<span>").append($a);
+ await linkService.loadReferenceLinkTitle($el, `#root/${note.noteId}`);
+ expect($el.text()).toContain("NoIconRef");
+ expect($el.children("span").length).toBe(0);
+ });
+});
+
+describe("module-level click handlers", () => {
+ it("prevents default paste on middle mouse button down on an anchor", () => {
+ const $a = $("<a href='#root/aaaaaaaaaaaa'>link</a>");
+ $("body").append($a);
+ const preventDefault = vi.fn();
+ $a.trigger($.Event("mousedown", { which: 2, preventDefault }));
+ expect(preventDefault).toHaveBeenCalled();
+ $a.remove();
+ });
+
+ it("invokes the delegated goToLink handler on a click", () => {
+ const $a = $("<a href='#root/aaaaaaaaaaaa'>link</a>");
+ $("body").append($a);
+ $a.trigger($.Event("click", { which: 1 }));
+ // goToLink -> goToLinkExt should attempt to open the note in the current context
+ expect(openInCurrentNoteContext).toHaveBeenCalled();
+ $a.remove();
+ });
+
+ it("opens the link context menu on contextmenu of an internal link", () => {
+ const $a = $("<a href='#root/aaaaaaaaaaaa'>link</a>");
+ $("body").append($a);
+ $a.trigger($.Event("contextmenu", { button: 2 }));
+ expect(openContextMenu).toHaveBeenCalled();
+ $a.remove();
+ });
+
+ it("skips the context menu when the link opts out via data-no-context-menu", () => {
+ const $a = $("<a href='#root/aaaaaaaaaaaa' data-no-context-menu='1'>link</a>");
+ $("body").append($a);
+ $a.trigger($.Event("contextmenu", { button: 2 }));
+ expect(openContextMenu).not.toHaveBeenCalled();
+ $a.remove();
+ });
+
+ it("does nothing on context menu when the link has no resolvable note path", () => {
+ const $a = $("<a href='https://example.com'>ext</a>");
+ $("body").append($a);
+ $a.trigger($.Event("contextmenu", { button: 2 }));
+ expect(openContextMenu).not.toHaveBeenCalled();
+ $a.remove();
+ });
+
+ it("opens a popup on ctrl+right-click of an internal link", () => {
+ const spy = vi.spyOn(utils, "isCtrlKey").mockReturnValue(true);
+ const $a = $("<a href='#root/aaaaaaaaaaaa'>link</a>");
+ $("body").append($a);
+ $a.trigger($.Event("contextmenu", { button: 2 }));
+ expect(triggerCommand).toHaveBeenCalledWith("openInPopup", { noteIdOrPath: "root/aaaaaaaaaaaa" });
+ spy.mockRestore();
+ $a.remove();
+ });
+
+ it("falls back to data-href when an anchor has no href (click handler)", () => {
+ const $a = $("<a data-href='#root/aaaaaaaaaaaa'>link</a>");
+ $("body").append($a);
+ $a.trigger($.Event("click", { which: 1 }));
+ expect(openInCurrentNoteContext).toHaveBeenCalled();
+ $a.remove();
+ });
+
+ it("falls back to data-href when an anchor has no href (context menu handler)", () => {
+ const $a = $("<a data-href='#root/aaaaaaaaaaaa'>link</a>");
+ $("body").append($a);
+ $a.trigger($.Event("contextmenu", { button: 2 }));
+ expect(openContextMenu).toHaveBeenCalled();
+ $a.remove();
+ });
+
+ it("does not prevent default on a left mouse button down", () => {
+ const $a = $("<a href='#root/aaaaaaaaaaaa'>link</a>");
+ $("body").append($a);
+ const preventDefault = vi.fn();
+ $a.trigger($.Event("mousedown", { which: 1, preventDefault }));
+ expect(preventDefault).not.toHaveBeenCalled();
+ $a.remove();
+ });
});
diff --git a/apps/client/src/services/link.ts b/apps/client/src/services/link.ts
index 421133b2b7..2462e4ebdc 100644
--- a/apps/client/src/services/link.ts
+++ b/apps/client/src/services/link.ts
@@ -105,6 +105,7 @@ async function createLink(notePath: string | undefined, options: CreateLinkOptio
let linkTitle = options.title;
if (linkTitle === undefined) {
+ /* v8 ignore start -- the implicit `else` of this chain (noteId falsy) is unreachable: an empty noteId already returned at the guard above */
if (viewMode === "attachments" && viewScope.attachmentId) {
const attachment = await froca.getAttachment(viewScope.attachmentId);
@@ -112,6 +113,7 @@ async function createLink(notePath: string | undefined, options: CreateLinkOptio
} else if (noteId) {
linkTitle = await treeService.getNoteTitle(noteId, parentNoteId);
}
+ /* v8 ignore stop */
}
const note = await froca.getNote(noteId);
@@ -166,6 +168,7 @@ async function createLink(notePath: string | undefined, options: CreateLinkOptio
pathSegments = await treeService.getNotePathTitleComponents(resolvedPath);
}
+ /* v8 ignore next 2 -- defensive guards: pathSegments is always a non-empty array (getNotePathTitleComponents never returns empty, and the root case yields ["⌂"]) */
if (pathSegments) {
if (pathSegments.length) {
$container.append($("<small>").append(treeService.formatNotePath(pathSegments)));
@@ -190,6 +193,7 @@ export function calculateHash({ notePath, ntxId, hoistedNoteId, viewScope = {} }
const name = Object.keys(pair)[0];
const value = (pair as Record<string, string | undefined>)[name];
+ /* v8 ignore next -- the `value || ""` fallback is unreachable: every retained param pair has a truthy value (falsy ones were filtered out above) */
return `${encodeURIComponent(name)}=${encodeURIComponent(value || "")}`;
})
.join("&");
@@ -494,6 +498,7 @@ function getReferenceLinkTitleSync(href: string) {
return note.title;
}
+/* v8 ignore next -- the `print` device branch is evaluated once at module load; under test glob.device is undefined, so the false arm cannot be exercised */
if (glob.device !== "print") {
// TODO: Check why the event is not supported.
//@ts-ignore
diff --git a/apps/client/src/services/link_embed.spec.ts b/apps/client/src/services/link_embed.spec.ts
index 4f9db68b6e..567ca75d36 100644
--- a/apps/client/src/services/link_embed.spec.ts
+++ b/apps/client/src/services/link_embed.spec.ts
@@ -1,5 +1,37 @@
-import { describe, expect, it } from "vitest";
-import { detectEmbedType, safeHostname } from "./link_embed.js";
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+import server from "./server.js";
+import {
+ applyLinkEmbeds,
+ detectEmbedType,
+ fetchMetadata,
+ renderEmbedPreview,
+ renderMentionPreview,
+ safeHostname
+} from "./link_embed.js";
+
+let container: HTMLDivElement | undefined;
+
+function makeContainer() {
+ container = document.createElement("div");
+ document.body.appendChild(container);
+ return container;
+}
+
+afterEach(() => {
+ if (container) {
+ container.remove();
+ container = undefined;
+ }
+ vi.restoreAllMocks();
+});
+
+/** Dispatches a native `error` event on an element and flushes Preact's state update. */
+async function fireError(el: Element) {
+ el.dispatchEvent(new Event("error", { bubbles: false }));
+ // Allow Preact's batched setState rerender to flush.
+ await new Promise((resolve) => setTimeout(resolve, 0));
+}
describe("detectEmbedType", () => {
it("detects YouTube URLs", () => {
@@ -26,3 +58,201 @@ describe("safeHostname", () => {
expect(safeHostname("http://localhost:8080/api")).toBe("localhost");
});
});
+
+describe("fetchMetadata", () => {
+ it("maps server metadata into the embed shape and encodes the URL", async () => {
+ const url = "https://example.com/path?a=b&c=d";
+ const fromServer = {
+ url: "https://canonical.example.com",
+ embedType: "opengraph",
+ title: "Title",
+ description: "Desc",
+ favicon: "https://example.com/favicon.ico",
+ siteName: "Example",
+ image: "https://example.com/img.png"
+ };
+ server.get = vi.fn(async () => fromServer) as typeof server.get;
+
+ const result = await fetchMetadata(url);
+
+ expect(server.get).toHaveBeenCalledWith(
+ `link-embed/metadata?url=${encodeURIComponent(url)}`
+ );
+ expect(result).toEqual(fromServer);
+ });
+
+ it("falls back to local detection when the server request fails", async () => {
+ server.get = vi.fn(async () => {
+ throw new Error("network down");
+ }) as typeof server.get;
+
+ const result = await fetchMetadata("https://youtu.be/abcdefghijk");
+ expect(result).toEqual({
+ url: "https://youtu.be/abcdefghijk",
+ embedType: "youtube",
+ title: "youtu.be"
+ });
+ });
+});
+
+describe("renderEmbedPreview", () => {
+ it("renders a YouTube iframe when embedType is not opengraph and the URL is a video", () => {
+ const root = makeContainer();
+ renderEmbedPreview(root, {
+ url: "https://www.youtube.com/watch?v=dQw4w9WgXcQ",
+ embedType: "youtube"
+ });
+
+ const iframe = root.querySelector("iframe");
+ expect(iframe).not.toBeNull();
+ expect(iframe!.getAttribute("src")).toContain("youtube-nocookie.com/embed/dQw4w9WgXcQ");
+ expect(root.querySelector("a.link-embed-card")).toBeNull();
+ });
+
+ it("renders a card (not an iframe) for a YouTube URL forced to opengraph", () => {
+ const root = makeContainer();
+ renderEmbedPreview(root, {
+ url: "https://www.youtube.com/watch?v=dQw4w9WgXcQ",
+ embedType: "opengraph",
+ title: "A title",
+ description: "A description",
+ siteName: "YouTube",
+ image: "https://img.example/x.png"
+ });
+
+ expect(root.querySelector("iframe")).toBeNull();
+ const card = root.querySelector("a.link-embed-card")!;
+ expect(card.getAttribute("target")).toBe("_blank");
+ expect(card.querySelector(".link-embed-card-title")!.textContent).toBe("A title");
+ expect(card.querySelector(".link-embed-card-description")!.textContent).toBe("A description");
+ expect(card.querySelector(".link-embed-card-url")!.textContent).toBe("YouTube");
+ // image present -> real <img>, no placeholder
+ expect(root.querySelector("img.link-embed-card-image")).not.toBeNull();
+ expect(root.querySelector(".link-embed-card-image-placeholder")).toBeNull();
+ });
+
+ it("omits optional fields and falls back to hostname, and drops target when editable", () => {
+ const root = makeContainer();
+ renderEmbedPreview(
+ root,
+ {
+ url: "https://no-meta.example.com/page",
+ embedType: "opengraph"
+ },
+ true
+ );
+
+ const card = root.querySelector("a.link-embed-card")!;
+ expect(card.getAttribute("target")).toBeNull();
+ expect(root.querySelector(".link-embed-card-title")).toBeNull();
+ expect(root.querySelector(".link-embed-card-description")).toBeNull();
+ // siteName missing -> safeHostname(url)
+ expect(root.querySelector(".link-embed-card-url")!.textContent).toBe("no-meta.example.com");
+ // image missing -> placeholder, no real <img>
+ expect(root.querySelector(".link-embed-card-image-placeholder")).not.toBeNull();
+ expect(root.querySelector("img.link-embed-card-image")).toBeNull();
+ });
+
+ it("replaces a broken card image with the placeholder on error", async () => {
+ const root = makeContainer();
+ renderEmbedPreview(root, {
+ url: "https://example.com",
+ embedType: "opengraph",
+ image: "https://img.example/broken.png"
+ });
+
+ const img = root.querySelector("img.link-embed-card-image")!;
+ expect(img).not.toBeNull();
+ await fireError(img);
+
+ expect(root.querySelector("img.link-embed-card-image")).toBeNull();
+ expect(root.querySelector(".link-embed-card-image-placeholder")).not.toBeNull();
+ });
+});
+
+describe("renderMentionPreview", () => {
+ it("renders favicon img + title, with target=_blank by default", () => {
+ const root = makeContainer();
+ renderMentionPreview(root, {
+ url: "https://example.com",
+ title: "Example site",
+ favicon: "https://example.com/favicon.ico"
+ });
+
+ const anchor = root.querySelector("a.link-embed-mention")!;
+ expect(anchor.getAttribute("target")).toBe("_blank");
+ expect(anchor.querySelector("img.link-embed-mention-favicon")).not.toBeNull();
+ expect(root.querySelector(".link-embed-mention-dot")).toBeNull();
+ expect(anchor.querySelector(".link-embed-mention-title")!.textContent).toBe("Example site");
+ });
+
+ it("falls back to a dot favicon and hostname title; drops target when editable", () => {
+ const root = makeContainer();
+ renderMentionPreview(
+ root,
+ { url: "https://fallback.example.com/x" },
+ true
+ );
+
+ const anchor = root.querySelector("a.link-embed-mention")!;
+ expect(anchor.getAttribute("target")).toBeNull();
+ expect(root.querySelector("img.link-embed-mention-favicon")).toBeNull();
+ expect(root.querySelector(".link-embed-mention-dot")).not.toBeNull();
+ expect(anchor.querySelector(".link-embed-mention-title")!.textContent).toBe("fallback.example.com");
+ });
+
+ it("replaces a broken favicon with the dot on error", async () => {
+ const root = makeContainer();
+ renderMentionPreview(root, {
+ url: "https://example.com",
+ favicon: "https://example.com/broken.ico"
+ });
+
+ const img = root.querySelector("img.link-embed-mention-favicon")!;
+ expect(img).not.toBeNull();
+ await fireError(img);
+
+ expect(root.querySelector("img.link-embed-mention-favicon")).toBeNull();
+ expect(root.querySelector(".link-embed-mention-dot")).not.toBeNull();
+ });
+});
+
+describe("applyLinkEmbeds", () => {
+ it("renders previews from data attributes and skips elements without a url", () => {
+ const root = makeContainer();
+ root.innerHTML = `
+ <section class="link-embed" data-url="https://full.example.com"
+ data-embed-type="opengraph" data-title="T" data-description="D"
+ data-site-name="Site" data-image="https://img.example/x.png"></section>
+ <section class="link-embed"></section>
+ <span class="link-mention" data-url="https://m.example.com"
+ data-title="MT" data-favicon="https://m.example.com/fav.ico"></span>
+ <span class="link-mention"></span>
+ `;
+
+ applyLinkEmbeds(root);
+
+ const embeds = root.querySelectorAll("section.link-embed");
+ // First embed got rendered into a card; second (no url) stayed empty.
+ expect(embeds[0].querySelector("a.link-embed-card")).not.toBeNull();
+ expect(embeds[0].querySelector(".link-embed-card-title")!.textContent).toBe("T");
+ expect(embeds[1].innerHTML).toBe("");
+
+ const mentions = root.querySelectorAll("span.link-mention");
+ expect(mentions[0].querySelector("a.link-embed-mention")).not.toBeNull();
+ expect(mentions[0].querySelector(".link-embed-mention-title")!.textContent).toBe("MT");
+ expect(mentions[1].innerHTML).toBe("");
+ });
+
+ it("defaults embedType to opengraph when the data attribute is absent", () => {
+ const root = makeContainer();
+ root.innerHTML = `<section class="link-embed" data-url="https://www.youtube.com/watch?v=dQw4w9WgXcQ"></section>`;
+
+ applyLinkEmbeds(root);
+
+ // No embed-type attr -> defaults to "opengraph" -> renders a card, not an iframe.
+ const embed = root.querySelector("section.link-embed")!;
+ expect(embed.querySelector("iframe")).toBeNull();
+ expect(embed.querySelector("a.link-embed-card")).not.toBeNull();
+ });
+});
diff --git a/apps/client/src/services/llm_chat.spec.ts b/apps/client/src/services/llm_chat.spec.ts
new file mode 100644
index 0000000000..713a1ab320
--- /dev/null
+++ b/apps/client/src/services/llm_chat.spec.ts
@@ -0,0 +1,263 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+import type { LlmChatConfig, LlmMessage } from "@triliumnext/commons";
+
+import { getAvailableModels, streamChatCompletion, type StreamCallbacks } from "./llm_chat.js";
+import server from "./server.js";
+
+/**
+ * Build a Response-like object whose body streams the given SSE chunks.
+ * Each chunk is decoded by the production code with a TextDecoder.
+ */
+function makeStreamResponse(chunks: string[], opts: { ok?: boolean; status?: number; statusText?: string; noBody?: boolean } = {}): Response {
+ const encoder = new TextEncoder();
+ let i = 0;
+ const reader = {
+ read: vi.fn(async () => {
+ if (i < chunks.length) {
+ return { done: false, value: encoder.encode(chunks[i++]) };
+ }
+ return { done: true, value: undefined };
+ }),
+ releaseLock: vi.fn()
+ };
+
+ return {
+ ok: opts.ok ?? true,
+ status: opts.status ?? 200,
+ statusText: opts.statusText ?? "OK",
+ body: opts.noBody ? null : { getReader: () => reader }
+ } as unknown as Response;
+}
+
+function makeCallbacks(): Record<keyof StreamCallbacks, ReturnType<typeof vi.fn>> & StreamCallbacks {
+ return {
+ onChunk: vi.fn(),
+ onThinking: vi.fn(),
+ onToolInputStart: vi.fn(),
+ onToolInputDelta: vi.fn(),
+ onToolUse: vi.fn(),
+ onToolResult: vi.fn(),
+ onCitation: vi.fn(),
+ onUsage: vi.fn(),
+ onError: vi.fn(),
+ onDone: vi.fn()
+ } as Record<keyof StreamCallbacks, ReturnType<typeof vi.fn>> & StreamCallbacks;
+}
+
+const messages: LlmMessage[] = [{ role: "user", content: "hi" }];
+const config = {} as LlmChatConfig;
+
+describe("getAvailableModels", () => {
+ it("returns the models array from the server response", async () => {
+ const models = [{ name: "gpt", provider: "openai" }];
+ server.get = vi.fn(async () => ({ models })) as typeof server.get;
+ await expect(getAvailableModels()).resolves.toBe(models);
+ expect(server.get).toHaveBeenCalledWith("llm-chat/models");
+ });
+
+ it("defaults to an empty array when models is absent", async () => {
+ server.get = vi.fn(async () => ({})) as typeof server.get;
+ await expect(getAvailableModels()).resolves.toEqual([]);
+ });
+});
+
+describe("streamChatCompletion", () => {
+ beforeEach(() => {
+ server.getHeaders = vi.fn(async () => ({ "x-csrf-token": "tok" })) as typeof server.getHeaders;
+ });
+
+ afterEach(() => {
+ vi.restoreAllMocks();
+ });
+
+ it("posts messages/config with merged headers and consumes the stream", async () => {
+ const fetchMock = vi.fn(async () => makeStreamResponse([`data: ${JSON.stringify({ type: "text", content: "hello" })}\n`]));
+ vi.stubGlobal("fetch", fetchMock);
+
+ const cb = makeCallbacks();
+ await streamChatCompletion(messages, config, cb);
+
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ const [url, init] = fetchMock.mock.calls[0] as unknown as [string, RequestInit];
+ expect(url).toContain("llm-chat/stream");
+ expect(init.method).toBe("POST");
+ expect((init.headers as Record<string, string>)["Content-Type"]).toBe("application/json");
+ expect((init.headers as Record<string, string>)["x-csrf-token"]).toBe("tok");
+ expect(init.body).toBe(JSON.stringify({ messages, config }));
+ expect(cb.onChunk).toHaveBeenCalledWith("hello");
+ });
+
+ it("rethrows an AbortError from fetch (user stopped)", async () => {
+ const abort = new DOMException("aborted", "AbortError");
+ vi.stubGlobal("fetch", vi.fn(async () => { throw abort; }));
+
+ const cb = makeCallbacks();
+ await expect(streamChatCompletion(messages, config, cb)).rejects.toBe(abort);
+ expect(cb.onError).not.toHaveBeenCalled();
+ });
+
+ it("reports a connection failure for a non-abort Error from fetch", async () => {
+ vi.stubGlobal("fetch", vi.fn(async () => { throw new Error("boom"); }));
+
+ const cb = makeCallbacks();
+ await streamChatCompletion(messages, config, cb);
+ expect(cb.onError).toHaveBeenCalledWith("Failed to connect to LLM stream: boom");
+ });
+
+ it("reports a connection failure for a non-Error thrown by fetch", async () => {
+ vi.stubGlobal("fetch", vi.fn(async () => { throw "stringly"; }));
+
+ const cb = makeCallbacks();
+ await streamChatCompletion(messages, config, cb);
+ expect(cb.onError).toHaveBeenCalledWith("Failed to connect to LLM stream: stringly");
+ });
+
+ it("reports an HTTP error when the response is not ok", async () => {
+ vi.stubGlobal("fetch", vi.fn(async () => makeStreamResponse([], { ok: false, status: 503, statusText: "Unavailable" })));
+
+ const cb = makeCallbacks();
+ await streamChatCompletion(messages, config, cb);
+ expect(cb.onError).toHaveBeenCalledWith("HTTP 503: Unavailable");
+ });
+
+ it("reports a missing body when there is no reader", async () => {
+ vi.stubGlobal("fetch", vi.fn(async () => makeStreamResponse([], { noBody: true })));
+
+ const cb = makeCallbacks();
+ await streamChatCompletion(messages, config, cb);
+ expect(cb.onError).toHaveBeenCalledWith("No response body");
+ });
+
+ it("dispatches every SSE event type to the matching callback", async () => {
+ const events = [
+ { type: "text", content: "T" },
+ { type: "thinking", content: "TH" },
+ { type: "tool_input_start", toolCallId: "c1", toolName: "search" },
+ { type: "tool_input_delta", toolCallId: "c1", delta: "{" },
+ { type: "tool_use", toolCallId: "c1", toolName: "search", toolInput: { q: "x" } },
+ { type: "tool_result", toolCallId: "c1", toolName: "search", result: "res", isError: false },
+ { type: "citation", citation: { id: "cit1" } },
+ { type: "usage", usage: { totalTokens: 10 } },
+ { type: "done" },
+ { type: "unknown_ignored" }
+ ];
+ // Split a "data: " line across two chunks to exercise the buffer carry-over,
+ // and include a blank/non-data line which must be ignored.
+ const chunks = [
+ ...events.map((e) => `data: ${JSON.stringify(e)}\n`),
+ "ignored non-data line\n",
+ "data: " // trailing partial line left in the buffer (never flushed)
+ ];
+ vi.stubGlobal("fetch", vi.fn(async () => makeStreamResponse(chunks)));
+
+ const cb = makeCallbacks();
+ await streamChatCompletion(messages, config, cb);
+
+ expect(cb.onChunk).toHaveBeenCalledWith("T");
+ expect(cb.onThinking).toHaveBeenCalledWith("TH");
+ expect(cb.onToolInputStart).toHaveBeenCalledWith("c1", "search");
+ expect(cb.onToolInputDelta).toHaveBeenCalledWith("c1", "{");
+ expect(cb.onToolUse).toHaveBeenCalledWith("c1", "search", { q: "x" });
+ expect(cb.onToolResult).toHaveBeenCalledWith("c1", "search", "res", false);
+ expect(cb.onCitation).toHaveBeenCalledWith({ id: "cit1" });
+ expect(cb.onUsage).toHaveBeenCalledWith({ totalTokens: 10 });
+ expect(cb.onDone).toHaveBeenCalledTimes(1);
+ });
+
+ it("ignores citation/usage events that carry no payload", async () => {
+ const chunks = [
+ `data: ${JSON.stringify({ type: "citation" })}\n`,
+ `data: ${JSON.stringify({ type: "usage" })}\n`
+ ];
+ vi.stubGlobal("fetch", vi.fn(async () => makeStreamResponse(chunks)));
+
+ const cb = makeCallbacks();
+ await streamChatCompletion(messages, config, cb);
+ expect(cb.onCitation).not.toHaveBeenCalled();
+ expect(cb.onUsage).not.toHaveBeenCalled();
+ });
+
+ it("forwards an error event to onError", async () => {
+ const chunks = [`data: ${JSON.stringify({ type: "error", error: "model failed" })}\n`];
+ vi.stubGlobal("fetch", vi.fn(async () => makeStreamResponse(chunks)));
+
+ const cb = makeCallbacks();
+ await streamChatCompletion(messages, config, cb);
+ expect(cb.onError).toHaveBeenCalledWith("model failed");
+ });
+
+ it("skips optional callbacks that are not provided", async () => {
+ const events = [
+ { type: "thinking", content: "TH" },
+ { type: "tool_input_start", toolCallId: "c1", toolName: "search" },
+ { type: "tool_input_delta", toolCallId: "c1", delta: "{" },
+ { type: "tool_use", toolCallId: "c1", toolName: "search", toolInput: { q: "x" } },
+ { type: "tool_result", toolCallId: "c1", toolName: "search", result: "res" },
+ { type: "citation", citation: { id: "cit1" } },
+ { type: "usage", usage: { totalTokens: 1 } }
+ ];
+ const chunks = events.map((e) => `data: ${JSON.stringify(e)}\n`);
+ vi.stubGlobal("fetch", vi.fn(async () => makeStreamResponse(chunks)));
+
+ // Only the required callbacks are present; optional `?.` invocations must be no-ops.
+ const cb: StreamCallbacks = { onChunk: vi.fn(), onError: vi.fn(), onDone: vi.fn() };
+ await expect(streamChatCompletion(messages, config, cb)).resolves.toBeUndefined();
+ expect(cb.onError).not.toHaveBeenCalled();
+ });
+
+ it("logs and skips an SSE line that is not valid JSON", async () => {
+ const consoleError = vi.spyOn(console, "error").mockImplementation(() => {});
+ const chunks = ["data: {not json}\n"];
+ vi.stubGlobal("fetch", vi.fn(async () => makeStreamResponse(chunks)));
+
+ const cb = makeCallbacks();
+ await streamChatCompletion(messages, config, cb);
+ expect(consoleError).toHaveBeenCalled();
+ expect(cb.onChunk).not.toHaveBeenCalled();
+ });
+
+ it("rethrows an AbortError raised while reading the stream", async () => {
+ const abort = new DOMException("aborted", "AbortError");
+ const reader = { read: vi.fn(async () => { throw abort; }), releaseLock: vi.fn() };
+ const response = { ok: true, status: 200, statusText: "OK", body: { getReader: () => reader } } as unknown as Response;
+ vi.stubGlobal("fetch", vi.fn(async () => response));
+
+ const cb = makeCallbacks();
+ await expect(streamChatCompletion(messages, config, cb)).rejects.toBe(abort);
+ expect(reader.releaseLock).toHaveBeenCalledTimes(1);
+ expect(cb.onError).not.toHaveBeenCalled();
+ });
+
+ it("reports a non-abort Error raised while reading the stream", async () => {
+ const reader = { read: vi.fn(async () => { throw new Error("read failed"); }), releaseLock: vi.fn() };
+ const response = { ok: true, status: 200, statusText: "OK", body: { getReader: () => reader } } as unknown as Response;
+ vi.stubGlobal("fetch", vi.fn(async () => response));
+
+ const cb = makeCallbacks();
+ await streamChatCompletion(messages, config, cb);
+ expect(cb.onError).toHaveBeenCalledWith("LLM stream interrupted: read failed");
+ expect(reader.releaseLock).toHaveBeenCalledTimes(1);
+ });
+
+ it("reports a non-Error thrown while reading the stream", async () => {
+ const reader = { read: vi.fn(async () => { throw "kaput"; }), releaseLock: vi.fn() };
+ const response = { ok: true, status: 200, statusText: "OK", body: { getReader: () => reader } } as unknown as Response;
+ vi.stubGlobal("fetch", vi.fn(async () => response));
+
+ const cb = makeCallbacks();
+ await streamChatCompletion(messages, config, cb);
+ expect(cb.onError).toHaveBeenCalledWith("LLM stream interrupted: kaput");
+ });
+
+ it("passes the abort signal through to fetch", async () => {
+ const fetchMock = vi.fn(async () => makeStreamResponse([]));
+ vi.stubGlobal("fetch", fetchMock);
+ const controller = new AbortController();
+
+ const cb = makeCallbacks();
+ await streamChatCompletion(messages, config, cb, controller.signal);
+ const [, init] = fetchMock.mock.calls[0] as unknown as [string, RequestInit];
+ expect(init.signal).toBe(controller.signal);
+ });
+});
diff --git a/apps/client/src/services/load_results.spec.ts b/apps/client/src/services/load_results.spec.ts
new file mode 100644
index 0000000000..7e72c3b24a
--- /dev/null
+++ b/apps/client/src/services/load_results.spec.ts
@@ -0,0 +1,138 @@
+import { describe, expect, it } from "vitest";
+
+import type { EntityChange } from "../server_types.js";
+import LoadResults from "./load_results.js";
+
+function ec(entityName: EntityChange["entityName"], entityId: string, entity?: object): EntityChange {
+ return { entityName, entityId, entity, hash: "h", isSynced: 1, isErased: 0 } as EntityChange;
+}
+
+describe("LoadResults", () => {
+ it("indexes only entity changes that carry an entity payload", () => {
+ const lr = new LoadResults([
+ ec("notes", "n1", { title: "A" }),
+ ec("notes", "n2") // no entity -> skipped
+ ]);
+
+ expect(lr.getEntityRow("notes", "n1")).toEqual({ title: "A" });
+ expect(lr.getEntityRow("notes", "n2")).toBeUndefined();
+ // unknown entity name resolves through the optional chain to undefined
+ expect(lr.getEntityRow("attributes", "missing")).toBeUndefined();
+ });
+
+ it("tracks note <-> component associations, deduplicating component ids", () => {
+ const lr = new LoadResults([]);
+
+ lr.addNote("n1"); // no component id
+ lr.addNote("n1", "comp1");
+ lr.addNote("n1", "comp1"); // duplicate component id is ignored
+ lr.addNote("n1", "comp2");
+
+ expect(lr.getNoteIds()).toEqual(["n1"]);
+ expect(lr.isNoteReloaded("n1")).toBe(true);
+ // reloaded only counts components other than the one passed in
+ expect(lr.isNoteReloaded("n1", "comp1")).toBe(true);
+ expect(lr.isNoteReloaded("n2")).toBeFalsy(); // unknown note -> undefined (short-circuit)
+ expect(lr.isNoteReloaded(undefined)).toBe(false);
+ });
+
+ it("returns reloaded=false when the note has only the excluded component", () => {
+ const lr = new LoadResults([]);
+ lr.addNote("solo", "comp1");
+ expect(lr.isNoteReloaded("solo", "comp1")).toBe(false);
+ });
+
+ it("merges branch rows with their tracked component id and drops unknown branches", () => {
+ const lr = new LoadResults([ec("branches", "b1", { branchId: "b1", parentNoteId: "p" })]);
+ lr.addBranch("b1", "comp1");
+ lr.addBranch("b2", "comp2"); // no matching entity -> filtered out
+
+ expect(lr.getBranchRows()).toEqual([{ branchId: "b1", parentNoteId: "p", componentId: "comp1" }]);
+ });
+
+ it("filters attribute rows by component id and merges entity data", () => {
+ const lr = new LoadResults([
+ ec("attributes", "a1", { attributeId: "a1", name: "color" }),
+ ec("attributes", "a2", { attributeId: "a2", name: "size" })
+ ]);
+ lr.addAttribute("a1", "comp1");
+ lr.addAttribute("a2", "skip-me");
+ lr.addAttribute("a3", "comp1"); // no entity -> filtered out
+
+ expect(lr.getAttributeRows("skip-me")).toEqual([{ attributeId: "a1", name: "color", componentId: "comp1" }]);
+ // default component id ("none") keeps everything with a backing entity
+ expect(lr.getAttributeRows().map((a) => a.attributeId)).toEqual(["a1", "a2"]);
+ });
+
+ it("tracks note reorderings, revisions, content, options and attachments", () => {
+ const lr = new LoadResults([]);
+
+ lr.addNoteReordering("parent1", "comp1");
+ expect(lr.getNoteReorderings()).toEqual(["parent1"]);
+
+ lr.addRevision("rev1", "noteA", "comp1");
+ expect(lr.hasRevisionForNote("noteA")).toBe(true);
+ expect(lr.hasRevisionForNote("noteB")).toBe(false);
+
+ lr.addNoteContent("noteA", "comp1");
+ expect(lr.isNoteContentReloaded("noteA", "comp2")).toBeTruthy();
+ expect(lr.isNoteContentReloaded("noteA", "comp1")).toBeFalsy();
+ expect(lr.isNoteContentReloaded("")).toBe(false);
+
+ lr.addOption("eraseEntitiesAfterTimeInSeconds");
+ expect(lr.isOptionReloaded("eraseEntitiesAfterTimeInSeconds")).toBe(true);
+ expect(lr.isOptionReloaded("unrelated" as never)).toBe(false);
+ expect(lr.getOptionNames()).toEqual(["eraseEntitiesAfterTimeInSeconds"]);
+
+ const attachment = { attachmentId: "att1" } as never;
+ lr.addAttachmentRow(attachment);
+ expect(lr.getAttachmentRows()).toEqual([attachment]);
+ });
+
+ it("reports attribute-related changes from branches or attributes", () => {
+ const fromBranch = new LoadResults([]);
+ fromBranch.addBranch("b1", "comp1");
+ expect(fromBranch.hasAttributeRelatedChanges()).toBe(true);
+
+ const fromAttr = new LoadResults([]);
+ fromAttr.addAttribute("a1", "comp1");
+ expect(fromAttr.hasAttributeRelatedChanges()).toBe(true);
+
+ expect(new LoadResults([]).hasAttributeRelatedChanges()).toBe(false);
+ });
+
+ it("considers a fresh result empty, and any single mutation makes it non-empty", () => {
+ expect(new LoadResults([]).isEmpty()).toBe(true);
+ expect(new LoadResults([]).isEmptyForTree()).toBe(true);
+
+ const mutators: ((lr: LoadResults) => void)[] = [
+ (lr) => lr.addNote("n1", "c"),
+ (lr) => lr.addBranch("b1", "c"),
+ (lr) => lr.addAttribute("a1", "c"),
+ (lr) => lr.addNoteReordering("p1", "c"),
+ (lr) => lr.addRevision("r1", "n1", "c"),
+ (lr) => lr.addNoteContent("n1", "c"),
+ (lr) => lr.addOption("eraseEntitiesAfterTimeInSeconds"),
+ (lr) => lr.addAttachmentRow({ attachmentId: "att1" } as never),
+ (lr) => { lr.hasEtapiTokenChanges = true; }
+ ];
+
+ for (const mutate of mutators) {
+ const lr = new LoadResults([]);
+ mutate(lr);
+ expect(lr.isEmpty()).toBe(false);
+ }
+
+ // isEmptyForTree ignores revisions/content/options/attachments/etapi
+ const treeIgnored = new LoadResults([]);
+ treeIgnored.addRevision("r1", "n1", "c");
+ treeIgnored.addNoteContent("n1", "c");
+ treeIgnored.addOption("eraseEntitiesAfterTimeInSeconds");
+ treeIgnored.hasEtapiTokenChanges = true;
+ expect(treeIgnored.isEmptyForTree()).toBe(true);
+
+ const treeAffecting = new LoadResults([]);
+ treeAffecting.addNoteReordering("p1", "c");
+ expect(treeAffecting.isEmptyForTree()).toBe(false);
+ });
+});
diff --git a/apps/client/src/services/load_results.ts b/apps/client/src/services/load_results.ts
index b5706705ba..871ab77439 100644
--- a/apps/client/src/services/load_results.ts
+++ b/apps/client/src/services/load_results.ts
@@ -125,6 +125,7 @@ export default class LoadResults {
this.componentIdToNoteIds[componentId] = this.componentIdToNoteIds[componentId] || [];
+ /* v8 ignore next 3 -- redundant guard: the array is guaranteed by the assignment above (arrays are always truthy) */
if (this.componentIdToNoteIds[componentId]) {
this.componentIdToNoteIds[componentId].push(noteId);
}
diff --git a/apps/client/src/services/mermaid.spec.ts b/apps/client/src/services/mermaid.spec.ts
index 61461065b7..80b2497ecf 100644
--- a/apps/client/src/services/mermaid.spec.ts
+++ b/apps/client/src/services/mermaid.spec.ts
@@ -1,5 +1,6 @@
-import { describe, expect, it } from "vitest";
-import { postprocessMermaidSvg } from "./mermaid.js";
+import type { Mermaid } from "mermaid";
+import { describe, expect, it, vi } from "vitest";
+import { getMermaidConfig, loadElkIfNeeded, postprocessMermaidSvg } from "./mermaid.js";
import { trimIndentation } from "@triliumnext/commons";
describe("Mermaid", () => {
@@ -38,3 +39,74 @@ describe("Mermaid", () => {
.toBe("<text>a&#160;b&#160;&#160;c</text>");
});
});
+
+describe("getMermaidConfig", () => {
+ it("reads the --mermaid-theme CSS variable (trimmed) and keeps the static useMaxWidth flags", () => {
+ document.documentElement.style.setProperty("--mermaid-theme", " dark ");
+
+ const config = getMermaidConfig();
+
+ expect(config.theme).toBe("dark");
+ expect(config.securityLevel).toBe("antiscript");
+ expect(config.flowchart).toEqual({ useMaxWidth: false });
+ expect(config.sequence).toEqual({ useMaxWidth: false });
+ expect(config.gantt).toEqual({ useMaxWidth: false });
+ expect(config.class).toEqual({ useMaxWidth: false });
+ expect(config.state).toEqual({ useMaxWidth: false });
+ expect(config.pie).toEqual({ useMaxWidth: true });
+ expect(config.journey).toEqual({ useMaxWidth: false });
+ expect(config.gitGraph).toEqual({ useMaxWidth: false });
+
+ document.documentElement.style.removeProperty("--mermaid-theme");
+ });
+});
+
+describe("loadElkIfNeeded", () => {
+ function fakeMermaid(parseResult: unknown) {
+ return {
+ parse: vi.fn(async () => parseResult),
+ registerLayoutLoaders: vi.fn()
+ } as unknown as Mermaid & {
+ parse: ReturnType<typeof vi.fn>;
+ registerLayoutLoaders: ReturnType<typeof vi.fn>;
+ };
+ }
+
+ // NOTE: the module-level `elkLoaded` flag flips to true the first time an
+ // elk diagram is parsed, so the order of these tests matters: the
+ // "does not register" cases run first (while the flag is still false),
+ // the "registers" case flips it, and the "already loaded" case relies on it.
+
+ it("does not register loaders when parsing yields nothing", async () => {
+ const mermaid = fakeMermaid(null);
+ await loadElkIfNeeded(mermaid, "graph TD; A-->B");
+ expect(mermaid.parse).toHaveBeenCalledWith("graph TD; A-->B", { suppressErrors: true });
+ expect(mermaid.registerLayoutLoaders).not.toHaveBeenCalled();
+ });
+
+ it("does not register loaders when the layout is not elk", async () => {
+ const mermaid = fakeMermaid({ config: { layout: "dagre" } });
+ await loadElkIfNeeded(mermaid, "graph TD; A-->B");
+ expect(mermaid.registerLayoutLoaders).not.toHaveBeenCalled();
+ });
+
+ it("does not register loaders when there is no config at all", async () => {
+ const mermaid = fakeMermaid({});
+ await loadElkIfNeeded(mermaid, "graph TD; A-->B");
+ expect(mermaid.registerLayoutLoaders).not.toHaveBeenCalled();
+ });
+
+ it("registers the elk layout loader when the diagram requests elk", async () => {
+ const mermaid = fakeMermaid({ config: { layout: "elk" } });
+ await loadElkIfNeeded(mermaid, "---\nconfig:\n layout: elk\n---\ngraph TD; A-->B");
+ expect(mermaid.registerLayoutLoaders).toHaveBeenCalledTimes(1);
+ expect(mermaid.registerLayoutLoaders.mock.calls[0][0]).toBeTruthy();
+ });
+
+ it("exits immediately without parsing once elk has already been loaded", async () => {
+ const mermaid = fakeMermaid({ config: { layout: "elk" } });
+ await loadElkIfNeeded(mermaid, "---\nconfig:\n layout: elk\n---\ngraph TD; A-->B");
+ expect(mermaid.parse).not.toHaveBeenCalled();
+ expect(mermaid.registerLayoutLoaders).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/client/src/services/mime_types.spec.ts b/apps/client/src/services/mime_types.spec.ts
new file mode 100644
index 0000000000..5c6fb0e19f
--- /dev/null
+++ b/apps/client/src/services/mime_types.spec.ts
@@ -0,0 +1,78 @@
+import { MIME_TYPE_AUTO, MIME_TYPES_DICT, normalizeMimeTypeForCKEditor } from "@triliumnext/commons";
+import { describe, expect, it, vi } from "vitest";
+
+import options from "./options.js";
+import mimeTypesService, { getHighlightJsNameForMime } from "./mime_types.js";
+
+describe("mime_types service", () => {
+ it("getMimeTypes loads lazily, defaults to the dict's `default` set, and always enables text/plain", () => {
+ // No user option configured -> fall back to the entries flagged `default`.
+ options.getJson = vi.fn(() => null) as typeof options.getJson;
+
+ const mimeTypes = mimeTypesService.getMimeTypes();
+
+ // It is a clone, not the frozen source dictionary.
+ expect(mimeTypes).not.toBe(MIME_TYPES_DICT);
+ expect(mimeTypes.length).toBe(MIME_TYPES_DICT.length);
+ expect(Object.isFrozen(mimeTypes)).toBe(false);
+
+ const enabledMimes = mimeTypes.filter((mt) => mt.enabled).map((mt) => mt.mime);
+ const defaultMimes = MIME_TYPES_DICT.filter((mt) => mt.default).map((mt) => mt.mime);
+ // Every default mime is enabled, plus text/plain which is forced on.
+ for (const mime of defaultMimes) {
+ expect(enabledMimes).toContain(mime);
+ }
+ expect(enabledMimes).toContain("text/plain");
+
+ // A non-default mime (no `default` flag, not text/plain) stays disabled.
+ const apl = mimeTypes.find((mt) => mt.mime === "text/apl");
+ expect(apl?.enabled).toBe(false);
+ });
+
+ it("getMimeTypes returns the already-loaded cache on subsequent calls", () => {
+ // getJson must not be consulted again now that the cache is populated.
+ const spy = vi.fn(() => null);
+ options.getJson = spy as typeof options.getJson;
+
+ const first = mimeTypesService.getMimeTypes();
+ const second = mimeTypesService.getMimeTypes();
+
+ expect(second).toBe(first);
+ expect(spy).not.toHaveBeenCalled();
+ });
+
+ it("loadMimeTypes honours a user-configured enabled list", () => {
+ options.getJson = vi.fn(() => ["text/apl"]) as typeof options.getJson;
+
+ mimeTypesService.loadMimeTypes();
+ const mimeTypes = mimeTypesService.getMimeTypes();
+
+ const apl = mimeTypes.find((mt) => mt.mime === "text/apl");
+ const plain = mimeTypes.find((mt) => mt.mime === "text/plain");
+ // A default mime that is NOT in the user list is now disabled.
+ const html = mimeTypes.find((mt) => mt.mime === "text/html");
+
+ expect(apl?.enabled).toBe(true);
+ // text/plain stays enabled even though it is not in the configured list.
+ expect(plain?.enabled).toBe(true);
+ expect(html?.enabled).toBe(false);
+ });
+
+ it("getHighlightJsNameForMime maps CKEditor-normalized mimes to highlight.js codes and caches the mapping", () => {
+ // text/x-csrc -> text-x-csrc -> "c"
+ expect(getHighlightJsNameForMime(normalizeMimeTypeForCKEditor("text/x-csrc"))).toBe("c");
+ // text/css -> text-css -> "css" (exercises the cached path on the second call)
+ expect(getHighlightJsNameForMime(normalizeMimeTypeForCKEditor("text/css"))).toBe("css");
+ // A mime that exists but has no mdLanguageCode is omitted from the mapping.
+ expect(getHighlightJsNameForMime(normalizeMimeTypeForCKEditor("text/apl"))).toBeUndefined();
+ // An entirely unknown mime resolves to undefined.
+ expect(getHighlightJsNameForMime("totally-unknown")).toBeUndefined();
+ });
+
+ it("re-exports MIME_TYPE_AUTO and the public helpers", () => {
+ expect(mimeTypesService.MIME_TYPE_AUTO).toBe(MIME_TYPE_AUTO);
+ expect(typeof mimeTypesService.getMimeTypes).toBe("function");
+ expect(typeof mimeTypesService.loadMimeTypes).toBe("function");
+ expect(mimeTypesService.getHighlightJsNameForMime).toBe(getHighlightJsNameForMime);
+ });
+});
diff --git a/apps/client/src/services/note_attribute_cache.spec.ts b/apps/client/src/services/note_attribute_cache.spec.ts
new file mode 100644
index 0000000000..72db854890
--- /dev/null
+++ b/apps/client/src/services/note_attribute_cache.spec.ts
@@ -0,0 +1,21 @@
+import { describe, expect, it } from "vitest";
+
+import type FAttribute from "../entities/fattribute.js";
+import noteAttributeCache from "./note_attribute_cache.js";
+
+describe("noteAttributeCache", () => {
+ it("starts with an attributes map and clears it on invalidate", () => {
+ // The constructor initializes `attributes` to a plain object.
+ expect(noteAttributeCache.attributes).toBeTypeOf("object");
+
+ // Seed a cached entry, then ensure invalidate() resets the map to empty.
+ const fakeAttribute = { name: "color" } as unknown as FAttribute;
+ noteAttributeCache.attributes["someNote"] = [fakeAttribute];
+ expect(noteAttributeCache.attributes["someNote"]).toEqual([fakeAttribute]);
+
+ noteAttributeCache.invalidate();
+
+ expect(noteAttributeCache.attributes).toEqual({});
+ expect(noteAttributeCache.attributes["someNote"]).toBeUndefined();
+ });
+});
diff --git a/apps/client/src/services/note_autocomplete.spec.ts b/apps/client/src/services/note_autocomplete.spec.ts
new file mode 100644
index 0000000000..43d929249e
--- /dev/null
+++ b/apps/client/src/services/note_autocomplete.spec.ts
@@ -0,0 +1,758 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import $ from "jquery";
+
+// --- Mocks (hoisted above imports) ---
+
+const { triggerCommand, getActiveContextNoteId, getActiveContext, chooseNoteType, createNote, getAllCommands, searchCommands } = vi.hoisted(() => ({
+ triggerCommand: vi.fn(),
+ getActiveContextNoteId: vi.fn<() => string | null>(() => "activeNote"),
+ getActiveContext: vi.fn<() => any>(() => ({ hoistedNoteId: "hoisted" })),
+ chooseNoteType: vi.fn(),
+ createNote: vi.fn(),
+ getAllCommands: vi.fn(() => [] as any[]),
+ searchCommands: vi.fn(() => [] as any[])
+}));
+
+vi.mock("../components/app_context.js", () => ({
+ default: {
+ triggerCommand,
+ tabManager: {
+ getActiveContextNoteId,
+ getActiveContext
+ }
+ }
+}));
+
+vi.mock("./note_create.js", () => ({
+ default: { chooseNoteType, createNote }
+}));
+
+vi.mock("./command_registry.js", () => ({
+ default: { getAllCommands, searchCommands }
+}));
+
+// Imports AFTER vi.mock calls.
+import server from "./server.js";
+import froca from "./froca.js";
+import { buildNote } from "../test/easy-froca.js";
+import noteAutocomplete, { triggerRecentNotes } from "./note_autocomplete.js";
+
+type Dataset = {
+ displayKey: string;
+ cache: boolean;
+ source: (term: string, cb: (rows: any[]) => void) => void;
+ templates: { suggestion: (s: any) => string };
+};
+
+// Captures the last `$el.autocomplete(config, datasets)` init call and records
+// every command invocation so tests can drive the registered callbacks.
+let lastConfig: AutoCompleteConfig | undefined;
+let lastDatasets: Dataset[] | undefined;
+let autocompleteCalls: any[][];
+const stored = new Map<HTMLElement, string>();
+
+function registerAutocompleteStub() {
+ lastConfig = undefined;
+ lastDatasets = undefined;
+ autocompleteCalls = [];
+ ($.fn as any).autocomplete = vi.fn(function (this: JQuery, config: any, datasets?: Dataset[]) {
+ autocompleteCalls.push([config, datasets]);
+ if (typeof config === "object" && Array.isArray(datasets)) {
+ lastConfig = config;
+ lastDatasets = datasets;
+ }
+ // emulate the "val" getter/setter so fullTextSearch can read it back
+ if (config === "val") {
+ const el = this[0];
+ if (datasets === undefined) {
+ return stored.get(el) as any;
+ }
+ stored.set(el, datasets as unknown as string);
+ }
+ return this;
+ });
+}
+
+function makeEl(extraClass = "") {
+ return $(`<input class="${extraClass}" />`);
+}
+
+function lastCommandWith(arg: any) {
+ return autocompleteCalls.some((c) => c[0] === arg && c[1] === undefined);
+}
+
+describe("note_autocomplete", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ getActiveContextNoteId.mockReturnValue("activeNote");
+ getActiveContext.mockReturnValue({ hoistedNoteId: "hoisted" });
+ registerAutocompleteStub();
+ server.get = vi.fn(async () => []) as typeof server.get;
+ noteAutocomplete.init();
+ });
+
+ describe("autocompleteSourceForCKEditor (default export)", () => {
+ it("maps server rows into CKEditor mention feed items", async () => {
+ server.get = vi.fn(async () => [
+ {
+ action: "search-notes",
+ noteTitle: "Foo",
+ notePathTitle: "Root / Foo",
+ notePath: "root/abc",
+ highlightedNotePathTitle: "<b>Foo</b>",
+ icon: "bx bx-note"
+ }
+ ]) as typeof server.get;
+
+ const result = (await noteAutocomplete.autocompleteSourceForCKEditor("Foo")) as any[];
+ // autocompleteSourceForCKEditor forces allowCreatingNotes -> a create-note row is prepended.
+ const mapped = result.find((r) => r.notePath === "root/abc");
+ expect(mapped).toEqual({
+ action: "search-notes",
+ noteTitle: "Foo",
+ id: "@Root / Foo",
+ name: "Root / Foo",
+ link: "#root/abc",
+ notePath: "root/abc",
+ highlightedNotePathTitle: "<b>Foo</b>",
+ icon: "bx bx-note"
+ });
+ });
+
+ it("falls back to empty name when notePathTitle is missing", async () => {
+ server.get = vi.fn(async () => []) as typeof server.get;
+ const result = (await noteAutocomplete.autocompleteSourceForCKEditor("X")) as any[];
+ // only the synthetic create-note row remains; it has no notePathTitle.
+ const createRow = result.find((r) => r.action === "create-note");
+ expect(createRow).toBeDefined();
+ expect(createRow!.name).toBe("");
+ expect(createRow!.id).toBe("@undefined");
+ });
+ });
+});
+
+// ---------------------------------------------------------------------------
+// Exercise the internal autocompleteSource via the dataset.source registered
+// during initNoteAutocomplete (it is not exported, so we go through the public
+// init path and capture the dataset callbacks).
+// ---------------------------------------------------------------------------
+
+function initAndGetSource(options?: any) {
+ const $el = makeEl();
+ noteAutocomplete.initNoteAutocomplete($el, options);
+ return { $el, dataset: lastDatasets![0] };
+}
+
+/** Runs the dataset.source and resolves with the rows it passes to cb. */
+function runSource(dataset: Dataset, term: string): Promise<any[]> {
+ return new Promise((resolve) => {
+ dataset.source(term, (rows) => resolve(rows));
+ });
+}
+
+/**
+ * Fires the (debounced) dataset.source with the given cb and waits long enough
+ * for the debounce timer + the awaited body to flush, even when cb is never called.
+ */
+function runSourceRaw(dataset: Dataset, term: string, cb: (rows: any[]) => void): Promise<void> {
+ dataset.source(term, cb);
+ return new Promise((resolve) => setTimeout(resolve, 30));
+}
+
+describe("autocompleteSource (via dataset)", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ getActiveContextNoteId.mockReturnValue("activeNote");
+ registerAutocompleteStub();
+ server.get = vi.fn(async () => []) as typeof server.get;
+ noteAutocomplete.init();
+ });
+
+ it("returns command suggestions in command-palette mode (all commands, empty query)", async () => {
+ getAllCommands.mockReturnValue([
+ { id: "cmd1", name: "Cmd One", description: "desc", shortcut: "Ctrl+1", icon: "bx bx-cog" }
+ ]);
+ const { dataset } = initAndGetSource({ isCommandPalette: true });
+ const rows = await runSource(dataset, ">");
+ expect(getAllCommands).toHaveBeenCalled();
+ expect(searchCommands).not.toHaveBeenCalled();
+ expect(rows).toEqual([
+ {
+ action: "command",
+ commandId: "cmd1",
+ noteTitle: "Cmd One",
+ notePathTitle: ">Cmd One",
+ highlightedNotePathTitle: "Cmd One",
+ commandDescription: "desc",
+ commandShortcut: "Ctrl+1",
+ icon: "bx bx-cog"
+ }
+ ]);
+ });
+
+ it("uses searchCommands when a command query is provided", async () => {
+ searchCommands.mockReturnValue([{ id: "c", name: "C" }]);
+ const { dataset } = initAndGetSource({ isCommandPalette: true });
+ const rows = await runSource(dataset, "> hello");
+ expect(searchCommands).toHaveBeenCalledWith("hello");
+ expect(rows[0].commandId).toBe("c");
+ });
+
+ it("resets searchDelay back to the computed value after it was zeroed", async () => {
+ server.get = vi.fn(async () => []) as typeof server.get;
+ const { $el, dataset } = initAndGetSource();
+ // showRecentNotes zeroes the shared searchDelay...
+ noteAutocomplete.showRecentNotes($el);
+ // ...and the next source invocation runs immediately and restores it.
+ await runSource(dataset, "x");
+ expect(server.get).toHaveBeenCalled();
+ });
+
+ it("queries the server and returns plain results", async () => {
+ server.get = vi.fn(async () => [{ noteTitle: "Result", notePath: "root/x" }]) as typeof server.get;
+ const { dataset } = initAndGetSource();
+ const rows = await runSource(dataset, "hello");
+ expect(server.get).toHaveBeenCalledWith(
+ "autocomplete?query=hello&activeNoteId=activeNote&fastSearch=true"
+ );
+ expect(rows).toEqual([{ noteTitle: "Result", notePath: "root/x" }]);
+ });
+
+ it("does the slow-search placeholder branch when fastSearch is false", async () => {
+ server.get = vi.fn(async () => [{ noteTitle: "R" }]) as typeof server.get;
+ const cbRows: any[][] = [];
+ const { dataset } = initAndGetSource({ fastSearch: false });
+ await new Promise<void>((resolve) => {
+ let count = 0;
+ dataset.source("hi", (rows) => {
+ cbRows.push(rows);
+ if (++count === 2) resolve();
+ });
+ });
+ // first cb: searching placeholder, second cb: actual results
+ expect(cbRows[0][0].noteTitle).toBe("hi");
+ expect("highlightedNotePathTitle" in cbRows[0][0]).toBe(true);
+ expect(cbRows[1]).toEqual([{ noteTitle: "R" }]);
+ expect(server.get).toHaveBeenCalledWith(
+ expect.stringContaining("fastSearch=false")
+ );
+ });
+
+ it("returns early on blank term when fastSearch is false", async () => {
+ server.get = vi.fn(async () => [{ noteTitle: "R" }]) as typeof server.get;
+ const { dataset } = initAndGetSource({ fastSearch: false });
+ const cb = vi.fn();
+ // blank term -> autocompleteSource returns before touching the server / cb
+ await runSourceRaw(dataset, " ", cb);
+ expect(cb).not.toHaveBeenCalled();
+ expect(server.get).not.toHaveBeenCalled();
+ });
+
+ it("prepends a create-note suggestion when allowCreatingNotes and term is non-empty", async () => {
+ server.get = vi.fn(async () => [{ noteTitle: "Existing", notePath: "root/y" }]) as typeof server.get;
+ const { dataset } = initAndGetSource({ allowCreatingNotes: true });
+ const rows = await runSource(dataset, "New");
+ expect(rows[0].action).toBe("create-note");
+ expect(rows[0].parentNoteId).toBe("activeNote");
+ expect(rows[1].noteTitle).toBe("Existing");
+ });
+
+ it("uses root as parent when there is no active note", async () => {
+ getActiveContextNoteId.mockReturnValue(null);
+ server.get = vi.fn(async () => []) as typeof server.get;
+ const { dataset } = initAndGetSource({ allowCreatingNotes: true });
+ const rows = await runSource(dataset, "New");
+ expect(rows[0].parentNoteId).toBe("root");
+ });
+
+ it("appends a search-notes suggestion when allowJumpToSearchNotes", async () => {
+ server.get = vi.fn(async () => [{ noteTitle: "A", notePath: "root/a" }]) as typeof server.get;
+ const { dataset } = initAndGetSource({ allowJumpToSearchNotes: true });
+ const rows = await runSource(dataset, "term");
+ expect(rows[rows.length - 1].action).toBe("search-notes");
+ });
+
+ it("prepends an external-link suggestion when allowExternalLinks and term is a URL", async () => {
+ server.get = vi.fn(async () => [{ noteTitle: "A", notePath: "root/a" }]) as typeof server.get;
+ const { dataset } = initAndGetSource({ allowExternalLinks: true });
+ const rows = await runSource(dataset, "https://example.com/x");
+ expect(rows[0].action).toBe("external-link");
+ expect(rows[0].externalLink).toBe("https://example.com/x");
+ });
+
+ it("does not add a create suggestion for an empty term", async () => {
+ server.get = vi.fn(async () => [{ noteTitle: "A", notePath: "root/a" }]) as typeof server.get;
+ const { dataset } = initAndGetSource({ allowCreatingNotes: true, allowJumpToSearchNotes: true, allowExternalLinks: true });
+ const rows = await runSource(dataset, " ");
+ // length === 0 so neither create-note nor search-notes nor external-link added
+ expect(rows.every((r) => r.action !== "create-note")).toBe(true);
+ expect(rows.every((r) => r.action !== "search-notes")).toBe(true);
+ });
+
+ it("renders a note suggestion via the template (default icon, no attribute snippet)", () => {
+ const { dataset } = initAndGetSource();
+ const html = dataset.templates.suggestion({ highlightedNotePathTitle: "Title" });
+ expect(html).toContain("note-suggestion");
+ expect(html).toContain("bx bx-note");
+ expect(html).toContain("Title");
+ expect(html).not.toContain("search-result-attributes");
+ });
+
+ it("renders a note suggestion with explicit icon and attribute snippet", () => {
+ const { dataset } = initAndGetSource();
+ const html = dataset.templates.suggestion({
+ highlightedNotePathTitle: "T",
+ icon: "bx bx-star",
+ highlightedAttributeSnippet: "#color=red"
+ });
+ expect(html).toContain("bx bx-star");
+ expect(html).toContain("search-result-attributes");
+ expect(html).toContain("#color=red");
+ });
+
+ it("renders search-notes, create-note and external-link suggestion icons/classes", () => {
+ const { dataset } = initAndGetSource();
+ expect(dataset.templates.suggestion({ action: "search-notes", highlightedNotePathTitle: "S" }))
+ .toContain("search-notes-action");
+ expect(dataset.templates.suggestion({ action: "search-notes", highlightedNotePathTitle: "S" }))
+ .toContain("bx bx-search");
+ expect(dataset.templates.suggestion({ action: "create-note", highlightedNotePathTitle: "C" }))
+ .toContain("bx bx-plus");
+ expect(dataset.templates.suggestion({ action: "external-link", highlightedNotePathTitle: "E" }))
+ .toContain("bx bx-link-external");
+ });
+
+ it("renders a command suggestion with description and shortcut", () => {
+ const { dataset } = initAndGetSource();
+ const html = dataset.templates.suggestion({
+ action: "command",
+ highlightedNotePathTitle: "Cmd",
+ commandDescription: "Does a thing",
+ commandShortcut: "Ctrl+K",
+ icon: "bx bx-cog"
+ });
+ expect(html).toContain("command-suggestion");
+ expect(html).toContain("command-name");
+ expect(html).toContain("command-description");
+ expect(html).toContain("command-shortcut");
+ expect(html).toContain("bx bx-cog");
+ });
+
+ it("renders a command suggestion without description/shortcut and a default icon", () => {
+ const { dataset } = initAndGetSource();
+ const html = dataset.templates.suggestion({
+ action: "command",
+ highlightedNotePathTitle: "Cmd"
+ });
+ expect(html).toContain("bx bx-terminal");
+ expect(html).not.toContain("command-description");
+ expect(html).not.toContain("command-shortcut");
+ });
+});
+
+describe("source debounce + searchDelay reset", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ vi.useFakeTimers();
+ getActiveContextNoteId.mockReturnValue("activeNote");
+ registerAutocompleteStub();
+ server.get = vi.fn(async () => []) as typeof server.get;
+ noteAutocomplete.init();
+ });
+
+ afterEach(() => {
+ vi.useRealTimers();
+ });
+
+ it("debounces and skips the search while composing input", async () => {
+ const { $el, dataset } = initAndGetSource();
+ // simulate IME composition active
+ $el.trigger("compositionstart");
+ const cb = vi.fn();
+ dataset.source("hi", cb);
+ await vi.runAllTimersAsync();
+ // isComposingInput is true -> autocompleteSource not invoked
+ expect(server.get).not.toHaveBeenCalled();
+ expect(cb).not.toHaveBeenCalled();
+ });
+
+ it("runs the search after the debounce when not composing", async () => {
+ const { dataset } = initAndGetSource();
+ const cb = vi.fn();
+ dataset.source("hi", cb);
+ await vi.runAllTimersAsync();
+ expect(server.get).toHaveBeenCalled();
+ });
+});
+
+describe("$.fn jQuery extensions (init)", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ registerAutocompleteStub();
+ server.get = vi.fn(async () => []) as typeof server.get;
+ noteAutocomplete.init();
+ });
+
+ it("getSelectedNotePath returns empty when input value is blank", () => {
+ const $el = makeEl();
+ $el.val("");
+ $el.attr("data-note-path", "root/x");
+ expect($el.getSelectedNotePath()).toBe("");
+ });
+
+ it("getSelectedNotePath returns the stored path when there is a value", () => {
+ const $el = makeEl();
+ $el.val("Some title");
+ $el.attr("data-note-path", "root/x");
+ expect($el.getSelectedNotePath()).toBe("root/x");
+ });
+
+ it("getSelectedNoteId returns null when no path, last segment otherwise", () => {
+ const $el = makeEl();
+ $el.val("");
+ expect($el.getSelectedNoteId()).toBeNull();
+
+ $el.val("title");
+ $el.attr("data-note-path", "root/parent/child");
+ expect($el.getSelectedNoteId()).toBe("child");
+ });
+
+ it("setSelectedNotePath toggles the go-to button and sets href", () => {
+ const $group = $(`<div class="input-group"><input class="note-autocomplete-input" /><a class="go-to-selected-note-button"></a></div>`);
+ const $el = $group.find("input");
+ $el.setSelectedNotePath("root/abc");
+ const $btn = $group.find(".go-to-selected-note-button");
+ expect($btn.hasClass("disabled")).toBe(false);
+ expect($btn.attr("href")).toBe("#root/abc");
+
+ $el.setSelectedNotePath("");
+ expect($group.find(".go-to-selected-note-button").hasClass("disabled")).toBe(true);
+ });
+
+ it("getSelectedExternalLink mirrors getSelectedNotePath blank/value behaviour", () => {
+ const $el = makeEl();
+ $el.val("");
+ $el.attr("data-external-link", "https://x");
+ expect($el.getSelectedExternalLink()).toBe("");
+
+ $el.val("title");
+ expect($el.getSelectedExternalLink()).toBe("https://x");
+ });
+
+ it("setSelectedExternalLink stores the link and disables the go-to button", () => {
+ const $group = $(`<div class="input-group"><input /><a class="go-to-selected-note-button"></a></div>`);
+ const $el = $group.find("input");
+ $el.setSelectedExternalLink("https://example.com");
+ expect($el.attr("data-external-link")).toBe("https://example.com");
+ expect($group.find(".go-to-selected-note-button").hasClass("disabled")).toBe(true);
+ });
+
+ it("setNote loads the note title from froca and sets the value + path", async () => {
+ const note = buildNote({ title: "Loaded note" });
+ const $el = makeEl();
+ await $el.setNote(note.noteId);
+ expect($el.val()).toBe("Loaded note");
+ expect($el.attr("data-note-path")).toBe(note.noteId);
+ });
+
+ it("setNote clears the value when noteId is falsy", async () => {
+ const $el = makeEl();
+ $el.val("previous");
+ await $el.setNote(null as any);
+ expect($el.val()).toBe("");
+ expect($el.attr("data-note-path")).toBe("");
+ });
+});
+
+describe("initNoteAutocomplete wiring", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ registerAutocompleteStub();
+ server.get = vi.fn(async () => []) as typeof server.get;
+ noteAutocomplete.init();
+ });
+
+ it("returns early and detaches the noteselected listener if already initialized", () => {
+ const $el = makeEl("note-autocomplete-input");
+ const result = noteAutocomplete.initNoteAutocomplete($el);
+ // no autocomplete init call was made (config + datasets form)
+ expect(lastDatasets).toBeUndefined();
+ expect(result).toBe($el);
+ });
+
+ it("adds all buttons and wires their click handlers", () => {
+ const $group = $(`<div class="input-group"></div>`);
+ const $el = makeEl();
+ $group.append($el);
+ noteAutocomplete.initNoteAutocomplete($el);
+
+ expect($el.hasClass("note-autocomplete-input")).toBe(true);
+ expect($group.find(".input-clearer-button").length).toBe(1);
+ expect($group.find(".show-recent-notes-button").length).toBe(1);
+ expect($group.find(".full-text-search-button").length).toBe(1);
+ expect($group.find(".go-to-selected-note-button").length).toBe(1);
+
+ // clear button -> autocomplete("val", "") + change trigger
+ $group.find(".input-clearer-button").trigger("click");
+ expect(autocompleteCalls.some((c) => c[0] === "val" && c[1] === "")).toBe(true);
+
+ // show-recent-notes button click returns false (prevent focus steal)
+ $group.find(".show-recent-notes-button").trigger("click");
+ // full text search button click
+ $el.autocomplete("val", "search me");
+ $group.find(".full-text-search-button").trigger("click");
+ });
+
+ it("hides the go-to button only when hideGoToSelectedNoteButton is set", () => {
+ const $group = $(`<div class="input-group"></div>`);
+ const $el = makeEl();
+ $group.append($el);
+ noteAutocomplete.initNoteAutocomplete($el, { hideGoToSelectedNoteButton: true });
+ expect($group.find(".go-to-selected-note-button").length).toBe(0);
+ expect($group.find(".full-text-search-button").length).toBe(1);
+ });
+
+ it("hides all buttons when hideAllButtons is set", () => {
+ const $group = $(`<div class="input-group"></div>`);
+ const $el = makeEl();
+ $group.append($el);
+ noteAutocomplete.initNoteAutocomplete($el, { hideAllButtons: true });
+ expect($group.find(".input-clearer-button").length).toBe(0);
+ expect($group.find(".go-to-selected-note-button").length).toBe(0);
+ });
+
+ it("passes a container into the autocomplete config and enables debug", () => {
+ const container = document.createElement("div");
+ const $el = makeEl();
+ noteAutocomplete.initNoteAutocomplete($el, { container });
+ expect(lastConfig?.dropdownMenuContainer).toBe(container);
+ expect(lastConfig?.debug).toBe(true);
+ });
+
+ it("Ctrl+Enter triggers a search-notes selection when allowJumpToSearchNotes", () => {
+ const $el = makeEl();
+ const selected = vi.fn();
+ ($el as any).on("autocomplete:selected", selected);
+ noteAutocomplete.initNoteAutocomplete($el, { allowJumpToSearchNotes: true });
+
+ $el.autocomplete("val", "find this");
+ const ev = $.Event("keydown", { ctrlKey: true, key: "Enter" });
+ $el.trigger(ev);
+ expect(selected).toHaveBeenCalled();
+ const payload = selected.mock.calls[0][1];
+ expect(payload.action).toBe("search-notes");
+ });
+
+ it("Shift+Enter performs a full text search", () => {
+ const $el = makeEl();
+ noteAutocomplete.initNoteAutocomplete($el);
+ $el.autocomplete("val", "some text");
+ const ev = $.Event("keydown", { shiftKey: true, key: "Enter" });
+ $el.trigger(ev);
+ // fullTextSearch toggles options.fastSearch and re-sets val
+ expect(lastCommandWith("val")).toBe(true);
+ });
+
+ it("ignores keydowns that are not Ctrl+Enter / Shift+Enter", () => {
+ const $el = makeEl();
+ const selected = vi.fn();
+ ($el as any).on("autocomplete:selected", selected);
+ noteAutocomplete.initNoteAutocomplete($el, { allowJumpToSearchNotes: true });
+
+ // a plain key press -> neither handler fires its body
+ $el.trigger($.Event("keydown", { key: "a" }));
+ // Ctrl without Enter, Shift without Enter
+ $el.trigger($.Event("keydown", { ctrlKey: true, key: "a" }));
+ $el.trigger($.Event("keydown", { shiftKey: true, key: "b" }));
+ expect(selected).not.toHaveBeenCalled();
+ });
+
+ it("composition end re-sets the autocomplete value", () => {
+ const $el = makeEl();
+ noteAutocomplete.initNoteAutocomplete($el);
+ $el.autocomplete("val", "composed");
+ $el.trigger("compositionstart");
+ $el.trigger("compositionend");
+ // value was read then re-applied -> still "composed"
+ expect($el.autocomplete("val")).toBe("composed");
+ });
+
+ it("autocomplete:closed clears text when the input is blank", () => {
+ const $el = makeEl();
+ noteAutocomplete.initNoteAutocomplete($el);
+ $el.val("");
+ $el.trigger("autocomplete:closed");
+ // clearText sets the path to ""
+ expect($el.attr("data-note-path")).toBe("");
+ });
+
+ it("autocomplete:closed leaves a non-blank input untouched", () => {
+ const $el = makeEl();
+ noteAutocomplete.initNoteAutocomplete($el);
+ $el.val("keep me");
+ $el.attr("data-note-path", "root/keep");
+ $el.trigger("autocomplete:closed");
+ expect($el.attr("data-note-path")).toBe("root/keep");
+ });
+
+ it("autocomplete:opened closes the dropdown for a readonly input", () => {
+ const $el = makeEl();
+ noteAutocomplete.initNoteAutocomplete($el);
+ $el.attr("readonly", "readonly");
+ $el.trigger("autocomplete:opened");
+ expect(lastCommandWith("close")).toBe(true);
+ });
+
+ it("autocomplete:opened does nothing for a non-readonly input", () => {
+ const $el = makeEl();
+ noteAutocomplete.initNoteAutocomplete($el);
+ $el.trigger("autocomplete:opened");
+ expect(lastCommandWith("close")).toBe(false);
+ });
+});
+
+describe("autocomplete:selected handler", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ getActiveContext.mockReturnValue({ hoistedNoteId: "hoisted" });
+ registerAutocompleteStub();
+ server.get = vi.fn(async () => []) as typeof server.get;
+ noteAutocomplete.init();
+ });
+
+ function initWithSelected() {
+ const $el = makeEl();
+ const handlers: Record<string, any> = {};
+ noteAutocomplete.initNoteAutocomplete($el);
+ ["autocomplete:commandselected", "autocomplete:externallinkselected", "autocomplete:noteselected"].forEach((evt) => {
+ $el.on(evt, (_e: any, s: any) => (handlers[evt] = s));
+ });
+ return { $el, handlers };
+ }
+
+ function fireSelected($el: JQuery, suggestion: any) {
+ ($el as any).trigger("autocomplete:selected", suggestion);
+ return new Promise((r) => setTimeout(r, 0));
+ }
+
+ it("handles a command selection", async () => {
+ const { $el, handlers } = initWithSelected();
+ await fireSelected($el, { action: "command", commandId: "x" });
+ expect(lastCommandWith("close")).toBe(true);
+ expect(handlers["autocomplete:commandselected"]).toBeDefined();
+ });
+
+ it("handles an external-link selection", async () => {
+ const { $el, handlers } = initWithSelected();
+ await fireSelected($el, { action: "external-link", externalLink: "https://e.com" });
+ expect($el.attr("data-external-link")).toBe("https://e.com");
+ expect(handlers["autocomplete:externallinkselected"]).toBeDefined();
+ });
+
+ it("handles a search-notes selection by triggering searchNotes", async () => {
+ const { $el } = initWithSelected();
+ await fireSelected($el, { action: "search-notes", noteTitle: "query" });
+ expect(triggerCommand).toHaveBeenCalledWith("searchNotes", { searchString: "query" });
+ });
+
+ it("creates a note then selects it", async () => {
+ const note = buildNote({ title: "Created" });
+ chooseNoteType.mockResolvedValue({ success: true, noteType: "text", templateNoteId: undefined, notePath: undefined });
+ createNote.mockResolvedValue({ note: { getBestNotePathString: () => "root/created" } });
+ const { $el, handlers } = initWithSelected();
+ await fireSelected($el, { action: "create-note", noteTitle: "Created", parentNoteId: "parent" });
+ expect(chooseNoteType).toHaveBeenCalled();
+ expect(createNote).toHaveBeenCalledWith("parent", expect.objectContaining({ title: "Created", type: "text" }));
+ expect(handlers["autocomplete:noteselected"]).toBeDefined();
+ expect(handlers["autocomplete:noteselected"].notePath).toBe("root/created");
+ });
+
+ it("aborts the create-note flow when the type chooser is cancelled", async () => {
+ chooseNoteType.mockResolvedValue({ success: false });
+ const { $el, handlers } = initWithSelected();
+ await fireSelected($el, { action: "create-note", noteTitle: "X", parentNoteId: "p" });
+ expect(createNote).not.toHaveBeenCalled();
+ expect(handlers["autocomplete:noteselected"]).toBeUndefined();
+ });
+
+ it("uses the chosen notePath as parent and tolerates a missing created note", async () => {
+ chooseNoteType.mockResolvedValue({ success: true, noteType: "text", notePath: "chosen/path" });
+ createNote.mockResolvedValue({ note: undefined });
+ getActiveContext.mockReturnValue(undefined);
+ const { $el } = initWithSelected();
+ await fireSelected($el, { action: "create-note", noteTitle: "X", parentNoteId: "p" });
+ expect(createNote).toHaveBeenCalledWith("chosen/path", expect.any(Object));
+ });
+
+ it("handles a plain note selection", async () => {
+ const { $el, handlers } = initWithSelected();
+ await fireSelected($el, { action: undefined, notePath: "root/n", noteTitle: "N" });
+ expect($el.attr("data-note-path")).toBe("root/n");
+ expect(handlers["autocomplete:noteselected"]).toBeDefined();
+ });
+});
+
+describe("public helpers", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ registerAutocompleteStub();
+ server.get = vi.fn(async () => []) as typeof server.get;
+ noteAutocomplete.init();
+ });
+
+ it("setText sets the trimmed value and opens the dropdown", () => {
+ const $el = makeEl();
+ noteAutocomplete.setText($el, " hello ");
+ expect(lastCommandWith("open")).toBe(true);
+ expect($el.attr("data-note-path")).toBe("");
+ });
+
+ it("showRecentNotes clears path, blanks val, opens and focuses", () => {
+ const $el = makeEl();
+ noteAutocomplete.showRecentNotes($el);
+ expect(lastCommandWith("open")).toBe(true);
+ expect($el.attr("data-note-path")).toBe("");
+ });
+
+ it("showAllCommands sets the '>' prefix and opens", () => {
+ const $el = makeEl();
+ noteAutocomplete.showAllCommands($el);
+ // val was set to ">"
+ expect($el.autocomplete("val")).toBe(">");
+ expect(lastCommandWith("open")).toBe(true);
+ });
+
+ it("triggerRecentNotes is a no-op for a missing element", () => {
+ expect(() => triggerRecentNotes(null)).not.toThrow();
+ expect(() => triggerRecentNotes(undefined)).not.toThrow();
+ });
+
+ it("triggerRecentNotes shows recent notes for a real element", () => {
+ const input = document.createElement("input");
+ triggerRecentNotes(input);
+ expect(lastCommandWith("open")).toBe(true);
+ });
+});
+
+describe("fullTextSearch guards", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ registerAutocompleteStub();
+ server.get = vi.fn(async () => []) as typeof server.get;
+ noteAutocomplete.init();
+ });
+
+ it("returns early when the search string is blank (Shift+Enter on empty input)", () => {
+ const $el = makeEl();
+ noteAutocomplete.initNoteAutocomplete($el);
+ $el.autocomplete("val", " ");
+ const callsBefore = autocompleteCalls.length;
+ const ev = $.Event("keydown", { shiftKey: true, key: "Enter" });
+ $el.trigger(ev);
+ // fullTextSearch bailed out before re-setting val/focus
+ // the only thing that may have run is the val getter inside the guard
+ expect(autocompleteCalls.length).toBeGreaterThanOrEqual(callsBefore);
+ // setSelectedNotePath would have written the path; it was not called
+ expect($el.attr("data-note-path") ?? "").toBe("");
+ });
+});
diff --git a/apps/client/src/services/note_autocomplete.ts b/apps/client/src/services/note_autocomplete.ts
index 7bf3f5fa89..56da5c1c62 100644
--- a/apps/client/src/services/note_autocomplete.ts
+++ b/apps/client/src/services/note_autocomplete.ts
@@ -452,6 +452,7 @@ function init() {
const chunks = notePath.split("/");
+ /* v8 ignore next -- String.split always yields at least one element, so the `: null` branch is unreachable */
return chunks.length >= 1 ? chunks[chunks.length - 1] : null;
};
diff --git a/apps/client/src/services/note_create.spec.ts b/apps/client/src/services/note_create.spec.ts
new file mode 100644
index 0000000000..61d1a1a674
--- /dev/null
+++ b/apps/client/src/services/note_create.spec.ts
@@ -0,0 +1,297 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+import { buildNote } from "../test/easy-froca";
+import froca from "./froca";
+import server from "./server.js";
+import ws from "./ws.js";
+
+// ---- Mocks for non-froca collaborators --------------------------------------
+// All mock state lives in a hoisted holder so the (hoisted) vi.mock factories
+// can safely reference it.
+const h = vi.hoisted(() => {
+ const tabManager = {
+ activeNoteType: "text" as string | null,
+ activeContext: null as any,
+ getActiveContextNoteType: () => tabManager.activeNoteType,
+ getActiveContext: () => tabManager.activeContext
+ };
+ return {
+ tabManager,
+ protectedAvailable: { value: false },
+ triggerEvent: vi.fn(),
+ triggerCommand: vi.fn(),
+ showMessage: vi.fn()
+ };
+});
+const { tabManager, protectedAvailable, triggerEvent, triggerCommand, showMessage } = h;
+
+vi.mock("../components/app_context.js", () => ({
+ default: {
+ tabManager: h.tabManager,
+ triggerEvent: (...args: unknown[]) => h.triggerEvent(...args),
+ triggerCommand: (...args: unknown[]) => h.triggerCommand(...args)
+ }
+}));
+
+vi.mock("./protected_session_holder.js", () => ({
+ default: {
+ isProtectedSessionAvailable: () => h.protectedAvailable.value
+ }
+}));
+
+vi.mock("./tree.js", () => ({
+ default: {
+ // parentNotePath here is what we pass in; strip query, take last segment
+ getNoteIdFromUrl: (url?: string) => (url ? url.split("?")[0].split("/").pop() : null)
+ }
+}));
+
+vi.mock("./toast.js", () => ({
+ default: {
+ showMessage: (...args: unknown[]) => h.showMessage(...args)
+ }
+}));
+
+// i18n returns the key so we can assert on structure, never on translated text
+vi.mock("./i18n.js", () => ({
+ t: (key: string, opts?: Record<string, unknown>) => `${key}:${JSON.stringify(opts ?? {})}`
+}));
+
+import noteCreateService from "./note_create.js";
+
+// Build a real note + parent branch in froca so getNote/getBranch resolve.
+const parentNote = buildNote({
+ title: "Parent",
+ children: [{ title: "Child" }]
+});
+const childBranchId = parentNote.children[0];
+const childNote = froca.getNoteFromCache(childBranchId)!;
+const NOTE_ID = childNote.noteId;
+const BRANCH_ID = `${parentNote.noteId}_${NOTE_ID}`;
+
+function setActiveContext(activate = true) {
+ const setNote = vi.fn(async () => {});
+ tabManager.activeContext = activate ? { ntxId: "ntx-1", setNote } : null;
+ return setNote;
+}
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ tabManager.activeNoteType = "text";
+ protectedAvailable.value = false;
+ ws.waitForMaxKnownEntityChangeId = vi.fn(async () => {});
+ server.post = vi.fn(async () => ({
+ note: { noteId: NOTE_ID },
+ branch: { branchId: BRANCH_ID }
+ })) as typeof server.post;
+});
+
+describe("createNote", () => {
+ it("posts with merged defaults, activates and focuses the title, returns froca entities", async () => {
+ const setNote = setActiveContext(true);
+
+ const result = await noteCreateService.createNote("root", { title: "Hello" }, "comp-1");
+
+ // URL reflects default target=into and empty targetBranchId; parentNoteId from tree mock
+ // parentNoteId comes from the last path segment via the tree mock
+ expect(server.post).toHaveBeenCalledWith(
+ `notes/root/children?target=into&targetBranchId=`,
+ expect.objectContaining({ title: "Hello", content: "", isProtected: false }),
+ "comp-1"
+ );
+ expect(setNote).toHaveBeenCalledWith(`root/${NOTE_ID}`);
+ expect(triggerEvent).toHaveBeenCalledWith("focusAndSelectTitle", { isNewNote: true });
+ expect(result.note).toBe(childNote);
+ expect(result.branch).toBe(froca.getBranch(BRANCH_ID));
+ });
+
+ it("focuses content when focus=content", async () => {
+ setActiveContext(true);
+ await noteCreateService.createNote("root", { focus: "content" });
+ expect(triggerEvent).toHaveBeenCalledWith("focusOnDetail", { ntxId: "ntx-1" });
+ expect(triggerEvent).not.toHaveBeenCalledWith("focusAndSelectTitle", expect.anything());
+ });
+
+ it("activates without firing a focus event when focus is neither title nor content", async () => {
+ const setNote = setActiveContext(true);
+ // an out-of-range focus value still activates the note but triggers no focus event
+ await noteCreateService.createNote("root", { focus: undefined as any });
+ expect(setNote).toHaveBeenCalledWith(`root/${NOTE_ID}`);
+ expect(triggerEvent).not.toHaveBeenCalled();
+ });
+
+ it("does not activate when activate=false, and skips activation when there is no active context", async () => {
+ // activate=false with a context present
+ const setNote = setActiveContext(true);
+ await noteCreateService.createNote("root", { activate: false });
+ expect(setNote).not.toHaveBeenCalled();
+ expect(triggerEvent).not.toHaveBeenCalled();
+
+ // no active context at all
+ setActiveContext(false);
+ await noteCreateService.createNote("root", { activate: true });
+ expect(triggerEvent).not.toHaveBeenCalled();
+ });
+
+ it("keeps isProtected only when requested AND session is available", async () => {
+ setActiveContext(true);
+
+ // requested but session unavailable -> forced to false
+ protectedAvailable.value = false;
+ await noteCreateService.createNote("root", { isProtected: true });
+ expect(server.post).toHaveBeenLastCalledWith(
+ expect.any(String),
+ expect.objectContaining({ isProtected: false }),
+ undefined
+ );
+
+ // requested and session available -> stays true
+ protectedAvailable.value = true;
+ await noteCreateService.createNote("root", { isProtected: true });
+ expect(server.post).toHaveBeenLastCalledWith(
+ expect.any(String),
+ expect.objectContaining({ isProtected: true }),
+ undefined
+ );
+ });
+
+ it("parses a heading selection into title/content and removes the selection (text context)", async () => {
+ setActiveContext(true);
+ const removeSelection = vi.fn();
+ const textEditor = {
+ getSelectedHtml: () => "<h2>My Heading</h2><p>body</p>",
+ removeSelection
+ } as any;
+
+ await noteCreateService.createNote("root", {
+ saveSelection: true,
+ textEditor
+ });
+
+ expect(server.post).toHaveBeenCalledWith(
+ expect.any(String),
+ expect.objectContaining({ title: "My Heading", content: "<p>body</p>" }),
+ undefined
+ );
+ expect(removeSelection).toHaveBeenCalled();
+ });
+
+ it("treats a non-heading selection as content with no title", async () => {
+ setActiveContext(true);
+ const textEditor = {
+ getSelectedHtml: () => "<p>just a paragraph</p>",
+ removeSelection: vi.fn()
+ } as any;
+
+ await noteCreateService.createNote("root", { saveSelection: true, textEditor });
+
+ expect(server.post).toHaveBeenCalledWith(
+ expect.any(String),
+ expect.objectContaining({ title: null, content: "<p>just a paragraph</p>" }),
+ undefined
+ );
+ });
+
+ it("disables saveSelection when the active context note type is not text", async () => {
+ setActiveContext(true);
+ tabManager.activeNoteType = "code";
+ const removeSelection = vi.fn();
+ const textEditor = {
+ getSelectedHtml: vi.fn(() => "<h1>x</h1>"),
+ removeSelection
+ } as any;
+
+ await noteCreateService.createNote("root", { saveSelection: true, textEditor });
+
+ // selection parsing was skipped, so getSelectedHtml/removeSelection untouched
+ expect(textEditor.getSelectedHtml).not.toHaveBeenCalled();
+ expect(removeSelection).not.toHaveBeenCalled();
+ });
+
+ it("honors an explicit target and targetBranchId in the URL", async () => {
+ setActiveContext(true);
+ await noteCreateService.createNote("root", { target: "after", targetBranchId: "tb-9" });
+ expect(server.post).toHaveBeenCalledWith(
+ `notes/root/children?target=after&targetBranchId=tb-9`,
+ expect.anything(),
+ undefined
+ );
+ });
+});
+
+describe("createNoteWithTypePrompt", () => {
+ it("returns undefined and posts nothing when the chooser is cancelled", async () => {
+ triggerCommand.mockImplementation((_name: string, data: any) => {
+ data.callback({ success: false });
+ });
+
+ const result = await noteCreateService.createNoteWithTypePrompt("root", {});
+ expect(result).toBeUndefined();
+ expect(server.post).not.toHaveBeenCalled();
+ expect(triggerCommand).toHaveBeenCalledWith("chooseNoteType", expect.anything());
+ });
+
+ it("creates a note with chosen type/template, preferring the chooser notePath", async () => {
+ setActiveContext(true);
+ triggerCommand.mockImplementation((_name: string, data: any) => {
+ data.callback({
+ success: true,
+ noteType: "code",
+ templateNoteId: "tpl-1",
+ notePath: "chosen-parent"
+ });
+ });
+
+ await noteCreateService.createNoteWithTypePrompt("fallback-parent", {});
+
+ expect(server.post).toHaveBeenCalledWith(
+ `notes/chosen-parent/children?target=into&targetBranchId=`,
+ expect.objectContaining({ type: "code", templateNoteId: "tpl-1" }),
+ undefined
+ );
+ });
+
+ it("falls back to the passed parentNotePath when the chooser returns none", async () => {
+ setActiveContext(true);
+ triggerCommand.mockImplementation((_name: string, data: any) => {
+ data.callback({ success: true, noteType: "text" });
+ });
+
+ await noteCreateService.createNoteWithTypePrompt("fallback-parent", {});
+
+ expect(server.post).toHaveBeenCalledWith(
+ `notes/fallback-parent/children?target=into&targetBranchId=`,
+ expect.anything(),
+ undefined
+ );
+ });
+});
+
+describe("chooseNoteType", () => {
+ it("resolves with whatever the chooser callback is invoked with", async () => {
+ const payload = { success: true, noteType: "render" };
+ triggerCommand.mockImplementation((_name: string, data: any) => data.callback(payload));
+ await expect(noteCreateService.chooseNoteType()).resolves.toEqual(payload);
+ });
+});
+
+describe("duplicateSubtree", () => {
+ it("posts the duplicate, activates the new note when a context exists, and toasts the original title", async () => {
+ const setNote = setActiveContext(true);
+ server.post = vi.fn(async () => ({ note: { noteId: NOTE_ID } })) as typeof server.post;
+
+ await noteCreateService.duplicateSubtree(NOTE_ID, "root");
+
+ expect(server.post).toHaveBeenCalledWith(`notes/${NOTE_ID}/duplicate/root`);
+ expect(setNote).toHaveBeenCalledWith(`root/${NOTE_ID}`);
+ expect(showMessage).toHaveBeenCalledWith(expect.stringContaining("note_create.duplicated"));
+ });
+
+ it("does not throw when there is no active context", async () => {
+ setActiveContext(false);
+ server.post = vi.fn(async () => ({ note: { noteId: NOTE_ID } })) as typeof server.post;
+
+ await expect(noteCreateService.duplicateSubtree(NOTE_ID, "root")).resolves.toBeUndefined();
+ expect(showMessage).toHaveBeenCalled();
+ });
+});
diff --git a/apps/client/src/services/note_tooltip.spec.ts b/apps/client/src/services/note_tooltip.spec.ts
new file mode 100644
index 0000000000..3fc53046f7
--- /dev/null
+++ b/apps/client/src/services/note_tooltip.spec.ts
@@ -0,0 +1,516 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import $ from "jquery";
+
+// --- Mocks (hoisted above imports) ---
+
+const { parseNavigationStateFromUrl, renderNormalAttributes, getRenderedContent, getNoteTitleWithPathAsSuffix, getActiveContext } = vi.hoisted(() => ({
+ parseNavigationStateFromUrl: vi.fn(),
+ renderNormalAttributes: vi.fn(),
+ getRenderedContent: vi.fn(),
+ getNoteTitleWithPathAsSuffix: vi.fn(),
+ getActiveContext: vi.fn()
+}));
+
+vi.mock("./link.js", () => ({
+ default: { parseNavigationStateFromUrl }
+}));
+
+vi.mock("./attribute_renderer.js", () => ({
+ default: { renderNormalAttributes }
+}));
+
+vi.mock("./content_renderer.js", () => ({
+ default: { getRenderedContent }
+}));
+
+vi.mock("./tree.js", () => ({
+ default: { getNoteTitleWithPathAsSuffix }
+}));
+
+vi.mock("../components/app_context.js", () => ({
+ default: { tabManager: { getActiveContext } }
+}));
+
+vi.mock("./i18n.js", () => ({
+ t: (key: string) => key
+}));
+
+// Imports AFTER vi.mock calls.
+import froca from "./froca.js";
+import noteTooltipService, { mouseEnterHandler, renderFootnoteOrAnchor, renderTooltip } from "./note_tooltip.js";
+
+const { setupGlobalTooltip, setupElementTooltip, dismissAllTooltips } = noteTooltipService;
+
+/** Build a fake FNote-like object with the methods note_tooltip calls. */
+function fakeNote(opts: { noteId?: string; bestPath?: string | undefined; colorClass?: string } = {}) {
+ return {
+ noteId: opts.noteId ?? "abc",
+ getBestNotePathString: vi.fn(() => opts.bestPath),
+ getColorClass: vi.fn(() => opts.colorClass ?? "")
+ } as any;
+}
+
+/** A jQuery element that mimics "hovered" / "visible" for the duration of a test. */
+let origFilter: typeof $.fn.filter;
+let origIs: typeof $.fn.is;
+let hoverActive = false;
+let visibleActive = false;
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ hoverActive = false;
+ visibleActive = false;
+
+ origFilter = $.fn.filter;
+ origIs = $.fn.is;
+
+ // happy-dom has no layout / no real pointer, so :hover and :visible never match.
+ // Override the two selectors used by note_tooltip so we can drive the hover/visible branches.
+ ($.fn as any).filter = function (sel: any) {
+ if (sel === ":hover") {
+ return hoverActive ? this : (origFilter as any).call(this, () => false);
+ }
+ return origFilter.apply(this, arguments as any);
+ };
+ ($.fn as any).is = function (sel: any) {
+ if (sel === ":visible") {
+ return visibleActive;
+ }
+ return origIs.apply(this, arguments as any);
+ };
+
+ // Bootstrap's .tooltip() plugin is not loaded under happy-dom; stub it.
+ ($.fn as any).tooltip = vi.fn(function (this: unknown) {
+ return this;
+ });
+
+ // Sensible defaults for the renderTooltip dependency chain.
+ renderNormalAttributes.mockResolvedValue({ $renderedAttributes: $("<div class='attrs'></div>") });
+ getRenderedContent.mockResolvedValue({ $renderedContent: $("<div class='content'>body</div>") });
+ getNoteTitleWithPathAsSuffix.mockResolvedValue($("<span class='note-title-with-path'>Title</span>"));
+ getActiveContext.mockReturnValue({ hoistedNoteId: "root" });
+});
+
+afterEach(() => {
+ // Clear any tracked tooltip elements while the .tooltip stub is still installed.
+ dismissAllTooltips();
+ $.fn.filter = origFilter;
+ $.fn.is = origIs;
+ delete ($.fn as any).tooltip;
+ vi.useRealTimers();
+});
+
+describe("renderFootnoteOrAnchor", () => {
+ it("extracts a footnote's content for a #fn reference", () => {
+ const $root = $(`
+ <div class="ck-content">
+ <a class="link" href="#fn1">^</a>
+ <div class="footnote-section">
+ <div class="footnote-item">
+ <a href="#fnref1">back</a>
+ <div class="footnote-content">the footnote text</div>
+ </div>
+ </div>
+ </div>`);
+ $("body").append($root);
+ const $link = $root.find("a.link");
+
+ const result = renderFootnoteOrAnchor($link, "#fn1");
+ expect(result).toContain("the footnote text");
+ expect(result).toMatch(/^<div class="ck-content">/);
+ });
+
+ it("resolves an in-document anchor to its enclosing paragraph", () => {
+ const $root = $(`
+ <div class="ck-content">
+ <a class="link" href="#sec">jump</a>
+ <p id="sec">target paragraph</p>
+ </div>`);
+ $("body").append($root);
+ const $link = $root.find("a.link");
+
+ const result = renderFootnoteOrAnchor($link, "#sec");
+ expect(result).toContain("target paragraph");
+ });
+
+ it("returns empty string when the target content is missing", () => {
+ const $root = $(`<div class="ck-content"><a class="link" href="#fnX">^</a></div>`);
+ $("body").append($root);
+ const $link = $root.find("a.link");
+
+ expect(renderFootnoteOrAnchor($link, "#fnX")).toBe("");
+ });
+
+ it("strips CKEditor widget buttons and rewrites inline math in editable notes", () => {
+ const $root = $(`
+ <div class="ck-content note-detail-editable-text-editor">
+ <a class="link" href="#fn1">^</a>
+ <div class="footnote-section">
+ <div class="footnote-item">
+ <a href="#fnref1">back</a>
+ <div class="footnote-content">
+ <span class="ck-widget__selection-handle">x</span>
+ <span class="ck-widget__type-around">y</span>
+ <span class="ck-widget__resizer">z</span>
+ <span class="ck-math-tex ck-math-tex-inline ck-widget">
+ <span class="katex">E=mc^2</span>
+ </span>
+ </div>
+ </div>
+ </div>
+ </div>`);
+ $("body").append($root);
+ const $link = $root.find("a.link");
+
+ const result = renderFootnoteOrAnchor($link, "#fn1");
+ // widget chrome removed
+ expect(result).not.toContain("ck-widget__selection-handle");
+ expect(result).not.toContain("ck-widget__type-around");
+ expect(result).not.toContain("ck-widget__resizer");
+ // inline math rewritten into a span.math-tex wrapper, preserving the katex node
+ expect(result).toContain("math-tex");
+ expect(result).toContain("E=mc^2");
+ });
+
+ it("leaves an inline math widget untouched in editable notes when it has no .katex child", () => {
+ const $root = $(`
+ <div class="ck-content note-detail-editable-text-editor">
+ <a class="link" href="#fn2">^</a>
+ <div class="footnote-section">
+ <div class="footnote-item">
+ <a href="#fnref2">back</a>
+ <div class="footnote-content">
+ <span class="ck-math-tex ck-math-tex-inline ck-widget">no katex here</span>
+ </div>
+ </div>
+ </div>
+ </div>`);
+ $("body").append($root);
+ const $link = $root.find("a.link");
+
+ const result = renderFootnoteOrAnchor($link, "#fn2");
+ expect(result).toContain("no katex here");
+ // the original widget markup is preserved (no rewrite into a <span class="math-tex">)
+ expect(result).toContain("ck-math-tex-inline");
+ expect(result).not.toContain('class="math-tex"');
+ });
+});
+
+describe("renderTooltip", () => {
+ it("returns the deleted-note placeholder when the note is null", async () => {
+ const html = await renderTooltip(null);
+ expect(html).toBe("<div>note_tooltip.note-has-been-deleted</div>");
+ });
+
+ it("returns undefined when there is no best note path", async () => {
+ const note = fakeNote({ bestPath: undefined });
+ expect(await renderTooltip(note)).toBeUndefined();
+ // hoistedNoteId resolved from the active context
+ expect(note.getBestNotePathString).toHaveBeenCalledWith("root");
+ });
+
+ it("falls back to undefined hoistedNoteId when there is no active context", async () => {
+ getActiveContext.mockReturnValue(undefined);
+ const note = fakeNote({ bestPath: undefined });
+ await renderTooltip(note);
+ expect(note.getBestNotePathString).toHaveBeenCalledWith(undefined);
+ });
+
+ it("renders title, attributes, content and the quick-edit button when content is present", async () => {
+ const note = fakeNote({ noteId: "n1", bestPath: "root/n1" });
+ const html = (await renderTooltip(note)) as string;
+
+ expect(html).toContain('class="note-tooltip-title"');
+ expect(html).not.toContain("note-no-content");
+ expect(html).toContain('href="#n1"');
+ expect(html).toContain('class="note-tooltip-attributes"');
+ // non-empty content is appended
+ expect(html).toContain("body");
+ // quick-edit popup button always appended
+ expect(html).toContain('href="#n1?popup"');
+ expect(html).toContain("note_tooltip.quick-edit");
+ });
+
+ it("marks the title as having no content and omits the content block when content is empty", async () => {
+ getRenderedContent.mockResolvedValue({ $renderedContent: $("<div class='content'></div>") });
+ const note = fakeNote({ noteId: "n2", bestPath: "root/n2" });
+ const html = (await renderTooltip(note)) as string;
+
+ expect(html).toContain("note-no-content");
+ // empty content div should not be appended
+ expect(html).not.toContain('class="content"');
+ expect(html).toContain('class="note-tooltip-attributes"');
+ });
+
+ it("omits the title heading when the path suffix resolves to empty", async () => {
+ getNoteTitleWithPathAsSuffix.mockResolvedValue("");
+ const note = fakeNote({ noteId: "n3", bestPath: "root/n3" });
+ const html = (await renderTooltip(note)) as string;
+
+ expect(html).not.toContain("note-tooltip-title");
+ expect(html.startsWith('<div class="note-tooltip-attributes">')).toBe(true);
+ });
+});
+
+describe("mouseEnterHandler", () => {
+ function makeLink(html: string) {
+ const $el = $(html);
+ $("body").append($el);
+ return $el;
+ }
+
+ function eventFor($el: JQuery<HTMLElement>, pointerType = "mouse") {
+ return { pointerType } as any;
+ }
+
+ it("ignores non-mouse pointer events", async () => {
+ const $link = makeLink('<a href="#root/abc">x</a>');
+ await mouseEnterHandler.call($link[0], eventFor($link, "touch"));
+ expect(parseNavigationStateFromUrl).not.toHaveBeenCalled();
+ });
+
+ it("ignores links opted out via class, CK link actions, or inside a tooltip", async () => {
+ const $a = makeLink('<a class="no-tooltip-preview" href="#root/a">a</a>');
+ const $b = makeLink('<div class="ck-link-actions"><a href="#root/b">b</a></div>').find("a");
+ const $c = makeLink('<div class="note-tooltip"><a href="#root/c">c</a></div>').find("a");
+
+ await mouseEnterHandler.call($a[0], eventFor($a));
+ await mouseEnterHandler.call($b[0], eventFor($b));
+ await mouseEnterHandler.call($c[0], eventFor($c));
+
+ expect(parseNavigationStateFromUrl).not.toHaveBeenCalled();
+ });
+
+ it("ignores footnote back-reference links (#fnref...)", async () => {
+ const $link = makeLink('<a href="#fnref1">^</a>');
+ parseNavigationStateFromUrl.mockReturnValue({ notePath: "p", noteId: "x", viewScope: { viewMode: "default" } });
+ await mouseEnterHandler.call($link[0], eventFor($link));
+ // returns before reading froca / showing a tooltip
+ expect(($.fn as any).tooltip).not.toHaveBeenCalled();
+ });
+
+ it("bails out when navigation state is incomplete or not the default view", async () => {
+ const $link = makeLink('<a data-href="#root/abc">x</a>');
+ parseNavigationStateFromUrl.mockReturnValue({ notePath: "p", noteId: "x", viewScope: { viewMode: "source" } });
+ await mouseEnterHandler.call($link[0], eventFor($link));
+ expect(($.fn as any).tooltip).not.toHaveBeenCalled();
+ });
+
+ it("short-circuits when a tooltip for this link is already visible", async () => {
+ const $link = makeLink('<a data-link-id="existing" href="#root/abc">x</a>');
+ parseNavigationStateFromUrl.mockReturnValue({ notePath: "root/abc", noteId: "abc", viewScope: { viewMode: "default" } });
+ visibleActive = true;
+
+ await mouseEnterHandler.call($link[0], eventFor($link));
+ expect(($.fn as any).tooltip).not.toHaveBeenCalled();
+ // existing id is preserved
+ expect($link.attr("data-link-id")).toBe("existing");
+ });
+
+ it("returns without showing a tooltip when rendered content is empty", async () => {
+ vi.useFakeTimers();
+ const $link = makeLink('<a href="#root/abc">x</a>');
+ parseNavigationStateFromUrl.mockReturnValue({ notePath: "root/abc", noteId: "abc", viewScope: { viewMode: "default" } });
+ froca.getNote = vi.fn(async () => null) as any;
+
+ const promise = mouseEnterHandler.call($link[0], eventFor($link));
+ await vi.advanceTimersByTimeAsync(600);
+ await promise;
+
+ // null note renders the deleted placeholder which isHtmlEmpty treats as non-empty,
+ // but we are not hovering, so no tooltip is created.
+ expect(($.fn as any).tooltip).not.toHaveBeenCalled();
+ // a fresh random link id was assigned
+ expect($link.attr("data-link-id")).toMatch(/^link-\d+$/);
+ });
+
+ it("returns without showing a tooltip when the footnote target yields empty content", async () => {
+ vi.useFakeTimers();
+ // anchor with no matching target -> renderFootnoteOrAnchor returns ""
+ const $root = makeLink(`<div class="ck-content"><a class="link" href="#missingfn">^</a></div>`);
+ const $link = $root.find("a.link");
+ parseNavigationStateFromUrl.mockReturnValue({ notePath: "missingfn", noteId: "missingfn", viewScope: { viewMode: "default" } });
+ froca.getNote = vi.fn() as any;
+ hoverActive = true;
+
+ const promise = mouseEnterHandler.call($link[0], eventFor($link));
+ await vi.advanceTimersByTimeAsync(600);
+ await promise;
+
+ // empty content -> early return before the tooltip is created
+ expect(($.fn as any).tooltip).not.toHaveBeenCalled();
+ });
+
+ it("dismisses all tooltips when a link inside the freshly-shown tooltip is clicked", async () => {
+ vi.useFakeTimers();
+ // Deterministic ids/classes so we can target the in-tooltip anchor selector.
+ const randomSpy = vi.spyOn(Math, "random").mockReturnValue(0);
+ // The handler binds click to `.tooltip-0 a`; pre-create a matching element so the
+ // delegated-at-bind-time selector resolves to a real anchor.
+ const $tooltipDom = $('<div class="tooltip-0"><a class="inner-link" href="#x">link</a></div>');
+ $("body").append($tooltipDom);
+
+ const $root = makeLink(`
+ <div class="ck-content">
+ <a class="link" href="#fn7">^</a>
+ <div class="footnote-section">
+ <div class="footnote-item">
+ <a href="#fnref7">back</a>
+ <div class="footnote-content">fn body</div>
+ </div>
+ </div>
+ </div>`);
+ const $link = $root.find("a.link");
+ parseNavigationStateFromUrl.mockReturnValue({ notePath: "fn7", noteId: "fn7", viewScope: { viewMode: "default" } });
+ hoverActive = true;
+
+ const promise = mouseEnterHandler.call($link[0], eventFor($link));
+ await vi.advanceTimersByTimeAsync(600);
+ await promise;
+
+ // tooltip was created & shown, and the link was tracked
+ expect(($.fn as any).tooltip).toHaveBeenCalledWith("show");
+ const tooltipMock = ($.fn as any).tooltip as ReturnType<typeof vi.fn>;
+ const disposeBefore = tooltipMock.mock.calls.filter((c) => c[0] === "dispose").length;
+
+ // Click the anchor inside the tooltip -> dismissAllTooltips runs (disposes tracked link).
+ $tooltipDom.find("a.inner-link").trigger("click");
+
+ const disposeAfter = tooltipMock.mock.calls.filter((c) => c[0] === "dispose").length;
+ expect(disposeAfter).toBeGreaterThan(disposeBefore);
+
+ randomSpy.mockRestore();
+ });
+
+ it("renders an in-text footnote tooltip without touching froca", async () => {
+ vi.useFakeTimers();
+ const $root = makeLink(`
+ <div class="ck-content">
+ <a class="link" href="#fn9">^</a>
+ <div class="footnote-section">
+ <div class="footnote-item">
+ <a href="#fnref9">back</a>
+ <div class="footnote-content">footnote body</div>
+ </div>
+ </div>
+ </div>`);
+ const $link = $root.find("a.link");
+ parseNavigationStateFromUrl.mockReturnValue({ notePath: "fn9", noteId: "fn9", viewScope: { viewMode: "default" } });
+ froca.getNote = vi.fn() as any;
+ hoverActive = true;
+
+ const promise = mouseEnterHandler.call($link[0], eventFor($link));
+ await vi.advanceTimersByTimeAsync(600);
+ await promise;
+
+ expect(froca.getNote).not.toHaveBeenCalled();
+ // hovered -> tooltip shown (init call + "show" call)
+ expect(($.fn as any).tooltip).toHaveBeenCalled();
+ });
+
+ it("creates, shows and tracks a tooltip while hovering, then dismisses on click and via the watchdog", async () => {
+ vi.useFakeTimers();
+ const $link = makeLink('<a href="#root/abc">x</a>');
+ parseNavigationStateFromUrl.mockReturnValue({ notePath: "root/abc", noteId: "abc", viewScope: { viewMode: "default" } });
+ const note = fakeNote({ noteId: "abc", bestPath: "root/abc", colorClass: "color-blue" });
+ froca.getNote = vi.fn(async () => note) as any;
+ hoverActive = true;
+
+ const promise = mouseEnterHandler.call($link[0], eventFor($link));
+ await vi.advanceTimersByTimeAsync(600);
+ await promise;
+
+ const tooltipMock = ($.fn as any).tooltip as ReturnType<typeof vi.fn>;
+ // initialised with options then explicitly shown
+ const initCall = tooltipMock.mock.calls.find((c) => typeof c[0] === "object");
+ expect(initCall?.[0]).toMatchObject({ container: "body", placement: "bottom", html: true, sanitize: false });
+ // color class folded into the tooltip template
+ expect(initCall?.[0].template).toContain("color-blue");
+ expect(tooltipMock).toHaveBeenCalledWith("show");
+
+ // the watchdog re-arms while still hovering...
+ await vi.advanceTimersByTimeAsync(1000);
+ // ...and dismisses (dispose) once hover ends
+ hoverActive = false;
+ const disposeBefore = tooltipMock.mock.calls.filter((c) => c[0] === "dispose").length;
+ await vi.advanceTimersByTimeAsync(1000);
+ const disposeAfter = tooltipMock.mock.calls.filter((c) => c[0] === "dispose").length;
+ expect(disposeAfter).toBeGreaterThan(disposeBefore);
+ });
+});
+
+/**
+ * Drives mouseEnterHandler through a successful "hovering" render so the link is
+ * pushed onto the module-private openTooltipElements list, then clears the hover/timers.
+ * Returns the tracked $link whose .tooltip is the shared vi.fn() stub.
+ */
+async function trackOneTooltip() {
+ vi.useFakeTimers();
+ const $link = $('<a href="#root/abc">tracked</a>');
+ $("body").append($link);
+ parseNavigationStateFromUrl.mockReturnValue({ notePath: "root/abc", noteId: "abc", viewScope: { viewMode: "default" } });
+ froca.getNote = vi.fn(async () => fakeNote({ noteId: "abc", bestPath: "root/abc" })) as any;
+ hoverActive = true;
+
+ const promise = mouseEnterHandler.call($link[0], { pointerType: "mouse" } as any);
+ await vi.advanceTimersByTimeAsync(600);
+ await promise;
+
+ // Stop the watchdog from interfering, but keep the element tracked.
+ hoverActive = false;
+ vi.useRealTimers();
+ const tooltipMock = ($link as any).tooltip as ReturnType<typeof vi.fn>;
+ tooltipMock.mockClear();
+ return $link;
+}
+
+describe("setup helpers and dismissAllTooltips", () => {
+ it("setupElementTooltip wires the pointerenter handler to the element", () => {
+ const $el = $('<a href="#root/abc">x</a>');
+ const onSpy = vi.spyOn($el, "on");
+ setupElementTooltip($el);
+ expect(onSpy).toHaveBeenCalledWith("pointerenter", expect.any(Function));
+ });
+
+ it("setupGlobalTooltip delegates pointerenter for anchors and [data-href]", () => {
+ const onSpy = vi.spyOn($.fn, "on");
+ setupGlobalTooltip();
+
+ const calls = onSpy.mock.calls as unknown as [string, string?][];
+ const pointerSelectors = calls.filter((c) => c[0] === "pointerenter").map((c) => c[1]);
+ expect(pointerSelectors).toContain("a:not(.no-tooltip-preview)");
+ expect(pointerSelectors).toContain("[data-href]:not(.no-tooltip-preview)");
+ // a global click handler is also registered (no delegation selector)
+ expect(calls.some((c) => c[0] === "click")).toBe(true);
+ onSpy.mockRestore();
+ });
+
+ it("setupGlobalTooltip's click handler dismisses tooltips only for clicks outside .note-tooltip", async () => {
+ setupGlobalTooltip();
+
+ // Track an open tooltip element so we can observe whether it gets disposed.
+ const $tracked = await trackOneTooltip();
+
+ // Click inside a .note-tooltip -> handler returns early, no dispose.
+ const $inside = $('<div class="note-tooltip"><span class="target">hi</span></div>');
+ $("body").append($inside);
+ $(document).trigger($.Event("click", { target: $inside.find(".target")[0] }));
+ expect(($tracked as any).tooltip).not.toHaveBeenCalledWith("dispose");
+
+ // Click outside -> dismissAllTooltips disposes the tracked element.
+ $(document).trigger($.Event("click", { target: document.body }));
+ expect(($tracked as any).tooltip).toHaveBeenCalledWith("dispose");
+ });
+
+ it("dismissAllTooltips disposes every tracked element and clears aria-describedby", async () => {
+ // Nothing tracked yet -> safe no-op.
+ expect(() => dismissAllTooltips()).not.toThrow();
+
+ // Register a tracked element and assert it is cleaned up.
+ const $tracked = await trackOneTooltip();
+ $tracked.attr("aria-describedby", "tooltip-id");
+ dismissAllTooltips();
+ expect(($tracked as any).tooltip).toHaveBeenCalledWith("dispose");
+ expect($tracked.attr("aria-describedby")).toBeUndefined();
+ });
+});
diff --git a/apps/client/src/services/note_tooltip.ts b/apps/client/src/services/note_tooltip.ts
index 9ab8fc8e8f..c8bac2b080 100644
--- a/apps/client/src/services/note_tooltip.ts
+++ b/apps/client/src/services/note_tooltip.ts
@@ -40,7 +40,7 @@ function setupElementTooltip($el: JQuery<HTMLElement>) {
$el.on("pointerenter", mouseEnterHandler);
}
-async function mouseEnterHandler<T>(this: HTMLElement, e: JQuery.TriggeredEvent<T, undefined, T, T>) {
+export async function mouseEnterHandler<T>(this: HTMLElement, e: JQuery.TriggeredEvent<T, undefined, T, T>) {
if (e.pointerType !== "mouse") return;
const $link = $(this);
@@ -144,7 +144,7 @@ async function mouseEnterHandler<T>(this: HTMLElement, e: JQuery.TriggeredEvent<
}
}
-async function renderTooltip(note: FNote | null) {
+export async function renderTooltip(note: FNote | null) {
if (!note) {
return `<div>${t("note_tooltip.note-has-been-deleted")}</div>`;
}
@@ -187,7 +187,7 @@ async function renderTooltip(note: FNote | null) {
return content;
}
-function renderFootnoteOrAnchor($link: JQuery<HTMLElement>, url: string) {
+export function renderFootnoteOrAnchor($link: JQuery<HTMLElement>, url: string) {
// A footnote text reference
const footnoteRef = url.substring(3);
let $targetContent: JQuery<HTMLElement>;
@@ -229,6 +229,7 @@ function renderFootnoteOrAnchor($link: JQuery<HTMLElement>, url: string) {
let footnoteContent = $targetContent.html();
footnoteContent = `<div class="ck-content">${footnoteContent}</div>`;
+ /* v8 ignore next -- footnoteContent is always a non-empty wrapper div here, so the || "" fallback is unreachable */
return footnoteContent || "";
}
diff --git a/apps/client/src/services/note_types.spec.ts b/apps/client/src/services/note_types.spec.ts
new file mode 100644
index 0000000000..242a1c4de5
--- /dev/null
+++ b/apps/client/src/services/note_types.spec.ts
@@ -0,0 +1,390 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+import { buildNote } from "../test/easy-froca";
+import froca from "./froca";
+import server from "./server.js";
+
+// i18next is not initialized in the test env, so the real `t` returns undefined.
+// Echo the key so titles are truthy (covers the title->header branch in
+// getBuiltInTemplates and gives badges a stable title).
+vi.mock("./i18n.js", () => ({
+ t: (key: string) => key
+}));
+
+// Control the llmChat gating deterministically.
+vi.mock("./experimental_features.js", () => ({
+ isExperimentalFeatureEnabled: vi.fn(() => false)
+}));
+
+import { isExperimentalFeatureEnabled } from "./experimental_features.js";
+import noteTypesService from "./note_types";
+
+const llmFlag = vi.mocked(isExperimentalFeatureEnabled);
+
+// Builds a fresh `_templates`-rooted tree for getBuiltInTemplates. Because froca and
+// the module-level `_templates` note are singletons, we recreate it under a unique
+// child set per test by overriding froca.getNote/getChildNotes for that note id.
+type FakeNote = {
+ noteId: string;
+ title: string;
+ type: string;
+ hasLabel: (n: string) => boolean;
+ getIcon: () => string;
+ getChildNotes: () => Promise<FakeNote[]>;
+};
+
+function fakeTemplate(noteId: string, labels: string[], title = noteId): FakeNote {
+ return {
+ noteId,
+ title,
+ type: "text",
+ hasLabel: (n: string) => labels.includes(n),
+ getIcon: () => "tn-icon bx-x",
+ getChildNotes: async () => []
+ };
+}
+
+function withTemplatesRoot(children: FakeNote[] | null) {
+ const realGetNote = froca.getNote.bind(froca);
+ froca.getNote = (async (noteId: string, silent?: boolean) => {
+ if (noteId === "_templates") {
+ if (children === null) {
+ return null;
+ }
+ return {
+ noteId: "_templates",
+ getChildNotes: async () => children
+ };
+ }
+ return realGetNote(noteId, silent ?? false);
+ }) as typeof froca.getNote;
+ return () => {
+ froca.getNote = realGetNote;
+ };
+}
+
+describe("getBlankNoteTypes (via getNoteTypeItems)", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ llmFlag.mockReturnValue(false);
+ // Empty templates root and no user templates so we only see blank types.
+ server.get = vi.fn(async (url: string) => {
+ if (url === "search-templates") return [];
+ return undefined;
+ }) as typeof server.get;
+ });
+
+ it("excludes reserved types, book, and llmChat (when feature disabled), and maps icons/badges", async () => {
+ const restore = withTemplatesRoot([]);
+ try {
+ const items = await noteTypesService.getNoteTypeItems("note-types-command" as never);
+ const cmdItems: any[] = items.filter((i: any) => i.type);
+
+ const types = cmdItems.map((i: any) => i.type);
+ // reserved types are removed
+ for (const reserved of ["contentWidget", "doc", "file", "image", "launcher"]) {
+ expect(types).not.toContain(reserved);
+ }
+ // book is removed, llmChat removed while feature disabled
+ expect(types).not.toContain("book");
+ expect(types).not.toContain("llmChat");
+ // a few expected types survive
+ expect(types).toContain("text");
+ expect(types).toContain("mermaid");
+
+ // every command item carries the passed command and a bx-prefixed icon
+ for (const item of cmdItems) {
+ expect(item.command).toBe("note-types-command");
+ expect(item.uiIcon.startsWith("bx ")).toBe(true);
+ }
+
+ // isNew -> NEW badge, isBeta -> BETA badge. spreadsheet is both new+beta.
+ const spreadsheet = cmdItems.find((i: any) => i.type === "spreadsheet");
+ expect(spreadsheet.badges).toHaveLength(2);
+ expect(spreadsheet.badges.some((b: any) => b.className === "new-note-type-badge")).toBe(true);
+
+ // text has no badges
+ const text = cmdItems.find((i: any) => i.type === "text");
+ expect(text.badges).toEqual([]);
+ } finally {
+ restore();
+ }
+ });
+
+ it("includes llmChat when the llm experimental feature is enabled", async () => {
+ llmFlag.mockImplementation((id: string) => id === "llm");
+ const restore = withTemplatesRoot([]);
+ try {
+ const items = await noteTypesService.getNoteTypeItems();
+ const types = items.filter((i: any) => i.type).map((i: any) => i.type);
+ expect(types).toContain("llmChat");
+ } finally {
+ restore();
+ }
+ });
+});
+
+describe("getBuiltInTemplates", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ llmFlag.mockReturnValue(false);
+ server.get = vi.fn(async (url: string) => {
+ if (url === "search-templates") return [];
+ // notes/root returns an object WITHOUT dateCreated: exercises the
+ // `"dateCreated" in rootNoteInfo` false branch AND keeps the module-level
+ // rootCreationDate undefined for the following tests.
+ if (url === "notes/root") return { id: "root" };
+ // A recent built-in template ("tpl-plain") gets the "new" badge; everything
+ // else is old.
+ if (url === "notes/tpl-plain") return { dateCreated: new Date().toISOString() };
+ return { dateCreated: "2000-01-02 00:00:00.000Z" };
+ }) as typeof server.get;
+ });
+
+ it("warns and returns nothing when the templates root is missing", async () => {
+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
+ const restore = withTemplatesRoot(null);
+ try {
+ const items = await noteTypesService.getNoteTypeItems();
+ // No header/separator coming from built-in templates -> only blank note types remain.
+ expect(items.some((i: any) => i.kind === "separator")).toBe(false);
+ expect(items.some((i: any) => i.kind === "header")).toBe(false);
+ expect(warn).toHaveBeenCalled();
+ } finally {
+ restore();
+ warn.mockRestore();
+ }
+ });
+
+ it("returns nothing when the templates root has no children", async () => {
+ const restore = withTemplatesRoot([]);
+ try {
+ const items = await noteTypesService.getNoteTypeItems();
+ expect(items.some((i: any) => i.kind === "separator")).toBe(false);
+ expect(items.some((i: any) => i.kind === "header")).toBe(false);
+ } finally {
+ restore();
+ }
+ });
+
+ it("emits a separator for non-collection group and a header for the collections group, filtering by labels", async () => {
+ // Children include: a plain template (non-collection), a collection template,
+ // and a child that is neither a template nor matches -> skipped in both passes.
+ const plain = fakeTemplate("tpl-plain", ["template"], "Plain");
+ const collection = fakeTemplate("tpl-coll", ["template", "collection"], "Coll");
+ const notTemplate = fakeTemplate("tpl-skip", ["collection"], "Skip"); // missing "template"
+ const restore = withTemplatesRoot([plain, collection, notTemplate]);
+ try {
+ const items: any[] = await noteTypesService.getNoteTypeItems("cmd" as never);
+
+ // Non-collection pass (filterCollections=false, title=null) pushes a separator
+ // then the plain template.
+ const sepIdx = items.findIndex((i) => i.kind === "separator");
+ expect(sepIdx).toBeGreaterThanOrEqual(0);
+ expect(items.some((i) => i.templateNoteId === "tpl-plain")).toBe(true);
+
+ // Collections pass (filterCollections=true, title set) pushes a header then
+ // the collection template.
+ expect(items.some((i) => i.kind === "header")).toBe(true);
+ expect(items.some((i) => i.templateNoteId === "tpl-coll")).toBe(true);
+
+ // The note missing the "template" label is never included.
+ expect(items.some((i) => i.templateNoteId === "tpl-skip")).toBe(false);
+
+ // built-in template items carry command/type/icon/title.
+ const plainItem = items.find((i) => i.templateNoteId === "tpl-plain");
+ expect(plainItem.command).toBe("cmd");
+ expect(plainItem.type).toBe("text");
+ expect(plainItem.uiIcon).toBe("tn-icon bx-x");
+ // tpl-plain has a recent creation date -> gets the "new" badge.
+ expect(plainItem.badges).toHaveLength(1);
+ expect(plainItem.badges[0].className).toBe("new-note-type-badge");
+ // The old collection template is not marked new.
+ const collItem = items.find((i) => i.templateNoteId === "tpl-coll");
+ expect(collItem.badges).toBeUndefined();
+ } finally {
+ restore();
+ }
+ });
+});
+
+describe("getUserTemplates", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ llmFlag.mockReturnValue(false);
+ });
+
+ it("returns nothing when there are no user template notes", async () => {
+ server.get = vi.fn(async (url: string) => {
+ if (url === "search-templates") return [];
+ return undefined;
+ }) as typeof server.get;
+ const restore = withTemplatesRoot([]);
+ try {
+ const items: any[] = await noteTypesService.getNoteTypeItems();
+ // The user-templates header should not be present.
+ expect(items.some((i) => i.kind === "header" && i.templateNoteId === undefined && i.title === "note_type_chooser.templates")).toBe(false);
+ } finally {
+ restore();
+ }
+ });
+
+ it("adds a header and one item per user template, mapping note fields", async () => {
+ const userTpl = buildNote({ title: "My Template", type: "text" });
+ server.get = vi.fn(async (url: string) => {
+ if (url === "search-templates") return [userTpl.noteId];
+ if (url === "notes/root") throw new Error("no root");
+ // Old creation date -> not "new".
+ return { dateCreated: "2000-01-02 00:00:00.000Z" };
+ }) as typeof server.get;
+ const restore = withTemplatesRoot([]);
+ try {
+ const items: any[] = await noteTypesService.getNoteTypeItems("cmd2" as never);
+ expect(items.some((i) => i.kind === "header")).toBe(true);
+ const tplItem = items.find((i) => i.templateNoteId === userTpl.noteId);
+ expect(tplItem).toBeTruthy();
+ expect(tplItem.title).toBe("My Template");
+ expect(tplItem.command).toBe("cmd2");
+ expect(tplItem.type).toBe("text");
+ expect(typeof tplItem.uiIcon).toBe("string");
+ // Old template -> no "new" badge.
+ expect(tplItem.badges).toBeUndefined();
+ } finally {
+ restore();
+ }
+ });
+});
+
+describe("isNewTemplate (via getUserTemplates)", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ llmFlag.mockReturnValue(false);
+ });
+
+ async function runWithTemplate(noteId: string, getImpl: (url: string) => Promise<unknown>) {
+ const tpl = buildNote({ id: noteId, title: noteId, type: "text" });
+ server.get = vi.fn(getImpl) as typeof server.get;
+ const restore = withTemplatesRoot([]);
+ try {
+ const items: any[] = await noteTypesService.getNoteTypeItems();
+ return items.find((i) => i.templateNoteId === tpl.noteId);
+ } finally {
+ restore();
+ }
+ }
+
+ // NOTE on ordering: the module caches `rootCreationDate` on the FIRST successful
+ // `notes/root` fetch and never resets it. To keep it `undefined` for the
+ // age-based-branch tests, those tests make `notes/root` throw (a throw is caught,
+ // leaving the date unset). The single test that sets a real root date — the "30s"
+ // test — runs LAST so it cannot pollute the others.
+
+ it("tolerates a failing notes/root fetch (root date stays unknown) and marks a recent template as new", async () => {
+ const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {});
+ const recent = new Date().toISOString();
+ // notes/root throws -> caught, rootCreationDate stays undefined; template fetched
+ // with a recent date and no root date -> age check applies -> new badge.
+ const item = await runWithTemplate("isnew-recent-1", async (url) => {
+ if (url === "search-templates") return ["isnew-recent-1"];
+ if (url === "notes/root") throw new Error("boom");
+ return { dateCreated: recent };
+ });
+ expect(item.badges).toHaveLength(1);
+ expect(item.badges[0].className).toBe("new-note-type-badge");
+ expect(errorSpy).toHaveBeenCalled();
+ errorSpy.mockRestore();
+ });
+
+ it("does not mark an old template as new (age check returns false)", async () => {
+ // root fetch throws -> rootCreationDate undefined -> skips 30s check, reaches age check.
+ const item = await runWithTemplate("isnew-old", async (url) => {
+ if (url === "search-templates") return ["isnew-old"];
+ if (url === "notes/root") throw new Error("no root");
+ return { dateCreated: "1999-06-01 00:00:00.000Z" };
+ });
+ expect(item.badges).toBeUndefined();
+ });
+
+ it("returns no badge when the note fetch fails (creation date stays unknown)", async () => {
+ const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {});
+ // Template note fetch throws -> creationDate stays undefined -> returns false (no badge).
+ const item = await runWithTemplate("isnew-nodate", async (url) => {
+ if (url === "search-templates") return ["isnew-nodate"];
+ if (url === "notes/root") throw new Error("no root");
+ throw new Error("note fetch failed");
+ });
+ expect(item.badges).toBeUndefined();
+ expect(errorSpy).toHaveBeenCalled();
+ errorSpy.mockRestore();
+ });
+
+ it("returns no badge when the note response has no dateCreated field", async () => {
+ // notes/<id> returns an object without dateCreated -> creationDate stays
+ // undefined -> returns false. Exercises the `"dateCreated" in noteInfo` false branch.
+ const item = await runWithTemplate("isnew-nofield", async (url) => {
+ if (url === "search-templates") return ["isnew-nofield"];
+ if (url === "notes/root") throw new Error("no root");
+ return { id: "isnew-nofield" };
+ });
+ expect(item.badges).toBeUndefined();
+ });
+
+ it("uses the cached creation date on a second lookup (no second notes/<id> fetch)", async () => {
+ const recent = new Date().toISOString();
+ const getImpl = vi.fn(async (url: string) => {
+ if (url === "search-templates") return ["isnew-cached"];
+ if (url === "notes/root") throw new Error("no root");
+ return { dateCreated: recent };
+ });
+ buildNote({ id: "isnew-cached", title: "isnew-cached", type: "text" });
+ server.get = getImpl as unknown as typeof server.get;
+ const restore = withTemplatesRoot([]);
+ try {
+ await noteTypesService.getNoteTypeItems();
+ const callsAfterFirst = getImpl.mock.calls.filter((c) => c[0] === "notes/isnew-cached").length;
+ await noteTypesService.getNoteTypeItems();
+ const callsAfterSecond = getImpl.mock.calls.filter((c) => c[0] === "notes/isnew-cached").length;
+ // The per-note creation date is cached, so it is fetched at most once.
+ expect(callsAfterFirst).toBe(1);
+ expect(callsAfterSecond).toBe(1);
+ } finally {
+ restore();
+ }
+ });
+
+ // MUST run before the "cached root date" test below: this is the only test that
+ // lets `notes/root` resolve, which permanently caches `rootCreationDate` in the module.
+ it("ignores templates created within 30s of the root note (no new badge)", async () => {
+ const root = new Date();
+ const justAfterRoot = new Date(root.getTime() + 10_000).toISOString();
+ const item = await runWithTemplate("isnew-near-root", async (url) => {
+ if (url === "search-templates") return ["isnew-near-root"];
+ if (url === "notes/root") return { dateCreated: root.toISOString() };
+ return { dateCreated: justAfterRoot };
+ });
+ expect(item.badges).toBeUndefined();
+ });
+
+ // MUST be last: relies on `rootCreationDate` already being cached by the test above.
+ it("does not re-fetch notes/root once the root creation date is cached", async () => {
+ const getImpl = vi.fn(async (url: string) => {
+ if (url === "search-templates") return ["isnew-after-cached"];
+ // notes/root must NOT be requested anymore; if it were, this would throw.
+ if (url === "notes/root") throw new Error("root should not be fetched again");
+ return { dateCreated: "1999-06-01 00:00:00.000Z" };
+ });
+ buildNote({ id: "isnew-after-cached", title: "isnew-after-cached", type: "text" });
+ server.get = getImpl as unknown as typeof server.get;
+ const restore = withTemplatesRoot([]);
+ try {
+ const items: any[] = await noteTypesService.getNoteTypeItems();
+ const item = items.find((i) => i.templateNoteId === "isnew-after-cached");
+ // Old template -> not new regardless.
+ expect(item.badges).toBeUndefined();
+ // The cached root date means notes/root is never requested.
+ expect(getImpl.mock.calls.some((c) => c[0] === "notes/root")).toBe(false);
+ } finally {
+ restore();
+ }
+ });
+});
diff --git a/apps/client/src/services/open.spec.ts b/apps/client/src/services/open.spec.ts
new file mode 100644
index 0000000000..df53d84c92
--- /dev/null
+++ b/apps/client/src/services/open.spec.ts
@@ -0,0 +1,239 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+import { buildNote } from "../test/easy-froca";
+import open, { checkType, downloadFileNote, getUrlForDownload, openNoteExternally } from "./open.js";
+import options from "./options.js";
+import server from "./server.js";
+import utils from "./utils.js";
+
+const realWindow = window as any;
+
+/** Build a minimal electronApi.shell stub and install it on window. */
+function installElectronApi() {
+ const shell = {
+ downloadURL: vi.fn(),
+ openCustom: vi.fn(),
+ openPath: vi.fn(async () => "") as ReturnType<typeof vi.fn>
+ };
+ realWindow.electronApi = { shell };
+ return shell;
+}
+
+function removeElectronApi() {
+ delete realWindow.electronApi;
+}
+
+describe("open service", () => {
+ beforeEach(() => {
+ vi.restoreAllMocks();
+ removeElectronApi();
+ // Default: behave like a plain web browser.
+ vi.spyOn(utils, "isElectron").mockReturnValue(false);
+ vi.spyOn(utils, "isMac").mockReturnValue(false);
+ // window.open / location.href are used as side effects; stub open, track href.
+ vi.spyOn(window, "open").mockReturnValue(null);
+ });
+
+ afterEach(() => {
+ removeElectronApi();
+ });
+
+ describe("getUrlForDownload", () => {
+ it("returns an absolute URL under Electron and a relative one in the browser", () => {
+ (window as any).history.replaceState({}, "", "/");
+ vi.spyOn(utils, "isElectron").mockReturnValue(true);
+ const electronUrl = getUrlForDownload("api/notes/abc/download");
+ // host is derived from window.location: protocol//hostname:port
+ expect(electronUrl).toMatch(/^https?:\/\/[^/]+\/api\/notes\/abc\/download$/);
+
+ vi.spyOn(utils, "isElectron").mockReturnValue(false);
+ expect(getUrlForDownload("api/notes/abc/download")).toBe("api/notes/abc/download");
+ });
+ });
+
+ describe("download", () => {
+ it("uses electronApi.shell.downloadURL when running under Electron", () => {
+ const shell = installElectronApi();
+ open.download("http://example/x");
+ expect(shell.downloadURL).toHaveBeenCalledWith("http://example/x");
+ });
+
+ it("navigates via window.location.href in the browser", () => {
+ open.download("http://example/y");
+ expect(window.location.href).toContain("http://example/y");
+ });
+ });
+
+ describe("downloadFileNote", () => {
+ it("delegates to customDownload for PDF file notes via the parent component", () => {
+ const note = buildNote({ title: "Doc", type: "file" });
+ (note as any).mime = "application/pdf";
+ const parent = { triggerEvent: vi.fn() } as any;
+ downloadFileNote(note, parent, "ntx-1");
+ expect(parent.triggerEvent).toHaveBeenCalledWith("customDownload", { ntxId: "ntx-1" });
+ });
+
+ it("delegates to customDownload for the _backendLog note", () => {
+ const note = buildNote({ id: "_backendLog", title: "Backend log", type: "text" });
+ const parent = { triggerEvent: vi.fn() } as any;
+ downloadFileNote(note, parent, null);
+ expect(parent.triggerEvent).toHaveBeenCalledWith("customDownload", { ntxId: null });
+ });
+
+ it("downloads the note content when there is no parent component", () => {
+ const note = buildNote({ title: "Plain", type: "file" });
+ (note as any).mime = "image/png";
+ downloadFileNote(note, null, undefined);
+ expect(window.location.href).toContain(`api/notes/${note.noteId}/download?`);
+ });
+ });
+
+ describe("downloadAttachment", () => {
+ it("downloads an attachment via a cache-busted URL", () => {
+ open.downloadAttachment("att-123");
+ expect(window.location.href).toContain("api/attachments/att-123/download?");
+ });
+ });
+
+ describe("downloadRevision", () => {
+ it("downloads a revision via the revisions endpoint", () => {
+ open.downloadRevision("note-1", "rev-9");
+ expect(window.location.href).toContain("api/revisions/rev-9/download");
+ });
+ });
+
+ describe("checkType", () => {
+ it("accepts notes and attachments but throws otherwise", () => {
+ expect(() => checkType("notes")).not.toThrow();
+ expect(() => checkType("attachments")).not.toThrow();
+ expect(() => checkType("bogus")).toThrow(/Unrecognized type 'bogus'/);
+ });
+ });
+
+ describe("openCustom", () => {
+ it("does nothing in the browser (no electronApi)", async () => {
+ server.post = vi.fn(async () => ({ tmpFilePath: "/tmp/x" })) as typeof server.post;
+ await open.openNoteCustom("n1", "image/png");
+ expect(server.post).not.toHaveBeenCalled();
+ });
+
+ it("does nothing under Electron on macOS", async () => {
+ const shell = installElectronApi();
+ vi.spyOn(utils, "isMac").mockReturnValue(true);
+ server.post = vi.fn(async () => ({ tmpFilePath: "/tmp/x" })) as typeof server.post;
+ await open.openAttachmentCustom("a1", "image/png");
+ expect(server.post).not.toHaveBeenCalled();
+ expect(shell.openCustom).not.toHaveBeenCalled();
+ });
+
+ it("saves to tmp dir and opens the file under Electron on non-Mac", async () => {
+ const shell = installElectronApi();
+ server.post = vi.fn(async () => ({ tmpFilePath: "/tmp/file.png" })) as typeof server.post;
+ await open.openNoteCustom("n2", "image/png");
+ expect(server.post).toHaveBeenCalledWith("notes/n2/save-to-tmp-dir");
+ expect(shell.openCustom).toHaveBeenCalledWith("/tmp/file.png");
+ });
+ });
+
+ describe("openExternally", () => {
+ it("opens common mime types in the browser via window.open", async () => {
+ await openNoteExternally("n3", "application/pdf");
+ expect(window.open).toHaveBeenCalledWith("api/notes/n3/open");
+ });
+
+ it("navigates via location.href for non-browser-openable mime types", async () => {
+ await open.openAttachmentExternally("a3", "application/zip");
+ expect(window.location.href).toContain("api/attachments/a3/download");
+ });
+
+ it("covers all canOpenInBrowser branches (image/audio/video)", async () => {
+ await openNoteExternally("img", "image/jpeg");
+ expect(window.open).toHaveBeenLastCalledWith("api/notes/img/open");
+ await openNoteExternally("aud", "audio/mpeg");
+ expect(window.open).toHaveBeenLastCalledWith("api/notes/aud/open");
+ await openNoteExternally("vid", "video/mp4");
+ expect(window.open).toHaveBeenLastCalledWith("api/notes/vid/open");
+ });
+
+ it("opens via the OS under Electron and does not fall back when openPath succeeds", async () => {
+ const shell = installElectronApi();
+ vi.spyOn(utils, "isElectron").mockReturnValue(true);
+ shell.openPath.mockResolvedValue(""); // empty string = success
+ server.post = vi.fn(async () => ({ tmpFilePath: "/tmp/a.bin" })) as typeof server.post;
+ await openNoteExternally("n4", "application/octet-stream");
+ expect(server.post).toHaveBeenCalledWith("notes/n4/save-to-tmp-dir");
+ expect(shell.openPath).toHaveBeenCalledWith("/tmp/a.bin");
+ expect(window.open).not.toHaveBeenCalled();
+ });
+
+ it("falls back to window.open under Electron when openPath returns an error", async () => {
+ const shell = installElectronApi();
+ vi.spyOn(utils, "isElectron").mockReturnValue(true);
+ shell.openPath.mockResolvedValue("no default app"); // non-empty = failure
+ server.post = vi.fn(async () => ({ tmpFilePath: "/tmp/b.bin" })) as typeof server.post;
+ await open.openAttachmentExternally("a4", "application/octet-stream");
+ // Under Electron getFileUrl yields an absolute URL (host prefix).
+ expect(window.open).toHaveBeenCalledWith(
+ expect.stringContaining("api/attachments/a4/download")
+ );
+ });
+ });
+
+ describe("openNoteOnServer", () => {
+ it("logs an error when no sync server host is configured", async () => {
+ await options.initializedPromise;
+ options.set("syncServerHost", "");
+ const errSpy = vi.spyOn(console, "error").mockImplementation(() => {});
+ await open.openNoteOnServer("n5");
+ expect(errSpy).toHaveBeenCalled();
+ expect(window.open).not.toHaveBeenCalled();
+ });
+
+ it("opens the note URL in a new browser tab when a sync server host is set", async () => {
+ await options.initializedPromise;
+ options.set("syncServerHost", "https://sync.example.com");
+ await open.openNoteOnServer("n6");
+ expect(window.open).toHaveBeenCalledWith(
+ "https://sync.example.com/#root/n6",
+ "_blank",
+ "noopener,noreferrer"
+ );
+ });
+ });
+
+ describe("openDirectory", () => {
+ it("warns in a non-Electron environment", async () => {
+ const errSpy = vi.spyOn(console, "error").mockImplementation(() => {});
+ await open.openDirectory("/some/dir");
+ expect(errSpy).toHaveBeenCalledWith("Not running in an Electron environment.");
+ });
+
+ it("opens the directory under Electron when openPath succeeds", async () => {
+ const shell = installElectronApi();
+ vi.spyOn(utils, "isElectron").mockReturnValue(true);
+ shell.openPath.mockResolvedValue(""); // success
+ const errSpy = vi.spyOn(console, "error").mockImplementation(() => {});
+ await open.openDirectory("/ok/dir");
+ expect(shell.openPath).toHaveBeenCalledWith("/ok/dir");
+ expect(errSpy).not.toHaveBeenCalled();
+ });
+
+ it("logs an error under Electron when openPath returns an error string", async () => {
+ const shell = installElectronApi();
+ vi.spyOn(utils, "isElectron").mockReturnValue(true);
+ shell.openPath.mockResolvedValue("ENOENT"); // failure
+ const errSpy = vi.spyOn(console, "error").mockImplementation(() => {});
+ await open.openDirectory("/bad/dir");
+ expect(errSpy).toHaveBeenCalledWith("Failed to open directory:", "ENOENT");
+ });
+
+ it("catches and logs filesystem errors thrown by openPath", async () => {
+ const shell = installElectronApi();
+ vi.spyOn(utils, "isElectron").mockReturnValue(true);
+ shell.openPath.mockRejectedValue(new Error("boom"));
+ const errSpy = vi.spyOn(console, "error").mockImplementation(() => {});
+ await open.openDirectory("/throws");
+ expect(errSpy).toHaveBeenCalledWith("Error:", "boom");
+ });
+ });
+});
diff --git a/apps/client/src/services/open.ts b/apps/client/src/services/open.ts
index 06944f8057..3dcaa4aa57 100644
--- a/apps/client/src/services/open.ts
+++ b/apps/client/src/services/open.ts
@@ -9,7 +9,7 @@ interface TmpResponse {
tmpFilePath: string;
}
-function checkType(type: string) {
+export function checkType(type: string) {
if (type !== "notes" && type !== "attachments") {
throw new Error(`Unrecognized type '${type}', should be 'notes' or 'attachments'`);
}
diff --git a/apps/client/src/services/options.spec.ts b/apps/client/src/services/options.spec.ts
new file mode 100644
index 0000000000..232948d3e2
--- /dev/null
+++ b/apps/client/src/services/options.spec.ts
@@ -0,0 +1,135 @@
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+import type { OptionNames } from "@triliumnext/commons";
+import options from "./options.js";
+import server from "./server.js";
+
+// Cast helper: the methods are typed against the full OptionNames union, but the
+// behavior under test is purely string-keyed, so any string is a valid stand-in.
+const k = (name: string) => name as OptionNames;
+
+describe("Options service", () => {
+ afterEach(() => {
+ vi.restoreAllMocks();
+ });
+
+ it("resolves the singleton once the canned options GET has loaded", async () => {
+ // The constructor (non-share branch) issues server.get("options"); the global
+ // mock returns {}. Awaiting the promise exercises load() and leaves arr = {}.
+ await options.initializedPromise;
+ expect(options.getNames()).toEqual([]);
+ });
+
+ it("load() replaces the backing record and feeds every reader", () => {
+ options.load({
+ str: "hello",
+ jsonValid: '{"a":1}',
+ jsonInvalid: "{not json}",
+ jsonNonString: 5,
+ intString: "42",
+ intNumber: 7,
+ floatString: "3.14",
+ floatNumber: 9,
+ boolTrue: "true",
+ boolFalse: "false"
+ });
+
+ expect(options.getNames().sort()).toEqual([
+ "boolFalse",
+ "boolTrue",
+ "floatNumber",
+ "floatString",
+ "intNumber",
+ "intString",
+ "jsonInvalid",
+ "jsonNonString",
+ "jsonValid",
+ "str"
+ ]);
+
+ // get(): plain string passthrough
+ expect(options.get(k("str"))).toBe("hello");
+
+ // getJson(): valid string parses, invalid string is caught -> null, non-string -> null
+ expect(options.getJson("jsonValid")).toEqual({ a: 1 });
+ expect(options.getJson("jsonInvalid")).toBeNull();
+ expect(options.getJson("jsonNonString")).toBeNull();
+ expect(options.getJson("missing")).toBeNull();
+
+ // getInt(): number returned as-is, string parsed, unsupported -> warn + null
+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
+ expect(options.getInt(k("intNumber"))).toBe(7);
+ expect(options.getInt(k("intString"))).toBe(42);
+ expect(options.getInt(k("missing"))).toBeNull();
+ expect(warn).toHaveBeenCalledTimes(1);
+
+ // getFloat(): only strings parse, everything else -> null
+ expect(options.getFloat(k("floatString"))).toBeCloseTo(3.14);
+ expect(options.getFloat(k("floatNumber"))).toBeNull();
+ expect(options.getFloat(k("missing"))).toBeNull();
+
+ // is(): strict "true" comparison
+ expect(options.is(k("boolTrue"))).toBe(true);
+ expect(options.is(k("boolFalse"))).toBe(false);
+ });
+
+ it("set() mutates the in-memory record without touching the server", () => {
+ const put = (server.put = vi.fn(async () => ({})) as typeof server.put);
+ options.set(k("str"), "changed");
+ expect(options.get(k("str"))).toBe("changed");
+ expect(put).not.toHaveBeenCalled();
+ });
+
+ it("save() updates locally and PUTs only the changed key", async () => {
+ const put = (server.put = vi.fn(async () => ({})) as typeof server.put);
+ await options.save(k("str"), "saved");
+
+ expect(options.get(k("str"))).toBe("saved");
+ expect(put).toHaveBeenCalledWith("options", { str: "saved" });
+ });
+
+ it("saveMany() PUTs the whole record verbatim", async () => {
+ const put = (server.put = vi.fn(async () => ({})) as typeof server.put);
+ const payload = { a: "1", b: "2" } as unknown as Record<OptionNames, string>;
+ await options.saveMany(payload);
+ expect(put).toHaveBeenCalledWith("options", payload);
+ });
+
+ it("toggle() flips the boolean value and persists the negation", async () => {
+ const put = (server.put = vi.fn(async () => ({})) as typeof server.put);
+
+ options.set(k("flag"), "false");
+ await options.toggle(k("flag"));
+ expect(options.get(k("flag"))).toBe("true");
+ expect(put).toHaveBeenLastCalledWith("options", { flag: "true" });
+
+ await options.toggle(k("flag"));
+ expect(options.get(k("flag"))).toBe("false");
+ expect(put).toHaveBeenLastCalledWith("options", { flag: "false" });
+ });
+
+ it("readers tolerate an uninitialized record via optional chaining", async () => {
+ // Re-import a fresh module copy with isShare=true so the constructor takes the
+ // share branch (resolves immediately, never assigns arr).
+ vi.resetModules();
+ vi.doMock("./utils.js", async (orig) => ({
+ ...(await orig<typeof import("./utils.js")>()),
+ isShare: true
+ }));
+
+ const fresh = (await import("./options.js")).default;
+ await fresh.initializedPromise; // share branch: Promise.resolve(), arr stays undefined
+
+ expect(fresh.get(k("anything"))).toBeUndefined();
+ expect(fresh.getNames()).toEqual([]);
+ expect(fresh.getJson("anything")).toBeNull();
+
+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
+ expect(fresh.getInt(k("anything"))).toBeNull();
+ expect(warn).toHaveBeenCalledTimes(1);
+ expect(fresh.getFloat(k("anything"))).toBeNull();
+
+ vi.doUnmock("./utils.js");
+ vi.resetModules();
+ });
+});
diff --git a/apps/client/src/services/promoted_attribute_definition_parser.spec.ts b/apps/client/src/services/promoted_attribute_definition_parser.spec.ts
new file mode 100644
index 0000000000..d55dd6cf38
--- /dev/null
+++ b/apps/client/src/services/promoted_attribute_definition_parser.spec.ts
@@ -0,0 +1,55 @@
+import { describe, expect, it, vi } from "vitest";
+
+import parser, { extractAttributeDefinitionTypeAndName } from "./promoted_attribute_definition_parser.js";
+
+describe("promoted_attribute_definition_parser.parse", () => {
+ it("parses promoted, label type and multiplicity tokens (with surrounding whitespace)", () => {
+ const def = parser.parse(" promoted , number , single ");
+
+ expect(def).toEqual({
+ isPromoted: true,
+ labelType: "number",
+ multiplicity: "single"
+ });
+ });
+
+ it("accepts every supported label type and multi multiplicity", () => {
+ const labelTypes = ["text", "textarea", "number", "boolean", "date", "datetime", "time", "url", "color"];
+ for (const labelType of labelTypes) {
+ expect(parser.parse(labelType)).toEqual({ labelType });
+ }
+
+ expect(parser.parse("multi")).toEqual({ multiplicity: "multi" });
+ });
+
+ it("parses precision, alias and inverse key=value tokens", () => {
+ const def = parser.parse("precision=2,alias=foo,inverse=isChildOf");
+
+ expect(def).toEqual({
+ numberPrecision: 2,
+ promotedAlias: "foo",
+ inverseRelation: "isChildOf"
+ });
+ });
+
+ it("logs and ignores unrecognized tokens", () => {
+ const logSpy = vi.spyOn(console, "log").mockImplementation(() => {});
+ try {
+ const def = parser.parse("bogus");
+ expect(def).toEqual({});
+ expect(logSpy).toHaveBeenCalledWith("Unrecognized attribute definition token:", "bogus");
+ } finally {
+ logSpy.mockRestore();
+ }
+ });
+});
+
+describe("extractAttributeDefinitionTypeAndName", () => {
+ it("extracts the label type and strips the prefix", () => {
+ expect(extractAttributeDefinitionTypeAndName("label:TEST:TEST1")).toEqual(["label", "TEST:TEST1"]);
+ });
+
+ it("treats anything not starting with label: as a relation", () => {
+ expect(extractAttributeDefinitionTypeAndName("relation:author")).toEqual(["relation", "author"]);
+ });
+});
diff --git a/apps/client/src/services/protected_session.spec.ts b/apps/client/src/services/protected_session.spec.ts
new file mode 100644
index 0000000000..1858f5c255
--- /dev/null
+++ b/apps/client/src/services/protected_session.spec.ts
@@ -0,0 +1,324 @@
+import type { WebSocketMessage } from "@triliumnext/commons";
+import { beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
+
+// `protected_session.ts` registers two ws.subscribeToMessages handlers at
+// import time. The setup.ts global ws mock simply drops the callbacks, so we
+// override ws.js for this spec to CAPTURE them (hoisted so the factory runs
+// before any transitive load of the module under test). protected_session only
+// consumes `subscribeToMessages`; nothing else in its graph needs ws at load.
+const { messageHandlers } = vi.hoisted(() => ({
+ messageHandlers: [] as ((message: any) => Promise<void> | void)[]
+}));
+
+vi.mock("./ws.js", () => ({
+ default: {
+ subscribeToMessages(cb: (message: any) => Promise<void> | void) {
+ messageHandlers.push(cb);
+ },
+ waitForMaxKnownEntityChangeId: async () => {}
+ }
+}));
+
+import appContext from "../components/app_context.js";
+import froca from "./froca.js";
+import options from "./options.js";
+import protectedSessionHolder from "./protected_session_holder.js";
+import server from "./server.js";
+import toastService from "./toast.js";
+import utils from "./utils.js";
+
+let protectedSession: typeof import("./protected_session.js").default;
+
+function dispatch(message: any) {
+ // Both handlers are invoked for every message in production.
+ return Promise.all(messageHandlers.map((h) => h(message as WebSocketMessage)));
+}
+
+beforeAll(async () => {
+ protectedSession = (await import("./protected_session.js")).default;
+});
+
+beforeEach(() => {
+ vi.restoreAllMocks();
+ glob.isProtectedSessionAvailable = false;
+});
+
+describe("enterProtectedSession", () => {
+ it("triggers showPasswordNotSet and returns a deferred when no password is set", () => {
+ options.is = vi.fn(() => false) as typeof options.is;
+ const triggerCommand = vi.spyOn(appContext, "triggerCommand").mockReturnValue(undefined as any);
+
+ const result = protectedSession.enterProtectedSession();
+
+ expect(options.is).toHaveBeenCalledWith("isPasswordSet");
+ expect(triggerCommand).toHaveBeenCalledWith("showPasswordNotSet");
+ // returns the raw deferred (not the promise) in this branch
+ expect(typeof (result as any).promise).toBe("function");
+ });
+
+ it("resolves false immediately when a protected session is already available", async () => {
+ options.is = vi.fn(() => true) as typeof options.is;
+ protectedSessionHolder.isProtectedSessionAvailable = vi.fn(() => true);
+ const triggerCommand = vi.spyOn(appContext, "triggerCommand").mockReturnValue(undefined as any);
+
+ const result = await protectedSession.enterProtectedSession();
+
+ expect(result).toBe(false);
+ expect(triggerCommand).not.toHaveBeenCalledWith("showProtectedSessionPasswordDialog");
+ });
+
+ it("shows the password dialog and keeps the deferred pending when no session is available", () => {
+ options.is = vi.fn(() => true) as typeof options.is;
+ protectedSessionHolder.isProtectedSessionAvailable = vi.fn(() => false);
+ const triggerCommand = vi.spyOn(appContext, "triggerCommand").mockReturnValue(undefined as any);
+
+ let settled = false;
+ const promise = protectedSession.enterProtectedSession() as unknown as Promise<boolean>;
+ promise.then(() => {
+ settled = true;
+ });
+
+ expect(triggerCommand).toHaveBeenCalledWith("showProtectedSessionPasswordDialog");
+ expect(settled).toBe(false);
+ });
+});
+
+describe("leaveProtectedSession", () => {
+ it("resets the protected session when one is available", async () => {
+ protectedSessionHolder.isProtectedSessionAvailable = vi.fn(() => true);
+ protectedSessionHolder.resetProtectedSession = vi.fn(async () => {});
+
+ await protectedSession.leaveProtectedSession();
+
+ expect(protectedSessionHolder.resetProtectedSession).toHaveBeenCalled();
+ });
+
+ it("does nothing when no protected session is available", async () => {
+ protectedSessionHolder.isProtectedSessionAvailable = vi.fn(() => false);
+ protectedSessionHolder.resetProtectedSession = vi.fn(async () => {});
+
+ await protectedSession.leaveProtectedSession();
+
+ expect(protectedSessionHolder.resetProtectedSession).not.toHaveBeenCalled();
+ });
+});
+
+describe("setupProtectedSession", () => {
+ it("enables the protected session on a successful login", async () => {
+ server.post = vi.fn(async () => ({ success: true })) as typeof server.post;
+ protectedSessionHolder.enableProtectedSession = vi.fn();
+
+ await protectedSession.setupProtectedSession("secret");
+
+ expect(server.post).toHaveBeenCalledWith("login/protected", { password: "secret" });
+ expect(protectedSessionHolder.enableProtectedSession).toHaveBeenCalled();
+ });
+
+ it("shows an error and aborts on a failed login", async () => {
+ server.post = vi.fn(async () => ({ success: false })) as typeof server.post;
+ protectedSessionHolder.enableProtectedSession = vi.fn();
+ const showError = vi.spyOn(toastService, "showError").mockReturnValue(undefined as any);
+
+ await protectedSession.setupProtectedSession("wrong");
+
+ expect(showError).toHaveBeenCalled();
+ expect(protectedSessionHolder.enableProtectedSession).not.toHaveBeenCalled();
+ });
+});
+
+describe("protectNote", () => {
+ it("enters the session and PUTs the protect endpoint with subtree flags", async () => {
+ options.is = vi.fn(() => true) as typeof options.is;
+ protectedSessionHolder.isProtectedSessionAvailable = vi.fn(() => true);
+ vi.spyOn(appContext, "triggerCommand").mockReturnValue(undefined as any);
+ server.put = vi.fn(async () => ({})) as typeof server.put;
+
+ await protectedSession.protectNote("note123", true, true);
+ expect(server.put).toHaveBeenCalledWith("notes/note123/protect/1?subtree=1");
+
+ await protectedSession.protectNote("note456", false, false);
+ expect(server.put).toHaveBeenCalledWith("notes/note456/protect/0?subtree=0");
+ });
+});
+
+describe("protectedSessionLogin / logout ws handler", () => {
+ it("reloads data, fires events, resolves a pending deferred, and shows a message on login", async () => {
+ // Build a note so reloadData has something to gather/reload.
+ const note = froca.notes;
+ froca.loadInitialTree = vi.fn(async () => ({}) as any);
+ froca.reloadNotes = vi.fn(async () => {});
+ const triggerEvent = vi.spyOn(appContext, "triggerEvent").mockResolvedValue(undefined as any);
+ const triggerCommand = vi.spyOn(appContext, "triggerCommand").mockReturnValue(undefined as any);
+ const showMessage = vi.spyOn(toastService, "showMessage").mockReturnValue(undefined as any);
+
+ // Establish a pending deferred so the resolve branch is exercised.
+ options.is = vi.fn(() => true) as typeof options.is;
+ protectedSessionHolder.isProtectedSessionAvailable = vi.fn(() => false);
+ const pending = protectedSession.enterProtectedSession() as unknown as Promise<boolean>;
+
+ await dispatch({ type: "protectedSessionLogin" });
+
+ expect(froca.loadInitialTree).toHaveBeenCalled();
+ expect(froca.reloadNotes).toHaveBeenCalledWith(Object.keys(note));
+ expect(triggerEvent).toHaveBeenCalledWith("frocaReloaded", {});
+ expect(triggerEvent).toHaveBeenCalledWith("protectedSessionStarted", {});
+ expect(triggerCommand).toHaveBeenCalledWith("closeProtectedSessionPasswordDialog");
+ expect(showMessage).toHaveBeenCalled();
+
+ // The pending deferred is resolved with true by the login handler.
+ await expect(pending).resolves.toBe(true);
+ });
+
+ it("handles login when no deferred is pending", async () => {
+ froca.loadInitialTree = vi.fn(async () => ({}) as any);
+ froca.reloadNotes = vi.fn(async () => {});
+ vi.spyOn(appContext, "triggerEvent").mockResolvedValue(undefined as any);
+ vi.spyOn(appContext, "triggerCommand").mockReturnValue(undefined as any);
+ const showMessage = vi.spyOn(toastService, "showMessage").mockReturnValue(undefined as any);
+
+ await dispatch({ type: "protectedSessionLogin" });
+
+ expect(showMessage).toHaveBeenCalled();
+ });
+
+ it("reloads the frontend app on logout", async () => {
+ const reload = vi.spyOn(utils, "reloadFrontendApp").mockReturnValue(undefined as any);
+
+ await dispatch({ type: "protectedSessionLogout" });
+
+ expect(reload).toHaveBeenCalledWith("Protected session logout");
+ });
+
+ it("ignores unrelated message types", async () => {
+ froca.loadInitialTree = vi.fn(async () => ({}) as any);
+ const reload = vi.spyOn(utils, "reloadFrontendApp").mockReturnValue(undefined as any);
+
+ await dispatch({ type: "somethingElse" });
+
+ expect(froca.loadInitialTree).not.toHaveBeenCalled();
+ expect(reload).not.toHaveBeenCalled();
+ });
+});
+
+describe("protectNotes task ws handler", () => {
+ it("ignores messages without the protectNotes taskType", async () => {
+ const showError = vi.spyOn(toastService, "showError").mockReturnValue(undefined as any);
+ const showPersistent = vi.spyOn(toastService, "showPersistent").mockReturnValue(undefined as any);
+
+ await dispatch({ type: "taskError", taskType: "exportNotes", taskId: "t1", message: "x" });
+ await dispatch({ type: "taskError", taskId: "t1", message: "x" });
+
+ expect(showError).not.toHaveBeenCalled();
+ expect(showPersistent).not.toHaveBeenCalled();
+ });
+
+ it("closes the persistent toast and shows an error on taskError (protecting)", async () => {
+ const closePersistent = vi.spyOn(toastService, "closePersistent").mockReturnValue(undefined as any);
+ const showError = vi.spyOn(toastService, "showError").mockReturnValue(undefined as any);
+
+ await dispatch({
+ type: "taskError",
+ taskType: "protectNotes",
+ taskId: "task-err",
+ message: "boom",
+ data: { protect: true }
+ });
+
+ expect(closePersistent).toHaveBeenCalledWith("task-err");
+ expect(showError).toHaveBeenCalledWith("boom");
+ });
+
+ it("shows a persistent progress toast while protecting", async () => {
+ const showPersistent = vi.spyOn(toastService, "showPersistent").mockReturnValue(undefined as any);
+
+ await dispatch({
+ type: "taskProgressCount",
+ taskType: "protectNotes",
+ taskId: "task-prot",
+ progressCount: 5,
+ data: { protect: true }
+ });
+
+ expect(showPersistent).toHaveBeenCalledWith(
+ expect.objectContaining({ id: "task-prot", icon: "check-shield" })
+ );
+ });
+
+ it("shows a persistent progress toast while unprotecting", async () => {
+ const showPersistent = vi.spyOn(toastService, "showPersistent").mockReturnValue(undefined as any);
+
+ await dispatch({
+ type: "taskProgressCount",
+ taskType: "protectNotes",
+ taskId: "task-unprot",
+ progressCount: 2,
+ data: { protect: false }
+ });
+
+ expect(showPersistent).toHaveBeenCalledWith(
+ expect.objectContaining({ id: "task-unprot", icon: "shield" })
+ );
+ });
+
+ it("shows a timed success toast on taskSucceeded for both protecting and unprotecting", async () => {
+ const showPersistent = vi.spyOn(toastService, "showPersistent").mockReturnValue(undefined as any);
+
+ await dispatch({
+ type: "taskSucceeded",
+ taskType: "protectNotes",
+ taskId: "task-done",
+ data: { protect: false }
+ });
+ expect(showPersistent).toHaveBeenCalledWith(
+ expect.objectContaining({ id: "task-done", icon: "shield", timeout: 3000 })
+ );
+
+ // Protecting variant exercises the truthy side of the success-text ternary.
+ await dispatch({
+ type: "taskSucceeded",
+ taskType: "protectNotes",
+ taskId: "task-done-prot",
+ data: { protect: true }
+ });
+ expect(showPersistent).toHaveBeenCalledWith(
+ expect.objectContaining({ id: "task-done-prot", icon: "check-shield", timeout: 3000 })
+ );
+ });
+
+ it("does nothing for a protectNotes message with an unrelated type", async () => {
+ const closePersistent = vi.spyOn(toastService, "closePersistent").mockReturnValue(undefined as any);
+ const showError = vi.spyOn(toastService, "showError").mockReturnValue(undefined as any);
+ const showPersistent = vi.spyOn(toastService, "showPersistent").mockReturnValue(undefined as any);
+
+ // taskType matches but the message type is none of error/progress/succeeded:
+ // falls through all branches without producing a toast.
+ await dispatch({
+ type: "taskProgress",
+ taskType: "protectNotes",
+ taskId: "task-other",
+ data: { protect: true }
+ });
+
+ expect(closePersistent).not.toHaveBeenCalled();
+ expect(showError).not.toHaveBeenCalled();
+ expect(showPersistent).not.toHaveBeenCalled();
+ });
+
+ it("treats a message with no data as unprotecting (undefined protect) on taskError", async () => {
+ const closePersistent = vi.spyOn(toastService, "closePersistent").mockReturnValue(undefined as any);
+ const showError = vi.spyOn(toastService, "showError").mockReturnValue(undefined as any);
+
+ // No `data`: message.data?.protect short-circuits to undefined (falsy),
+ // selecting the unprotecting title. taskError never calls makeToast, so
+ // the missing `data` is safe here.
+ await dispatch({
+ type: "taskError",
+ taskType: "protectNotes",
+ taskId: "task-nodata",
+ message: "no data"
+ });
+
+ expect(closePersistent).toHaveBeenCalledWith("task-nodata");
+ expect(showError).toHaveBeenCalledWith("no data");
+ });
+});
diff --git a/apps/client/src/services/protected_session_holder.spec.ts b/apps/client/src/services/protected_session_holder.spec.ts
new file mode 100644
index 0000000000..ec974daf69
--- /dev/null
+++ b/apps/client/src/services/protected_session_holder.spec.ts
@@ -0,0 +1,64 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+import type FNote from "../entities/fnote.js";
+import protectedSessionHolder from "./protected_session_holder.js";
+import server from "./server.js";
+
+const glob = window.glob as unknown as { isProtectedSessionAvailable: boolean };
+
+function fakeNote(isProtected: boolean): FNote {
+ return { isProtected } as FNote;
+}
+
+describe("protected_session_holder", () => {
+ beforeEach(() => {
+ glob.isProtectedSessionAvailable = false;
+ server.post = vi.fn(async () => ({})) as typeof server.post;
+ });
+
+ it("isProtectedSessionAvailable reflects the glob flag", () => {
+ glob.isProtectedSessionAvailable = false;
+ expect(protectedSessionHolder.isProtectedSessionAvailable()).toBe(false);
+ glob.isProtectedSessionAvailable = true;
+ expect(protectedSessionHolder.isProtectedSessionAvailable()).toBe(true);
+ });
+
+ it("enableProtectedSession sets the flag and touches the session", async () => {
+ protectedSessionHolder.enableProtectedSession();
+ expect(protectedSessionHolder.isProtectedSessionAvailable()).toBe(true);
+ expect(server.post).toHaveBeenCalledWith("login/protected/touch");
+ });
+
+ it("resetProtectedSession posts the logout endpoint", async () => {
+ await protectedSessionHolder.resetProtectedSession();
+ expect(server.post).toHaveBeenCalledWith("logout/protected");
+ });
+
+ it("touchProtectedSession posts only when a session is available", async () => {
+ await protectedSessionHolder.touchProtectedSession();
+ expect(server.post).not.toHaveBeenCalled();
+
+ glob.isProtectedSessionAvailable = true;
+ await protectedSessionHolder.touchProtectedSession();
+ expect(server.post).toHaveBeenCalledWith("login/protected/touch");
+ });
+
+ it("touchProtectedSessionIfNecessary touches only for a protected note in an available session", () => {
+ // null note -> nothing
+ protectedSessionHolder.touchProtectedSessionIfNecessary(null);
+ expect(server.post).not.toHaveBeenCalled();
+
+ // protected note but no session -> nothing
+ protectedSessionHolder.touchProtectedSessionIfNecessary(fakeNote(true));
+ expect(server.post).not.toHaveBeenCalled();
+
+ // session available but note not protected -> nothing
+ glob.isProtectedSessionAvailable = true;
+ protectedSessionHolder.touchProtectedSessionIfNecessary(fakeNote(false));
+ expect(server.post).not.toHaveBeenCalled();
+
+ // protected note + available session -> touch
+ protectedSessionHolder.touchProtectedSessionIfNecessary(fakeNote(true));
+ expect(server.post).toHaveBeenCalledWith("login/protected/touch");
+ });
+});
diff --git a/apps/client/src/services/render.spec.tsx b/apps/client/src/services/render.spec.tsx
new file mode 100644
index 0000000000..56823c30af
--- /dev/null
+++ b/apps/client/src/services/render.spec.tsx
@@ -0,0 +1,278 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import $ from "jquery";
+
+// Control the bundle execution machinery (avoids eval / ScriptContext).
+const executeMock = vi.fn();
+vi.mock("./bundle.js", () => ({
+ executeBundleWithoutErrorHandling: (...args: unknown[]) => executeMock(...args)
+}));
+
+// Spy on the actual JSX rendering so we don't depend on Preact mounting.
+const renderAtElementMock = vi.fn();
+vi.mock("../widgets/react/react_utils.jsx", () => ({
+ renderReactWidgetAtElement: (...args: unknown[]) => renderAtElementMock(...args)
+}));
+
+import { buildNote } from "../test/easy-froca";
+import froca from "./froca.js";
+import renderDefault, { render, renderIfJsx } from "./render.js";
+import server from "./server.js";
+
+const flush = () => new Promise<void>((resolve) => setTimeout(resolve, 0));
+
+describe("render", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ // Default: a successful bundle execution resolving to nothing.
+ executeMock.mockResolvedValue(undefined);
+ server.postWithSilentInternalServerError = vi.fn(async () => ({
+ script: "",
+ html: "<p>hi</p>",
+ noteId: "scriptNote",
+ allNoteIds: []
+ })) as typeof server.postWithSilentInternalServerError;
+ });
+
+ afterEach(() => {
+ delete (glob as any).getComponentByEl;
+ });
+
+ it("default export exposes render", () => {
+ expect(renderDefault.render).toBe(render);
+ });
+
+ it("empties and hides the element when there are no renderNote relations", async () => {
+ const note = buildNote({ title: "No relations" });
+ const $el = $("<div>").append("<span>old</span>");
+
+ const result = await render(note, $el);
+
+ expect(result).toBe(false);
+ expect($el.children().length).toBe(0);
+ expect($el.css("display")).toBe("none");
+ expect(server.postWithSilentInternalServerError).not.toHaveBeenCalled();
+ });
+
+ it("ignores relations whose value is empty (filtered out)", async () => {
+ const note = buildNote({ title: "Empty value", "~renderNote": "" });
+ const $el = $("<div>");
+
+ const result = await render(note, $el);
+
+ expect(result).toBe(false);
+ expect(server.postWithSilentInternalServerError).not.toHaveBeenCalled();
+ });
+
+ it("loads, appends bundle html and executes the bundle for each render note", async () => {
+ const target = buildNote({ title: "Target" });
+ const note = buildNote({ title: "Host", "~renderNote": target.noteId });
+ const $el = $("<div>");
+
+ const result = await render(note, $el);
+
+ expect(result).toBe(true);
+ expect(server.postWithSilentInternalServerError).toHaveBeenCalledWith(`script/bundle/${target.noteId}`);
+ expect($el.css("display")).not.toBe("none");
+ // A script container div was appended and got the bundle html.
+ const $container = $el.children();
+ expect($container.length).toBe(1);
+ expect($container.html()).toContain("hi");
+ expect(executeMock).toHaveBeenCalledOnce();
+ });
+
+ it("invokes onError when the bundle could not be loaded", async () => {
+ const target = buildNote({ title: "Target2" });
+ const note = buildNote({ title: "Host2", "~renderNote": target.noteId });
+ server.postWithSilentInternalServerError = vi.fn(async () => null) as typeof server.postWithSilentInternalServerError;
+ const onError = vi.fn();
+
+ const result = await render(note, $("<div>"), onError);
+
+ // The throw is caught, so render resolves to undefined.
+ expect(result).toBeUndefined();
+ expect(onError).toHaveBeenCalledOnce();
+ expect(onError.mock.calls[0][0]).toBeInstanceOf(Error);
+ });
+
+ it("forwards bundle execution rejections to onError via catch", async () => {
+ const target = buildNote({ title: "Target3" });
+ const note = buildNote({ title: "Host3", "~renderNote": target.noteId });
+ const boom = new Error("exec failed");
+ executeMock.mockRejectedValue(boom);
+ const onError = vi.fn();
+
+ await render(note, $("<div>"), onError);
+ await flush();
+
+ expect(onError).toHaveBeenCalledWith(boom);
+ });
+
+ it("parses a JSON-shaped string error and passes the parsed object to onError", async () => {
+ const target = buildNote({ title: "Target4" });
+ const note = buildNote({ title: "Host4", "~renderNote": target.noteId });
+ server.postWithSilentInternalServerError = vi.fn(async () => {
+ throw `{"message":"nope"}`;
+ }) as typeof server.postWithSilentInternalServerError;
+ const onError = vi.fn();
+
+ await render(note, $("<div>"), onError);
+
+ expect(onError).toHaveBeenCalledWith({ message: "nope" });
+ });
+
+ it("falls back to passing the raw error when a JSON-shaped string fails to parse", async () => {
+ const target = buildNote({ title: "Target5" });
+ const note = buildNote({ title: "Host5", "~renderNote": target.noteId });
+ const bad = `{not valid json}`;
+ server.postWithSilentInternalServerError = vi.fn(async () => {
+ throw bad;
+ }) as typeof server.postWithSilentInternalServerError;
+ const onError = vi.fn();
+
+ await render(note, $("<div>"), onError);
+
+ // Inner try/catch: JSON.parse throws, the parse error is forwarded.
+ expect(onError).toHaveBeenCalledOnce();
+ expect(onError.mock.calls[0][0]).toBeInstanceOf(SyntaxError);
+ });
+
+ it("passes a non-string thrown error straight to onError", async () => {
+ const target = buildNote({ title: "Target6" });
+ const note = buildNote({ title: "Host6", "~renderNote": target.noteId });
+ const err = new Error("plain");
+ server.postWithSilentInternalServerError = vi.fn(async () => {
+ throw err;
+ }) as typeof server.postWithSilentInternalServerError;
+ const onError = vi.fn();
+
+ await render(note, $("<div>"), onError);
+
+ expect(onError).toHaveBeenCalledWith(err);
+ });
+
+ it("triggers JSX rendering when the bundle html is empty", async () => {
+ const target = buildNote({ title: "Target7", type: "code" });
+ // The root script note must be JSX for renderIfJsx to render.
+ const jsxNote = buildNote({ id: "jsxRoot", title: "JSX root" });
+ jsxNote.mime = "text/jsx";
+ const note = buildNote({ title: "Host7", "~renderNote": target.noteId });
+
+ const userComponent = () => null;
+ executeMock.mockResolvedValue(userComponent);
+ server.postWithSilentInternalServerError = vi.fn(async () => ({
+ script: "",
+ html: "",
+ noteId: "jsxRoot",
+ allNoteIds: []
+ })) as typeof server.postWithSilentInternalServerError;
+
+ const closest = { fake: "component" };
+ (glob as any).getComponentByEl = vi.fn(() => closest);
+
+ const $el = $("<div class='component'>");
+ await render(note, $el, vi.fn());
+ await flush();
+
+ expect(renderAtElementMock).toHaveBeenCalledOnce();
+ expect(renderAtElementMock.mock.calls[0][0]).toBe(closest);
+ expect(renderAtElementMock.mock.calls[0][2]).toBe($el[0]);
+ });
+});
+
+describe("renderIfJsx", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ afterEach(() => {
+ delete (glob as any).getComponentByEl;
+ });
+
+ function bundleFor(noteId: string) {
+ return { script: "", html: "", noteId, allNoteIds: [] };
+ }
+
+ it("does nothing when the root script note is not text/jsx", async () => {
+ const note = buildNote({ title: "Non-jsx" });
+ note.mime = "text/html";
+ await renderIfJsx(bundleFor(note.noteId), () => null, $("<div>"));
+ expect(renderAtElementMock).not.toHaveBeenCalled();
+ });
+
+ it("does nothing when the resolved root note is missing", async () => {
+ const originalGetNote = froca.getNote;
+ froca.getNote = vi.fn(async () => null) as typeof froca.getNote;
+ try {
+ await renderIfJsx(bundleFor("does-not-exist"), () => null, $("<div>"));
+ } finally {
+ froca.getNote = originalGetNote;
+ }
+ expect(renderAtElementMock).not.toHaveBeenCalled();
+ });
+
+ it("does nothing when the bundle result is not a function", async () => {
+ const note = buildNote({ title: "Jsx but bad result" });
+ note.mime = "text/jsx";
+ await renderIfJsx(bundleFor(note.noteId), "not a function", $("<div>"));
+ expect(renderAtElementMock).not.toHaveBeenCalled();
+ });
+
+ it("does nothing when there is no closest component", async () => {
+ const note = buildNote({ title: "Jsx no component" });
+ note.mime = "text/jsx";
+ (glob as any).getComponentByEl = vi.fn(() => null);
+ await renderIfJsx(bundleFor(note.noteId), () => null, $("<div class='component'>"));
+ expect(renderAtElementMock).not.toHaveBeenCalled();
+ });
+
+ it("renders the user component wrapped in an error boundary", async () => {
+ const note = buildNote({ title: "Jsx ok" });
+ note.mime = "text/jsx";
+ const closest = { id: "c" };
+ (glob as any).getComponentByEl = vi.fn(() => closest);
+
+ const $el = $("<div class='component'>");
+ await renderIfJsx(bundleFor(note.noteId), () => null, $el);
+
+ expect(renderAtElementMock).toHaveBeenCalledOnce();
+ const [parentComp, vnode, container] = renderAtElementMock.mock.calls[0];
+ expect(parentComp).toBe(closest);
+ expect(container).toBe($el[0]);
+ // The vnode is the UserErrorBoundary wrapping the user component.
+ expect(typeof vnode.type).toBe("function");
+ expect(vnode.type.name).toBe("UserErrorBoundary");
+ });
+
+ it("error boundary renders children normally and swallows errors via componentDidCatch", async () => {
+ const note = buildNote({ title: "Jsx boundary" });
+ note.mime = "text/jsx";
+ const closest = { id: "c2" };
+ (glob as any).getComponentByEl = vi.fn(() => closest);
+ const onError = vi.fn();
+
+ await renderIfJsx(bundleFor(note.noteId), () => null, $("<div class='component'>"), onError);
+
+ const vnode = renderAtElementMock.mock.calls[0][1];
+ const Boundary = vnode.type as new (props: object) => {
+ state: { error: unknown };
+ props: { children?: unknown };
+ setState: (s: object) => void;
+ componentDidCatch: (e: unknown) => void;
+ render: () => unknown;
+ };
+ const children = { marker: true };
+ const instance = new Boundary({ children });
+ instance.setState = (s: object) => Object.assign(instance.state, s);
+
+ // Initial state: no error -> renders children.
+ expect(instance.state.error).toBeNull();
+ expect(instance.render()).toBe(children);
+
+ // After catching an error: forwards to onError and renders null.
+ const caught = new Error("inner");
+ instance.componentDidCatch(caught);
+ expect(onError).toHaveBeenCalledWith(caught);
+ expect(instance.state.error).toBe(caught);
+ expect(instance.render()).toBeNull();
+ });
+});
diff --git a/apps/client/src/services/render.tsx b/apps/client/src/services/render.tsx
index 31450b3a82..984c2078af 100644
--- a/apps/client/src/services/render.tsx
+++ b/apps/client/src/services/render.tsx
@@ -8,7 +8,7 @@ import server from "./server.js";
type ErrorHandler = (e: unknown) => void;
-async function render(note: FNote, $el: JQuery<HTMLElement>, onError?: ErrorHandler) {
+export async function render(note: FNote, $el: JQuery<HTMLElement>, onError?: ErrorHandler) {
const relations = note.getRelations("renderNote");
const renderNoteIds = relations.map((rel) => rel.value).filter((noteId) => noteId);
@@ -52,7 +52,7 @@ async function render(note: FNote, $el: JQuery<HTMLElement>, onError?: ErrorHand
}
}
-async function renderIfJsx(bundle: Bundle, result: unknown, $el: JQuery<HTMLElement>, onError?: ErrorHandler) {
+export async function renderIfJsx(bundle: Bundle, result: unknown, $el: JQuery<HTMLElement>, onError?: ErrorHandler) {
// Ensure the root script note is actually a JSX.
const rootScriptNoteId = await froca.getNote(bundle.noteId);
if (rootScriptNoteId?.mime !== "text/jsx") return;
diff --git a/apps/client/src/services/resizer.spec.ts b/apps/client/src/services/resizer.spec.ts
new file mode 100644
index 0000000000..9af6d6db90
--- /dev/null
+++ b/apps/client/src/services/resizer.spec.ts
@@ -0,0 +1,348 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import $ from "jquery";
+
+import Split from "@triliumnext/split.js";
+
+// Replace the Split.js library with a controllable test double so we can assert
+// on the options passed and exercise the onDragEnd callbacks without needing
+// real layout (happy-dom has none).
+vi.mock("@triliumnext/split.js", () => ({
+ default: vi.fn(() => ({ destroy: vi.fn() }))
+}));
+
+const SplitMock = Split as unknown as ReturnType<typeof vi.fn>;
+
+// A manual requestAnimationFrame queue: callbacks are NOT run automatically, so
+// we can flush them on demand and exercise the cancelAnimationFrame branch.
+let rafCallbacks: Map<number, FrameRequestCallback>;
+let rafNextId: number;
+let cancelledRafIds: number[];
+
+function flushRaf() {
+ const pending = [...rafCallbacks.entries()];
+ rafCallbacks.clear();
+ for (const [, cb] of pending) {
+ cb(0);
+ }
+}
+
+/** Force `$("#right-pane").is(":visible")` to a chosen value (no layout in happy-dom). */
+function setRightPaneVisible(visible: boolean) {
+ const origIs = ($ as any).fn.is;
+ return vi.spyOn(($ as any).fn, "is").mockImplementation(function (this: any, sel: any, ...rest: any[]) {
+ if (sel === ":visible") {
+ return visible;
+ }
+ return origIs.call(this, sel, ...rest);
+ });
+}
+
+/**
+ * Load a fresh copy of resizer.ts (its module-level state is otherwise a
+ * singleton that never resets) with options.get/getInt stubbed to the supplied
+ * values.
+ */
+async function loadResizer(opts: { layoutOrientation?: string; leftPaneWidth?: number | null; rightPaneWidth?: number | null } = {}) {
+ vi.resetModules();
+ const optionsModule = (await import("./options.js")).default;
+ optionsModule.get = vi.fn((key) => (key === "layoutOrientation" ? (opts.layoutOrientation ?? "horizontal") : "")) as typeof optionsModule.get;
+ optionsModule.getInt = vi.fn((key) => {
+ if (key === "leftPaneWidth") return opts.leftPaneWidth ?? null;
+ if (key === "rightPaneWidth") return opts.rightPaneWidth ?? null;
+ return null;
+ }) as typeof optionsModule.getInt;
+ optionsModule.save = vi.fn(async () => {}) as typeof optionsModule.save;
+ const resizer = (await import("./resizer.js")).default;
+ return { resizer, options: optionsModule };
+}
+
+beforeEach(() => {
+ rafCallbacks = new Map();
+ rafNextId = 0;
+ cancelledRafIds = [];
+ globalThis.requestAnimationFrame = ((cb: FrameRequestCallback) => {
+ const id = ++rafNextId;
+ rafCallbacks.set(id, cb);
+ return id;
+ }) as typeof globalThis.requestAnimationFrame;
+ globalThis.cancelAnimationFrame = ((id: number) => {
+ cancelledRafIds.push(id);
+ rafCallbacks.delete(id);
+ }) as typeof globalThis.cancelAnimationFrame;
+ SplitMock.mockClear();
+ SplitMock.mockImplementation(() => ({ destroy: vi.fn() }));
+ document.body.innerHTML = `
+ <div id="launcher-pane"></div>
+ <div id="left-pane"></div>
+ <div id="rest-pane"></div>
+ <div id="center-pane">
+ <div class="split-note-container-widget"></div>
+ </div>
+ <div id="right-pane"></div>`;
+});
+
+afterEach(() => {
+ vi.restoreAllMocks();
+});
+
+describe("setupLeftPaneResizer", () => {
+ it("when left pane is hidden, stretches rest pane to full width (horizontal layout, no reserved width)", async () => {
+ const { resizer } = await loadResizer({ layoutOrientation: "horizontal" });
+
+ resizer.setupLeftPaneResizer(false);
+
+ expect($("#left-pane").is(":hidden") || $("#left-pane").css("display") === "none").toBe(true);
+ expect($("#rest-pane").css("width")).toBe("100%");
+ expect(SplitMock).not.toHaveBeenCalled();
+ });
+
+ it("when left pane is hidden in vertical layout, reserves launcher-pane width", async () => {
+ const { resizer } = await loadResizer({ layoutOrientation: "vertical" });
+
+ resizer.setupLeftPaneResizer(false);
+
+ // launcher-pane outerWidth() is 0 in happy-dom (no layout) -> reservedWidth 0 -> 100%.
+ expect($("#rest-pane").css("width")).toBe("100%");
+ });
+
+ it("when left pane is visible, creates a Split via requestAnimationFrame and persists drag results", async () => {
+ const destroy = vi.fn();
+ SplitMock.mockImplementation(() => ({ destroy }));
+ const { resizer, options } = await loadResizer({ layoutOrientation: "horizontal", leftPaneWidth: 30 });
+
+ resizer.setupLeftPaneResizer(true);
+ // Split is only created once the rAF callback runs.
+ expect(SplitMock).not.toHaveBeenCalled();
+ flushRaf();
+
+ expect(SplitMock).toHaveBeenCalledTimes(1);
+ const [elements, config] = SplitMock.mock.calls[0];
+ expect(elements).toEqual(["#left-pane", "#rest-pane"]);
+ expect(config.sizes).toEqual([30, 70]);
+ expect(config.gutterSize).toBe(5);
+ expect(config.minSize).toEqual([150, 300]);
+
+ // onDragEnd rounds and saves the new left pane width.
+ config.onDragEnd([42.6, 57.4]);
+ expect(options.save).toHaveBeenCalledWith("leftPaneWidth", 43);
+ });
+
+ it("clamps a missing stored width (getInt -> null) up to the minimum of 5", async () => {
+ const { resizer } = await loadResizer({ layoutOrientation: "horizontal", leftPaneWidth: null });
+
+ resizer.setupLeftPaneResizer(true);
+ flushRaf();
+
+ // getInt returns null -> falls back to 0 -> clamped to the 5 minimum.
+ expect(SplitMock.mock.calls[0][1].sizes).toEqual([5, 95]);
+ });
+
+ it("clamps a too-small stored width (e.g. 2) up to the minimum of 5", async () => {
+ const { resizer } = await loadResizer({ layoutOrientation: "horizontal", leftPaneWidth: 2 });
+
+ resizer.setupLeftPaneResizer(true);
+ flushRaf();
+
+ expect(SplitMock.mock.calls[0][1].sizes).toEqual([5, 95]);
+ });
+
+ it("destroys the previous Split instance when re-invoked", async () => {
+ const destroy = vi.fn();
+ SplitMock.mockImplementation(() => ({ destroy }));
+ const { resizer } = await loadResizer({ layoutOrientation: "horizontal", leftPaneWidth: 30 });
+
+ resizer.setupLeftPaneResizer(true);
+ flushRaf();
+ expect(destroy).not.toHaveBeenCalled();
+
+ // Second invocation must tear down the existing instance before rebuilding.
+ resizer.setupLeftPaneResizer(true);
+ expect(destroy).toHaveBeenCalledTimes(1);
+ flushRaf();
+ expect(SplitMock).toHaveBeenCalledTimes(2);
+ });
+
+ it("reuses cached layout/width state on subsequent calls instead of re-reading options", async () => {
+ const { resizer, options } = await loadResizer({ layoutOrientation: "horizontal", leftPaneWidth: 30 });
+
+ resizer.setupLeftPaneResizer(true);
+ flushRaf();
+ const getCallsAfterFirst = (options.get as ReturnType<typeof vi.fn>).mock.calls.length;
+ const getIntCallsAfterFirst = (options.getInt as ReturnType<typeof vi.fn>).mock.calls.length;
+
+ resizer.setupLeftPaneResizer(true);
+ flushRaf();
+
+ // layoutOrientation / leftPaneWidth are cached after the first call (?? short-circuits).
+ expect((options.get as ReturnType<typeof vi.fn>).mock.calls.length).toBe(getCallsAfterFirst);
+ expect((options.getInt as ReturnType<typeof vi.fn>).mock.calls.length).toBe(getIntCallsAfterFirst);
+ });
+});
+
+describe("setupRightPaneResizer", () => {
+ it("when right pane is hidden, stretches center pane to full width", async () => {
+ const isSpy = setRightPaneVisible(false);
+ const { resizer } = await loadResizer();
+
+ resizer.setupRightPaneResizer();
+
+ expect($("#center-pane").css("width")).toBe("100%");
+ expect(SplitMock).not.toHaveBeenCalled();
+ isSpy.mockRestore();
+ });
+
+ it("when right pane is visible, creates a Split and persists drag results", async () => {
+ const isSpy = setRightPaneVisible(true);
+ const { resizer, options } = await loadResizer({ rightPaneWidth: 25 });
+
+ resizer.setupRightPaneResizer();
+
+ expect(SplitMock).toHaveBeenCalledTimes(1);
+ const [elements, config] = SplitMock.mock.calls[0];
+ expect(elements).toEqual(["#center-pane", "#right-pane"]);
+ expect(config.sizes).toEqual([75, 25]);
+ expect(config.minSize).toEqual([300, 180]);
+
+ config.onDragEnd([60.2, 39.8]);
+ expect(options.save).toHaveBeenCalledWith("rightPaneWidth", 40);
+ isSpy.mockRestore();
+ });
+
+ it("clamps an undefined/too-small right pane width up to 5 and destroys a previous instance", async () => {
+ const isSpy = setRightPaneVisible(true);
+ const destroy = vi.fn();
+ SplitMock.mockImplementation(() => ({ destroy }));
+ const { resizer } = await loadResizer({ rightPaneWidth: null });
+
+ resizer.setupRightPaneResizer();
+ expect(SplitMock.mock.calls[0][1].sizes).toEqual([95, 5]);
+ expect(destroy).not.toHaveBeenCalled();
+
+ resizer.setupRightPaneResizer();
+ expect(destroy).toHaveBeenCalledTimes(1);
+ expect(SplitMock).toHaveBeenCalledTimes(2);
+ isSpy.mockRestore();
+ });
+});
+
+describe("note split resizers", () => {
+ function panel(ntxId: string) {
+ const el = document.createElement("div");
+ el.className = "note-split";
+ el.setAttribute("data-ntx-id", ntxId);
+ return el;
+ }
+
+ function seedPanels(container: Element, ...ntxIds: string[]) {
+ for (const id of ntxIds) {
+ container.appendChild(panel(id));
+ }
+ }
+
+ it("setupNoteSplitResizer creates a Split for a brand-new group of ntx ids", async () => {
+ const { resizer } = await loadResizer();
+ const container = document.querySelector(".split-note-container-widget")!;
+ seedPanels(container, "a1", "a2");
+ // A stray .note-split without a data-ntx-id attribute must be ignored (the
+ // null attribute falls back to "" and fails the includes() filter).
+ const stray = document.createElement("div");
+ stray.className = "note-split";
+ container.appendChild(stray);
+
+ resizer.setupNoteSplitResizer(["a1", "a2"]);
+ flushRaf();
+
+ expect(SplitMock).toHaveBeenCalledTimes(1);
+ const [panels, config] = SplitMock.mock.calls[0];
+ expect(panels.map((p: HTMLElement) => p.getAttribute("data-ntx-id"))).toEqual(["a1", "a2"]);
+ expect(config.minSize).toBe(150);
+ expect(config.gutterSize).toBe(5);
+ });
+
+ it("setupNoteSplitResizer merges new ntx ids into an existing matching group and rebuilds", async () => {
+ const destroy = vi.fn();
+ SplitMock.mockImplementation(() => ({ destroy }));
+ const { resizer } = await loadResizer();
+ const container = document.querySelector(".split-note-container-widget")!;
+ seedPanels(container, "b1", "b2", "b3");
+
+ resizer.setupNoteSplitResizer(["b1", "b2"]);
+ flushRaf();
+ expect(SplitMock).toHaveBeenCalledTimes(1);
+
+ // "b1" already belongs to a group; "b3" is new and should be appended to it.
+ resizer.setupNoteSplitResizer(["b1", "b3"]);
+ // Previous instance for the group is destroyed before rebuilding.
+ expect(destroy).toHaveBeenCalledTimes(1);
+ flushRaf();
+ expect(SplitMock).toHaveBeenCalledTimes(2);
+ expect(SplitMock.mock.calls[1][0].map((p: HTMLElement) => p.getAttribute("data-ntx-id"))).toEqual(["b1", "b2", "b3"]);
+ });
+
+ it("createSplitInstance cancels a still-pending rAF for the same group before scheduling a new one", async () => {
+ const { resizer } = await loadResizer();
+ const container = document.querySelector(".split-note-container-widget")!;
+ seedPanels(container, "c1", "c2");
+
+ // First scheduling leaves a pending rAF (we don't flush).
+ resizer.setupNoteSplitResizer(["c1", "c2"]);
+ // Second scheduling for the overlapping group should cancel the first rAF.
+ resizer.setupNoteSplitResizer(["c1"]);
+ expect(cancelledRafIds.length).toBe(1);
+
+ flushRaf();
+ expect(SplitMock).toHaveBeenCalledTimes(1);
+ });
+
+ it("moveNoteSplitResizer rebuilds an existing group and is a no-op for an unknown ntx id", async () => {
+ const destroy = vi.fn();
+ SplitMock.mockImplementation(() => ({ destroy }));
+ const { resizer } = await loadResizer();
+ const container = document.querySelector(".split-note-container-widget")!;
+ seedPanels(container, "d1", "d2");
+
+ resizer.setupNoteSplitResizer(["d1", "d2"]);
+ flushRaf();
+
+ resizer.moveNoteSplitResizer("d1");
+ expect(destroy).toHaveBeenCalledTimes(1);
+ flushRaf();
+ expect(SplitMock).toHaveBeenCalledTimes(2);
+
+ // Unknown ntx id -> early return, no extra Split / destroy.
+ resizer.moveNoteSplitResizer("does-not-exist");
+ flushRaf();
+ expect(SplitMock).toHaveBeenCalledTimes(2);
+ expect(destroy).toHaveBeenCalledTimes(1);
+ });
+
+ it("delNoteSplitResizer removes ids, rebuilds when >= 2 remain, drops the group otherwise, and ignores unknown ids", async () => {
+ const destroy = vi.fn();
+ SplitMock.mockImplementation(() => ({ destroy }));
+ const { resizer } = await loadResizer();
+ const container = document.querySelector(".split-note-container-widget")!;
+ seedPanels(container, "e1", "e2", "e3");
+
+ resizer.setupNoteSplitResizer(["e1", "e2", "e3"]);
+ flushRaf();
+ expect(SplitMock).toHaveBeenCalledTimes(1);
+
+ // Removing one id from a 3-member group leaves 2 -> rebuild.
+ resizer.delNoteSplitResizer(["e3"]);
+ expect(destroy).toHaveBeenCalledTimes(1);
+ flushRaf();
+ expect(SplitMock).toHaveBeenCalledTimes(2);
+ expect(SplitMock.mock.calls[1][0].map((p: HTMLElement) => p.getAttribute("data-ntx-id"))).toEqual(["e1", "e2"]);
+
+ // Removing another leaves only 1 -> group is dropped, no rebuild.
+ resizer.delNoteSplitResizer(["e2"]);
+ expect(destroy).toHaveBeenCalledTimes(2);
+ flushRaf();
+ expect(SplitMock).toHaveBeenCalledTimes(2);
+
+ // Unknown id -> early return.
+ resizer.delNoteSplitResizer(["totally-unknown"]);
+ flushRaf();
+ expect(SplitMock).toHaveBeenCalledTimes(2);
+ });
+});
diff --git a/apps/client/src/services/resizer.ts b/apps/client/src/services/resizer.ts
index 93cb5c1b0a..af2fb77e15 100644
--- a/apps/client/src/services/resizer.ts
+++ b/apps/client/src/services/resizer.ts
@@ -37,6 +37,7 @@ function setupLeftPaneResizer(leftPaneVisible: boolean) {
}
const restPaneWidth = 100 - leftPaneWidth - reservedWidth;
+ /* v8 ignore next -- redundant guard: a falsy leftPaneVisible already returned above */
if (leftPaneVisible) {
// Delayed initialization ensures that all DOM elements are fully rendered and part of the layout,
// preventing Split.js from retrieving incorrect dimensions due to #left-pane not being rendered yet,
@@ -75,6 +76,7 @@ function setupRightPaneResizer() {
rightPaneWidth = 5;
}
+ /* v8 ignore next -- redundant guard: a falsy rightPaneVisible already returned above */
if (rightPaneVisible) {
rightInstance = Split(["#center-pane", "#right-pane"], {
sizes: [100 - rightPaneWidth, rightPaneWidth],
diff --git a/apps/client/src/services/script_context.spec.ts b/apps/client/src/services/script_context.spec.ts
new file mode 100644
index 0000000000..716911e121
--- /dev/null
+++ b/apps/client/src/services/script_context.spec.ts
@@ -0,0 +1,59 @@
+import { describe, expect, it, vi } from "vitest";
+
+import { buildNote } from "../test/easy-froca";
+import ScriptContext from "./script_context.js";
+import server from "./server.js";
+
+describe("ScriptContext", () => {
+ it("builds notes/apis maps and resolves modules via require", async () => {
+ const startNote = buildNote({ title: "Start" });
+ const moduleA = buildNote({ title: "ModuleA" });
+ const moduleB = buildNote({ title: "ModuleB" });
+
+ const allNoteIds = [startNote.noteId, moduleA.noteId, moduleB.noteId];
+ const ctx = await ScriptContext(startNote.noteId, allNoteIds);
+
+ // modules starts empty, notes/apis are keyed by noteId for every requested note.
+ expect(ctx.modules).toEqual({});
+ expect(Object.keys(ctx.notes).sort()).toEqual([...allNoteIds].sort());
+ expect(Object.keys(ctx.apis).sort()).toEqual([...allNoteIds].sort());
+ expect(ctx.notes[moduleA.noteId]).toBe(moduleA);
+ // Each api is a FrontendScriptApi instance referencing the right current note.
+ expect(ctx.apis[moduleA.noteId].currentNote).toBe(moduleA);
+ expect(ctx.apis[moduleA.noteId].startNote).toBe(startNote);
+
+ // require: the returned function resolves a module note by title and returns its exports.
+ const exportsA = { value: 42 };
+ ctx.modules[moduleA.noteId] = { exports: exportsA };
+ const requireFn = ctx.require(`${moduleA.noteId} ${moduleB.noteId}`);
+ expect(requireFn("ModuleA")).toBe(exportsA);
+ });
+
+ it("require throws when the requested module title is not among the allowed note ids", async () => {
+ const startNote = buildNote({ title: "Start2" });
+ const moduleA = buildNote({ title: "ModA2" });
+ const otherNote = buildNote({ title: "Other2" });
+
+ const ctx = await ScriptContext(startNote.noteId, [startNote.noteId, moduleA.noteId, otherNote.noteId]);
+
+ // moduleNoteIds only allows moduleA, so requesting "Other2" (filtered out) throws.
+ const requireFn = ctx.require(moduleA.noteId);
+ expect(() => requireFn("Other2")).toThrow(/Could not find module note Other2/);
+ // Requesting a title that exists nowhere also throws.
+ expect(() => requireFn("Nonexistent")).toThrow(/Could not find module note Nonexistent/);
+ });
+
+ it("throws when the start note cannot be found", async () => {
+ // Make froca's "tree/load" resolve with an empty subtree so the unknown note id
+ // simply stays missing (instead of the setup mock throwing on the POST).
+ const originalPost = server.post;
+ server.post = vi.fn(async () => ({ notes: [], branches: [], attributes: [] })) as typeof server.post;
+ try {
+ await expect(ScriptContext("missingStartNoteId", ["missingStartNoteId"])).rejects.toThrow(
+ /Could not find start note missingStartNoteId\./
+ );
+ } finally {
+ server.post = originalPost;
+ }
+ });
+});
diff --git a/apps/client/src/services/search.spec.ts b/apps/client/src/services/search.spec.ts
new file mode 100644
index 0000000000..214c10978e
--- /dev/null
+++ b/apps/client/src/services/search.spec.ts
@@ -0,0 +1,42 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+import { buildNote } from "../test/easy-froca";
+import searchService from "./search.js";
+import server from "./server.js";
+
+describe("search service", () => {
+ beforeEach(() => {
+ vi.restoreAllMocks();
+ });
+
+ it("searchForNoteIds encodes the search string in the URL and returns the server result", async () => {
+ const get = vi.fn(async () => ["id1", "id2"]);
+ server.get = get as typeof server.get;
+
+ const result = await searchService.searchForNoteIds("a b & #c");
+
+ expect(get).toHaveBeenCalledWith(`search/${encodeURIComponent("a b & #c")}`);
+ expect(result).toEqual(["id1", "id2"]);
+ });
+
+ it("searchForNotes resolves the returned ids into froca notes", async () => {
+ const noteA = buildNote({ title: "Note A" });
+ const noteB = buildNote({ title: "Note B" });
+
+ const get = vi.fn(async () => [noteA.noteId, noteB.noteId]);
+ server.get = get as typeof server.get;
+
+ const notes = await searchService.searchForNotes("query");
+
+ expect(get).toHaveBeenCalledWith(`search/${encodeURIComponent("query")}`);
+ expect(notes.map((n) => n.noteId)).toEqual([noteA.noteId, noteB.noteId]);
+ });
+
+ it("searchForNotes returns an empty array when no ids match", async () => {
+ server.get = vi.fn(async () => []) as typeof server.get;
+
+ const notes = await searchService.searchForNotes("nothing");
+
+ expect(notes).toEqual([]);
+ });
+});
diff --git a/apps/client/src/services/server.spec.ts b/apps/client/src/services/server.spec.ts
new file mode 100644
index 0000000000..c7a9b67515
--- /dev/null
+++ b/apps/client/src/services/server.spec.ts
@@ -0,0 +1,420 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+// Toggleable flag backing the `isShare` named export of ./utils.js.
+let isShareValue = false;
+
+// Partially mock utils so we keep the real helpers but can flip `isShare` per test.
+vi.mock("./utils.js", async (orig) => {
+ const actual = (await orig()) as any;
+ return {
+ ...actual,
+ default: {
+ ...actual.default,
+ localNowDateTime: () => "2026-05-29 12:00:00.000+0000"
+ },
+ get isShare() {
+ return isShareValue;
+ }
+ };
+});
+
+// Keep i18n predictable (the test env never initialises i18next).
+vi.mock("./i18n.js", () => ({
+ t: (key: string, opts?: Record<string, unknown>) => (opts ? `${key}:${JSON.stringify(opts)}` : key)
+}));
+
+// Avoid pulling in app_context (toast → app_context → options → server) on the
+// dynamic import inside reportError.
+const toastMock = {
+ showError: vi.fn(),
+ showPersistent: vi.fn(),
+ showErrorTitleAndMessage: vi.fn()
+};
+vi.mock("./toast.js", () => ({ default: toastMock }));
+
+// The target file (server.ts) is GLOBALLY mocked by test/setup.ts. Import the
+// REAL implementation so we exercise actual code rather than the canned stub.
+const serverModule = (await vi.importActual("./server.js")) as {
+ default: typeof import("./server.js").default;
+};
+const server = serverModule.default;
+
+type AjaxOptions = JQueryAjaxSettings & {
+ success: (body: unknown, textStatus: string, jqXhr: any) => void;
+ error: (jqXhr: any) => void | Promise<void>;
+};
+
+function fakeJqXhr(headerLines: string) {
+ return {
+ getAllResponseHeaders: () => headerLines
+ };
+}
+
+beforeEach(() => {
+ isShareValue = false;
+ vi.clearAllMocks();
+ (window as any).glob = {
+ isMainWindow: true,
+ componentId: "comp-glob",
+ csrfToken: "csrf-1",
+ baseApiUrl: "/api/",
+ appContext: undefined
+ };
+ (window as any).logError = vi.fn();
+});
+
+describe("getHeaders", () => {
+ it("returns the full header set with active note context", async () => {
+ (window as any).glob.appContext = {
+ tabManager: { getActiveContext: () => ({ hoistedNoteId: "hoisted-1" }) }
+ };
+ const headers = await server.getHeaders({ "x-extra": "value", "x-empty": "" });
+ expect(headers).toMatchObject({
+ "trilium-component-id": "comp-glob",
+ "trilium-local-now-datetime": "2026-05-29 12:00:00.000+0000",
+ "trilium-hoisted-note-id": "hoisted-1",
+ "x-csrf-token": "csrf-1",
+ "x-extra": "value"
+ });
+ // falsy custom header values are skipped
+ expect(headers).not.toHaveProperty("x-empty");
+ });
+
+ it("uses null hoisted note id when there is no active context", async () => {
+ (window as any).glob.appContext = { tabManager: { getActiveContext: () => null } };
+ const headers = await server.getHeaders();
+ expect(headers["trilium-hoisted-note-id"]).toBeNull();
+ });
+
+ it("uses null hoisted note id when tabManager is absent", async () => {
+ (window as any).glob.appContext = {};
+ const headers = await server.getHeaders();
+ expect(headers["trilium-hoisted-note-id"]).toBeNull();
+ });
+
+ it("returns an empty object in share mode", async () => {
+ isShareValue = true;
+ const headers = await server.getHeaders({ "x-extra": "value" });
+ expect(headers).toEqual({});
+ });
+});
+
+describe("call / ajax success paths", () => {
+ it("parses response headers and tracks the max entity change id (GET)", async () => {
+ const ajaxSpy = vi.fn((opts: AjaxOptions) => {
+ opts.success(
+ { ok: true },
+ "success",
+ fakeJqXhr("trilium-max-entity-change-id: 42\r\nContent-Type: application/json: charset=utf-8\r\nBad-Line-Without-Colon")
+ );
+ });
+ (window as any).$.ajax = ajaxSpy;
+
+ const result = await server.get<{ ok: boolean }>("some/url", "comp-x");
+ expect(result).toEqual({ ok: true });
+ expect(ajaxSpy.mock.calls[0][0].url).toBe("/api/some/url");
+ expect(ajaxSpy.mock.calls[0][0].type).toBe("GET");
+ expect(server.getMaxKnownEntityChangeId()).toBeGreaterThanOrEqual(42);
+ });
+
+ it("does not advance the max entity change id for a blank header", async () => {
+ const before = server.getMaxKnownEntityChangeId();
+ (window as any).$.ajax = (opts: AjaxOptions) => {
+ opts.success({}, "success", fakeJqXhr("trilium-max-entity-change-id: "));
+ };
+ await server.get("blank/header");
+ expect(server.getMaxKnownEntityChangeId()).toBe(before);
+ });
+
+ it("sets dataType=text for raw GET and serialises POST data with content type", async () => {
+ let rawOpts: AjaxOptions | undefined;
+ let postOpts: AjaxOptions | undefined;
+
+ (window as any).$.ajax = (opts: AjaxOptions) => {
+ if (opts.type === "GET") {
+ rawOpts = opts;
+ } else {
+ postOpts = opts;
+ }
+ opts.success("body", "success", fakeJqXhr(""));
+ };
+
+ await server.get("raw/url", undefined, true);
+ await server.post("post/url", { a: 1 });
+
+ expect(rawOpts?.dataType).toBe("text");
+ expect(postOpts?.data).toBe(JSON.stringify({ a: 1 }));
+ expect(postOpts?.contentType).toBe("application/json");
+ });
+
+ it("logs and skips data when it cannot be stringified", async () => {
+ const logSpy = vi.spyOn(console, "log").mockImplementation(() => {});
+ const circular: any = {};
+ circular.self = circular; // JSON.stringify throws on circular refs
+
+ let captured: AjaxOptions | undefined;
+ (window as any).$.ajax = (opts: AjaxOptions) => {
+ captured = opts;
+ opts.success({}, "success", fakeJqXhr(""));
+ };
+
+ await server.post("post/url", circular);
+ expect(captured?.data).toBeUndefined();
+ expect(captured?.contentType).toBe("application/json");
+ expect(logSpy).toHaveBeenCalled();
+ logSpy.mockRestore();
+ });
+
+ it("supports put, patch and remove verbs", async () => {
+ const seen: string[] = [];
+ (window as any).$.ajax = (opts: AjaxOptions) => {
+ seen.push(opts.type as string);
+ opts.success({}, "success", fakeJqXhr(""));
+ };
+
+ await server.put("put/url", { x: 1 });
+ await server.patch("patch/url", { x: 1 });
+ await server.remove("del/url");
+
+ expect(seen).toEqual(["PUT", "PATCH", "DELETE"]);
+ });
+});
+
+describe("ajax error handling", () => {
+ it("rejects browser-cancelled requests (status 0) without reporting", async () => {
+ (window as any).$.ajax = (opts: AjaxOptions) => {
+ opts.error({ status: 0, responseText: "" });
+ };
+ await expect(server.get("url")).rejects.toBe("rejected by browser");
+ expect(toastMock.showError).not.toHaveBeenCalled();
+ });
+
+ it("stays silent on 404 when silentNotFound is set", async () => {
+ (window as any).$.ajax = (opts: AjaxOptions) => {
+ opts.error({ status: 404, responseText: "{}" });
+ };
+ await expect(server.getWithSilentNotFound("url")).rejects.toBeDefined();
+ expect(toastMock.showError).not.toHaveBeenCalled();
+ expect((window as any).logError).not.toHaveBeenCalled();
+ });
+
+ it("stays silent on 500 when silentInternalServerError is set", async () => {
+ (window as any).$.ajax = (opts: AjaxOptions) => {
+ opts.error({ status: 500, responseText: "boom" });
+ };
+ await expect(server.postWithSilentInternalServerError("url", {})).rejects.toBeDefined();
+ expect((window as any).logError).not.toHaveBeenCalled();
+ });
+
+ it("reports validation errors (400) and still rejects when reportError throws", async () => {
+ (window as any).$.ajax = (opts: AjaxOptions) => {
+ opts.error({ status: 400, responseText: JSON.stringify({ message: "Bad input" }) });
+ };
+ await expect(server.post("url", {})).rejects.toBeDefined();
+ expect(toastMock.showError).toHaveBeenCalledWith("Bad input");
+ });
+
+ it("shows a traefik-blocked toast for encoded-character 400s", async () => {
+ (window as any).$.ajax = (opts: AjaxOptions) => {
+ // string response (not an object) -> falls through to the else branch
+ opts.error({ status: 400, responseText: "plain error" });
+ };
+ await expect(server.get("notes/foo%23bar")).rejects.toBeDefined();
+ expect(toastMock.showPersistent).toHaveBeenCalledWith(
+ expect.objectContaining({ id: "trafik-blocked" })
+ );
+ expect((window as any).logError).toHaveBeenCalled();
+ });
+
+ it("shows a traefik-blocked toast for %2F-encoded 400s", async () => {
+ (window as any).$.ajax = (opts: AjaxOptions) => {
+ opts.error({ status: 400, responseText: "plain error" });
+ };
+ await expect(server.get("notes/foo%2Fbar")).rejects.toBeDefined();
+ expect(toastMock.showPersistent).toHaveBeenCalledWith(
+ expect.objectContaining({ id: "trafik-blocked" })
+ );
+ });
+
+ it("falls back to the '-' placeholder when the message is an empty string", async () => {
+ (window as any).$.ajax = (opts: AjaxOptions) => {
+ // valid JSON object with an empty message -> messageStr resolves to "-"
+ opts.error({ status: 400, responseText: JSON.stringify({ message: "" }) });
+ };
+ await expect(server.post("url", {})).rejects.toBeDefined();
+ expect(toastMock.showError).toHaveBeenCalledWith("-");
+ });
+
+ it("shows a generic error toast for other status codes", async () => {
+ (window as any).$.ajax = (opts: AjaxOptions) => {
+ opts.error({ status: 503, responseText: JSON.stringify({ message: "Down" }) });
+ };
+ await expect(server.get("plain/url")).rejects.toBeDefined();
+ expect(toastMock.showErrorTitleAndMessage).toHaveBeenCalled();
+ expect((window as any).logError).toHaveBeenCalled();
+ });
+
+ it("falls back to a JSON-stringified message when the response is not a string", async () => {
+ (window as any).$.ajax = (opts: AjaxOptions) => {
+ // object responseText with no message -> messageStr derives from JSON.stringify
+ opts.error({ status: 503, responseText: { detail: "object-body" } });
+ };
+ await expect(server.get("obj/url")).rejects.toBeDefined();
+ expect(toastMock.showErrorTitleAndMessage).toHaveBeenCalled();
+ });
+});
+
+describe("CSRF token handling", () => {
+ it("isCsrfError returns true only for 403 with the invalid-token message", async () => {
+ // Drive isCsrfError through the retry path: a 403 that IS a csrf error triggers refresh + retry.
+ const fetchMock = vi.fn(async () => ({
+ ok: true,
+ json: async () => ({ csrfToken: "fresh-token" })
+ }));
+ (window as any).fetch = fetchMock;
+ (window as any).location = { search: "?x=1" } as any;
+
+ let attempt = 0;
+ (window as any).$.ajax = (opts: AjaxOptions) => {
+ attempt++;
+ if (attempt === 1) {
+ opts.error({ status: 403, responseText: JSON.stringify({ message: "Invalid CSRF token" }) });
+ } else {
+ opts.success({ retried: true }, "success", fakeJqXhr(""));
+ }
+ };
+
+ const result = await server.get<{ retried: boolean }>("retry/url");
+ expect(result).toEqual({ retried: true });
+ expect(fetchMock).toHaveBeenCalledWith("./bootstrap?x=1", { cache: "no-store" });
+ expect((window as any).glob.csrfToken).toBe("fresh-token");
+ expect(attempt).toBe(2);
+ });
+
+ it("does not retry when the 403 is not a csrf error (bad json / wrong message)", async () => {
+ (window as any).$.ajax = (opts: AjaxOptions) => {
+ // unparseable body -> isCsrfError catch -> false
+ opts.error({ status: 403, responseText: "<<not json>>" });
+ };
+ await expect(server.get("noretry/url")).rejects.toBeDefined();
+ expect(toastMock.showErrorTitleAndMessage).toHaveBeenCalled();
+ });
+
+ it("rejects when the retried request itself fails", async () => {
+ (window as any).fetch = vi.fn(async () => ({ ok: false, json: async () => ({}) }));
+ (window as any).location = { search: "" } as any;
+
+ let attempt = 0;
+ (window as any).$.ajax = (opts: AjaxOptions) => {
+ attempt++;
+ if (attempt === 1) {
+ opts.error({ status: 403, responseText: JSON.stringify({ message: "Invalid CSRF token" }) });
+ } else {
+ // retried request rejects via browser-cancel (status 0 short-circuit)
+ opts.error({ status: 0, responseText: "" });
+ }
+ };
+
+ await expect(server.get("retry-fail/url")).rejects.toBe("rejected by browser");
+ expect(attempt).toBe(2);
+ });
+
+ it("coalesces concurrent csrf refreshes into a single bootstrap fetch", async () => {
+ let resolveFetch: (v: any) => void = () => {};
+ const fetchMock = vi.fn(
+ () =>
+ new Promise((res) => {
+ resolveFetch = res;
+ })
+ );
+ (window as any).fetch = fetchMock;
+ (window as any).location = { search: "" } as any;
+
+ const ajaxCalls: AjaxOptions[] = [];
+ (window as any).$.ajax = (opts: AjaxOptions) => {
+ ajaxCalls.push(opts);
+ if (ajaxCalls.length <= 2) {
+ opts.error({ status: 403, responseText: JSON.stringify({ message: "Invalid CSRF token" }) });
+ } else {
+ opts.success({ done: true }, "success", fakeJqXhr(""));
+ }
+ };
+
+ const p1 = server.get("c1");
+ const p2 = server.get("c2");
+ // wait until both requests have errored and triggered the (single) in-flight bootstrap
+ while (fetchMock.mock.calls.length === 0) {
+ await new Promise((r) => setTimeout(r, 0));
+ }
+ resolveFetch({ ok: true, json: async () => ({ csrfToken: "shared" }) });
+ await Promise.all([p1, p2]);
+
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ expect((window as any).glob.csrfToken).toBe("shared");
+ });
+});
+
+describe("upload", () => {
+ function makeFile() {
+ return new File(["data"], "f.txt", { type: "text/plain" });
+ }
+
+ it("uploads via $.ajax with the default PUT method and component header", async () => {
+ const ajaxSpy = vi.fn(async (opts: any) => ({ uploaded: true, opts }));
+ (window as any).$.ajax = ajaxSpy;
+
+ const res = (await server.upload("upload/url", makeFile(), "comp-up")) as any;
+ expect(res.uploaded).toBe(true);
+ const opts = ajaxSpy.mock.calls[0][0];
+ expect(opts.url).toBe("/api/upload/url");
+ expect(opts.type).toBe("PUT");
+ expect(opts.contentType).toBe(false);
+ expect(opts.processData).toBe(false);
+ expect(opts.headers["trilium-component-id"]).toBe("comp-up");
+ });
+
+ it("uploads with default headers when no componentId is given", async () => {
+ const ajaxSpy = vi.fn(async (opts: any) => ({ ok: true, opts }));
+ (window as any).$.ajax = ajaxSpy;
+ await server.upload("upload/url", makeFile(), undefined, "POST");
+ const opts = ajaxSpy.mock.calls[0][0];
+ expect(opts.type).toBe("POST");
+ // default headers fall back to glob.componentId
+ expect(opts.headers["trilium-component-id"]).toBe("comp-glob");
+ });
+
+ it("refreshes the csrf token and retries once on a csrf upload failure", async () => {
+ (window as any).fetch = vi.fn(async () => ({ ok: true, json: async () => ({ csrfToken: "up-fresh" }) }));
+ (window as any).location = { search: "" } as any;
+
+ let attempt = 0;
+ (window as any).$.ajax = vi.fn(async () => {
+ attempt++;
+ if (attempt === 1) {
+ const err: any = { status: 403, responseText: JSON.stringify({ message: "Invalid CSRF token" }) };
+ throw err;
+ }
+ return { retried: true };
+ });
+
+ const res = (await server.upload("upload/url", makeFile())) as any;
+ expect(res.retried).toBe(true);
+ expect(attempt).toBe(2);
+ expect((window as any).glob.csrfToken).toBe("up-fresh");
+ });
+
+ it("rethrows non-csrf upload failures", async () => {
+ (window as any).$.ajax = vi.fn(async () => {
+ const err: any = { status: 500, responseText: "server error" };
+ throw err;
+ });
+ await expect(server.upload("upload/url", makeFile())).rejects.toMatchObject({ status: 500 });
+ });
+
+ it("rethrows when the rejection carries no status", async () => {
+ (window as any).$.ajax = vi.fn(async () => {
+ throw "string failure";
+ });
+ await expect(server.upload("upload/url", makeFile())).rejects.toBe("string failure");
+ });
+});
diff --git a/apps/client/src/services/shortcuts.spec.ts b/apps/client/src/services/shortcuts.spec.ts
index c8f2d9b643..9214d82f6a 100644
--- a/apps/client/src/services/shortcuts.spec.ts
+++ b/apps/client/src/services/shortcuts.spec.ts
@@ -1,6 +1,7 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-import shortcuts, { isIMEComposing, keyMatches, matchesShortcut } from "./shortcuts.js";
+import shortcuts, { type Handler, isIMEComposing, keyMatches, matchesShortcut, removeIndividualBinding } from "./shortcuts.js";
+import utils from "./utils.js";
// Mock utils module
vi.mock("./utils.js", () => ({
@@ -165,6 +166,13 @@ describe("shortcuts", () => {
expect(matchesShortcut(event, "a")).toBe(false);
});
+ it("should not match when the main key differs", () => {
+ // Valid shortcut format but the pressed key ("b") does not match the
+ // shortcut's key ("a"), so keyMatches returns false (line 175 true branch -> 176).
+ const event = createKeyboardEvent({ key: "b", code: "KeyB", ctrlKey: true });
+ expect(matchesShortcut(event, "ctrl+a")).toBe(false);
+ });
+
it("should not match when no modifiers are used", () => {
const event = createKeyboardEvent({ key: "a", code: "KeyA" });
expect(matchesShortcut(event, "a")).toBe(false);
@@ -322,36 +330,82 @@ describe("shortcuts", () => {
});
describe("event handling", () => {
- it.skip("should call handler when shortcut matches", () => {
+ it("should call handler when shortcut matches", () => {
const handler = vi.fn();
shortcuts.bindGlobalShortcut("ctrl+a", handler, "test-namespace");
- // Get the listener that was registered
- expect(mockElement.addEventListener.mock.calls).toHaveLength(1);
const [, listener] = mockElement.addEventListener.mock.calls[0];
- // First verify that matchesShortcut works directly
- const testEvent = {
- type: "keydown",
+ // Real KeyboardEvent so `evt instanceof KeyboardEvent` is true and the
+ // handler/preventDefault/stopPropagation path (lines 106-109) executes.
+ const testEvent = new KeyboardEvent("keydown", {
key: "a",
code: "KeyA",
- ctrlKey: true,
- altKey: false,
- shiftKey: false,
- metaKey: false,
- preventDefault: vi.fn(),
- stopPropagation: vi.fn()
- } as any;
-
- // Test matchesShortcut directly first
- expect(matchesShortcut(testEvent, "ctrl+a")).toBe(true);
+ ctrlKey: true
+ });
+ const preventDefault = vi.spyOn(testEvent, "preventDefault");
+ const stopPropagation = vi.spyOn(testEvent, "stopPropagation");
- // Now test the actual listener
listener(testEvent);
- expect(handler).toHaveBeenCalled();
- expect(testEvent.preventDefault).toHaveBeenCalled();
- expect(testEvent.stopPropagation).toHaveBeenCalled();
+ expect(handler).toHaveBeenCalledWith(testEvent);
+ expect(preventDefault).toHaveBeenCalled();
+ expect(stopPropagation).toHaveBeenCalled();
+ });
+
+ it("should not call handler while IME is composing", () => {
+ const handler = vi.fn();
+ shortcuts.bindGlobalShortcut("ctrl+a", handler, "test-namespace");
+
+ const [, listener] = mockElement.addEventListener.mock.calls[0];
+
+ // isComposing true short-circuits before matchesShortcut (lines 102-103).
+ const event = new KeyboardEvent("keydown", {
+ key: "a",
+ code: "KeyA",
+ ctrlKey: true
+ });
+ Object.defineProperty(event, "isComposing", { value: true });
+
+ listener(event);
+
+ expect(handler).not.toHaveBeenCalled();
+ });
+
+ it("should not call handler for a real KeyboardEvent that does not match", () => {
+ const handler = vi.fn();
+ shortcuts.bindGlobalShortcut("ctrl+a", handler, "test-namespace");
+
+ const [, listener] = mockElement.addEventListener.mock.calls[0];
+
+ // A real KeyboardEvent that passes the type/instance/IME guards but fails
+ // matchesShortcut, exercising the false branch of line 106.
+ const event = new KeyboardEvent("keydown", {
+ key: "b",
+ code: "KeyB",
+ ctrlKey: true
+ });
+ const preventDefault = vi.spyOn(event, "preventDefault");
+
+ listener(event);
+
+ expect(handler).not.toHaveBeenCalled();
+ expect(preventDefault).not.toHaveBeenCalled();
+ });
+
+ it("should not call handler for keydown events that are not KeyboardEvents", () => {
+ const handler = vi.fn();
+ shortcuts.bindGlobalShortcut("ctrl+a", handler, "test-namespace");
+
+ const [, listener] = mockElement.addEventListener.mock.calls[0];
+
+ // type is "keydown" but the object is a plain Event, exercising the
+ // second operand of `evt.type !== 'keydown' || !(evt instanceof KeyboardEvent)`.
+ const event = new Event("keydown");
+
+ listener(event);
+
+ expect(handler).not.toHaveBeenCalled();
});
it("should not call handler for non-keyboard events", () => {
@@ -427,4 +481,100 @@ describe("shortcuts", () => {
expect(isIMEComposing(undefined as any)).toBe(false);
});
});
+
+ describe("removeIndividualBinding", () => {
+ // bindElShortcut returns the created ShortcutBinding; bindGlobalShortcut returns void.
+ const bind = (shortcut: string, handler: Handler, namespace?: string) =>
+ shortcuts.bindElShortcut([mockElement] as any, shortcut, handler, namespace)!;
+
+ it("should remove the event listener and drop the binding from its namespace", () => {
+ const handler = vi.fn();
+ const binding = bind("ctrl+a", handler, "test-namespace");
+
+ expect(binding).toBeTruthy();
+
+ removeIndividualBinding(binding);
+
+ expect(mockElement.removeEventListener).toHaveBeenCalledWith("keydown", binding.listener);
+ });
+
+ it("should default to the 'global' namespace when binding has no namespace", () => {
+ // Bind without a namespace so binding.namespace is null and the `?? "global"`
+ // fallback (line 136) is exercised, plus the activeBindings.has(key) true branch.
+ const handler = vi.fn();
+ const first = bind("ctrl+a", handler);
+ const second = bind("ctrl+b", handler);
+
+ expect(first.namespace).toBeNull();
+ expect(second.namespace).toBeNull();
+
+ removeIndividualBinding(first);
+
+ expect(mockElement.removeEventListener).toHaveBeenCalledWith("keydown", first.listener);
+ });
+
+ it("should be a no-op when no bindings exist for the namespace", () => {
+ // Fabricate a binding for a namespace that has never been registered so
+ // `activeBindings.get(key)` is undefined (false branch of line 138).
+ const binding = {
+ element: mockElement as any,
+ shortcut: "ctrl+z",
+ handler: vi.fn(),
+ namespace: "never-registered",
+ listener: vi.fn()
+ };
+
+ expect(() => removeIndividualBinding(binding)).not.toThrow();
+ expect(mockElement.removeEventListener).toHaveBeenCalledWith("keydown", binding.listener);
+ });
+ });
+
+ describe("non-desktop behavior", () => {
+ it("should not bind shortcuts when not on desktop", () => {
+ const isDesktopSpy = vi.spyOn(utils, "isDesktop").mockReturnValue(false);
+ try {
+ const handler = vi.fn();
+ const result = shortcuts.bindGlobalShortcut("ctrl+a", handler, "test-namespace");
+
+ expect(result).toBeUndefined();
+ expect(mockElement.addEventListener).not.toHaveBeenCalled();
+ } finally {
+ isDesktopSpy.mockRestore();
+ }
+ });
+ });
+
+ describe("matchesShortcut empty-key guard", () => {
+ it("should warn and return false when the key part is only whitespace", () => {
+ const consoleSpy = vi.spyOn(console, "warn").mockImplementation(() => {});
+ const event = { key: "a", code: "KeyA" } as KeyboardEvent;
+
+ // "ctrl+ " splits to ["ctrl", " "]; key is " " so !key is false but
+ // key.trim() === '' is true, covering the second operand of line 169.
+ expect(matchesShortcut(event, "ctrl+ ")).toBe(false);
+
+ expect(consoleSpy).toHaveBeenCalled();
+ consoleSpy.mockRestore();
+ });
+ });
+
+ describe("keyMatches code fallbacks", () => {
+ it("should match a mapped special key by its code when key differs", () => {
+ // "space" maps to [" ", "Space"]; matching via e.code === "Space" exercises
+ // the `mappedKeys.includes(e.code)` fallback on line 206.
+ expect(keyMatches({ key: "Unidentified", code: "Space" } as KeyboardEvent, "space")).toBe(true);
+ });
+
+ it("should match an Alt+letter by key when the code does not match", () => {
+ // altKey true, code mismatched, but e.key matches — covers the second
+ // operand of line 221.
+ expect(keyMatches({ key: "a", code: "Unidentified", altKey: true } as KeyboardEvent, "a")).toBe(true);
+ });
+
+ it("should match a regular key by its code as a fallback", () => {
+ // Not a mapped key, not a digit, not a single a-z letter, so it falls
+ // through to line 227 and matches via e.code.
+ expect(keyMatches({ key: "Unidentified", code: "Comma" } as KeyboardEvent, "comma")).toBe(true);
+ });
+ });
});
diff --git a/apps/client/src/services/spaced_update.spec.ts b/apps/client/src/services/spaced_update.spec.ts
index ab649f3435..5ee74f27f4 100644
--- a/apps/client/src/services/spaced_update.spec.ts
+++ b/apps/client/src/services/spaced_update.spec.ts
@@ -84,4 +84,145 @@ describe("SpacedUpdate", () => {
expect(updater).toHaveBeenCalledTimes(2);
});
+
+ describe("updateNowIfNecessary", () => {
+ it("calls updater and emits saving/saved states when there are pending changes", async () => {
+ const states: string[] = [];
+ const updater = vi.fn(async () => {});
+ const spacedUpdate = new SpacedUpdate(updater, 50, (s) => states.push(s));
+
+ // Mark as changed without triggering the timer-based update.
+ spacedUpdate.scheduleUpdate();
+
+ await spacedUpdate.updateNowIfNecessary();
+
+ expect(updater).toHaveBeenCalledTimes(1);
+ expect(states).toEqual(["unsaved", "saving", "saved"]);
+ });
+
+ it("does nothing when there are no pending changes", async () => {
+ const updater = vi.fn(async () => {});
+ const spacedUpdate = new SpacedUpdate(updater, 50);
+
+ await spacedUpdate.updateNowIfNecessary();
+
+ expect(updater).not.toHaveBeenCalled();
+ });
+
+ it("re-marks changed, emits error and rethrows when the updater fails", async () => {
+ const states: string[] = [];
+ let shouldFail = true;
+ const updater = vi.fn(async () => {
+ if (shouldFail) {
+ throw new Error("boom");
+ }
+ });
+ const spacedUpdate = new SpacedUpdate(updater, 50, (s) => states.push(s));
+
+ spacedUpdate.scheduleUpdate();
+
+ await expect(spacedUpdate.updateNowIfNecessary()).rejects.toThrow("boom");
+ expect(states).toEqual(["unsaved", "saving", "error"]);
+
+ // changed flag restored -> a subsequent successful flush runs the updater again
+ shouldFail = false;
+ await spacedUpdate.updateNowIfNecessary();
+ expect(updater).toHaveBeenCalledTimes(2);
+ });
+ });
+
+ describe("isAllSavedAndTriggerUpdate", () => {
+ it("returns false and flushes pending changes when there are changes", async () => {
+ const updater = vi.fn(async () => {});
+ const spacedUpdate = new SpacedUpdate(updater, 50);
+
+ spacedUpdate.scheduleUpdate();
+
+ expect(spacedUpdate.isAllSavedAndTriggerUpdate()).toBe(false);
+
+ await vi.runAllTimersAsync();
+ expect(updater).toHaveBeenCalledTimes(1);
+ });
+
+ it("returns true when nothing is pending", () => {
+ const updater = vi.fn(async () => {});
+ const spacedUpdate = new SpacedUpdate(updater, 50);
+
+ expect(spacedUpdate.isAllSavedAndTriggerUpdate()).toBe(true);
+ expect(updater).not.toHaveBeenCalled();
+ });
+ });
+
+ describe("resetUpdateTimer / setUpdateInterval", () => {
+ it("resetUpdateTimer defers the update past the new last-updated time", async () => {
+ const updater = vi.fn(async () => {});
+ const spacedUpdate = new SpacedUpdate(updater, 50);
+
+ spacedUpdate.scheduleUpdate();
+ // Keep resetting the timer so the interval never elapses.
+ await vi.advanceTimersByTimeAsync(40);
+ spacedUpdate.resetUpdateTimer();
+ await vi.advanceTimersByTimeAsync(40);
+ spacedUpdate.resetUpdateTimer();
+ await vi.advanceTimersByTimeAsync(40);
+
+ // Still within the interval since the last reset -> no update yet.
+ expect(updater).not.toHaveBeenCalled();
+
+ // Now let the interval fully elapse.
+ await vi.advanceTimersByTimeAsync(60);
+ expect(updater).toHaveBeenCalledTimes(1);
+ });
+
+ it("setUpdateInterval changes how long before the update fires", async () => {
+ const updater = vi.fn(async () => {});
+ const spacedUpdate = new SpacedUpdate(updater, 50);
+
+ spacedUpdate.setUpdateInterval(500);
+ spacedUpdate.scheduleUpdate();
+
+ // Past the old interval but not the new one.
+ await vi.advanceTimersByTimeAsync(100);
+ expect(updater).not.toHaveBeenCalled();
+
+ await vi.advanceTimersByTimeAsync(500);
+ expect(updater).toHaveBeenCalledTimes(1);
+ });
+ });
+
+ describe("allowUpdateWithoutChange", () => {
+ it("suppresses scheduleUpdate while the callback runs and re-enables it afterwards", async () => {
+ const updater = vi.fn(async () => {});
+ const spacedUpdate = new SpacedUpdate(updater, 50);
+
+ await spacedUpdate.allowUpdateWithoutChange(async () => {
+ // scheduleUpdate is a no-op while change is forbidden.
+ spacedUpdate.scheduleUpdate();
+ });
+
+ await vi.runAllTimersAsync();
+ expect(updater).not.toHaveBeenCalled();
+
+ // After the callback, scheduling works again.
+ spacedUpdate.scheduleUpdate();
+ await vi.runAllTimersAsync();
+ expect(updater).toHaveBeenCalledTimes(1);
+ });
+
+ it("re-enables scheduling even when the callback throws", async () => {
+ const updater = vi.fn(async () => {});
+ const spacedUpdate = new SpacedUpdate(updater, 50);
+
+ await expect(
+ spacedUpdate.allowUpdateWithoutChange(async () => {
+ throw new Error("callback failed");
+ })
+ ).rejects.toThrow("callback failed");
+
+ // changeForbidden was reset in finally -> scheduling works.
+ spacedUpdate.scheduleUpdate();
+ await vi.runAllTimersAsync();
+ expect(updater).toHaveBeenCalledTimes(1);
+ });
+ });
});
diff --git a/apps/client/src/services/sync.spec.ts b/apps/client/src/services/sync.spec.ts
new file mode 100644
index 0000000000..8ff26fb067
--- /dev/null
+++ b/apps/client/src/services/sync.spec.ts
@@ -0,0 +1,99 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+vi.mock("./toast.js", () => ({
+ default: {
+ showMessage: vi.fn(),
+ showError: vi.fn()
+ }
+}));
+
+// Make t() return the key + the interpolation options so we can assert on the
+// message that is passed through, without relying on translated strings.
+vi.mock("./i18n.js", () => ({
+ t: vi.fn((key: string, opts?: Record<string, unknown>) => ({ key, opts }))
+}));
+
+import { t } from "./i18n.js";
+import server from "./server.js";
+import syncService from "./sync.js";
+import toastService from "./toast.js";
+
+const showMessage = toastService.showMessage as ReturnType<typeof vi.fn>;
+const showError = toastService.showError as ReturnType<typeof vi.fn>;
+const translate = t as unknown as ReturnType<typeof vi.fn>;
+
+interface SyncResult {
+ success: boolean;
+ message: string;
+ errorCode?: string;
+}
+
+function stubPost(result: SyncResult) {
+ server.post = vi.fn(async () => result) as typeof server.post;
+}
+
+describe("syncNow", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it("shows a success message and posts to sync/now on success", async () => {
+ stubPost({ success: true, message: "" });
+
+ await syncService.syncNow();
+
+ expect(server.post).toHaveBeenCalledWith("sync/now");
+ expect(showMessage).toHaveBeenCalledTimes(1);
+ expect(showError).not.toHaveBeenCalled();
+ });
+
+ it("shows an error with the full message on failure", async () => {
+ stubPost({ success: false, message: "boom" });
+
+ await syncService.syncNow();
+
+ expect(showMessage).not.toHaveBeenCalled();
+ expect(showError).toHaveBeenCalledTimes(1);
+ // The failure message is interpolated into the i18n key; assert it carried the original text.
+ expect(translate).toHaveBeenCalledWith("sync.failed", { message: "boom" });
+ });
+
+ it("truncates failure messages longer than 200 characters", async () => {
+ const longMessage = "x".repeat(250);
+ stubPost({ success: false, message: longMessage });
+
+ await syncService.syncNow();
+
+ expect(showError).toHaveBeenCalledTimes(1);
+ const interpolated = translate.mock.calls.find(([key]) => key === "sync.failed");
+ expect(interpolated).toBeDefined();
+ const message = (interpolated![1] as { message: string }).message;
+ expect(message).toBe("x".repeat(200) + "...");
+ expect(message.length).toBe(203);
+ });
+
+ it("suppresses the error when not configured and ignoreNotConfigured is true", async () => {
+ stubPost({ success: false, message: "no config", errorCode: "NOT_CONFIGURED" });
+
+ await syncService.syncNow(true);
+
+ expect(showError).not.toHaveBeenCalled();
+ expect(showMessage).not.toHaveBeenCalled();
+ });
+
+ it("still shows the error when not configured but ignoreNotConfigured is false", async () => {
+ stubPost({ success: false, message: "no config", errorCode: "NOT_CONFIGURED" });
+
+ await syncService.syncNow(false);
+
+ expect(showError).toHaveBeenCalledTimes(1);
+ });
+
+ it("shows the error when ignoreNotConfigured is true but error is not NOT_CONFIGURED", async () => {
+ stubPost({ success: false, message: "other failure", errorCode: "OTHER" });
+
+ await syncService.syncNow(true);
+
+ expect(showError).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/apps/client/src/services/syntax_highlight.spec.ts b/apps/client/src/services/syntax_highlight.spec.ts
new file mode 100644
index 0000000000..e3a143604c
--- /dev/null
+++ b/apps/client/src/services/syntax_highlight.spec.ts
@@ -0,0 +1,448 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+// Mutable control state shared by the hoisted mock factories below.
+// `vi.hoisted` runs before the hoisted `vi.mock` factories, so they may read it.
+const ctrl = vi.hoisted(() => ({
+ isShare: false,
+ // highlight.js stubs are reset per test by reassigning these fns.
+}));
+
+// Partial-mock ./utils so we can flip `isShare` (a const in the target, read
+// here through a live getter at call time) while keeping the rest of the real
+// module intact (options.ts also imports `isShare` from here).
+vi.mock("./utils.js", async (orig) => {
+ const actual = (await orig()) as Record<string, unknown>;
+ return {
+ ...actual,
+ get isShare() {
+ return ctrl.isShare;
+ }
+ };
+});
+
+// Stub the heavy highlight.js bundle. The real implementation dynamically
+// imports CSS-as-raw and language modules, which don't resolve under vitest and
+// are not the unit under test. We assert the orchestration logic instead.
+const hl = vi.hoisted(() => ({
+ ensureMimeTypes: vi.fn(async (_types: unknown) => {}),
+ loadTheme: vi.fn(async (_theme: unknown) => {}),
+ highlight: vi.fn((_text: string, _opts: { language: string }) => ({ value: "HL" }) as { value: string } | null),
+ highlightAuto: vi.fn((_text: string) => ({ value: "AUTO" }) as { value: string } | null)
+}));
+
+vi.mock("@triliumnext/highlightjs", () => {
+ const Themes = {
+ default: { name: "Original (Light)", load: async () => ({ default: "" }) },
+ vs: { name: "Visual Studio (Light)", load: async () => ({ default: "" }) },
+ agate: { name: "Agate (Dark)", load: async () => ({ default: "" }) }
+ };
+ return {
+ Themes,
+ ensureMimeTypes: (t: unknown) => hl.ensureMimeTypes(t),
+ loadTheme: (t: unknown) => hl.loadTheme(t),
+ highlight: (text: string, opts: { language: string }) => hl.highlight(text, opts),
+ highlightAuto: (text: string) => hl.highlightAuto(text)
+ };
+});
+
+// Imports AFTER the vi.mock calls (which are hoisted above imports anyway).
+import type OptionsType from "./options.js";
+
+type SyntaxHighlightModule = typeof import("./syntax_highlight.js");
+
+// The fresh module copy binds to a fresh `options` singleton; we must drive THAT
+// instance, so freshModule returns it alongside the syntax-highlight module.
+let currentOptions: typeof OptionsType;
+
+/**
+ * Each scenario uses a fresh module copy so the module-level `highlightingLoaded`
+ * and `colorSchemeListenerRegistered` flags + the highlight cache start clean.
+ */
+async function freshModule(): Promise<SyntaxHighlightModule> {
+ vi.resetModules();
+ currentOptions = (await import("./options.js")).default;
+ return (await import("./syntax_highlight.js")) as SyntaxHighlightModule;
+}
+
+function setOptions(values: Record<string, string>) {
+ currentOptions.load(values);
+}
+
+// formatCodeBlocks fires applySingleBlockSyntaxHighlight without awaiting it, so
+// the (async) highlight completes on later microtasks. Flush a few rounds.
+async function flush() {
+ for (let i = 0; i < 5; i++) {
+ await Promise.resolve();
+ }
+}
+
+function $codeBlock(html: string, lang?: string) {
+ const $pre = $("<pre>");
+ const $code = $("<code>").text(html);
+ if (lang) {
+ $code.addClass(`language-${lang}`);
+ }
+ $pre.append($code);
+ $("<div>").append($pre); // give the <pre> a parent for button append
+ return $code;
+}
+
+describe("syntax_highlight", () => {
+ beforeEach(() => {
+ ctrl.isShare = false;
+ (window as any).glob = { isMainWindow: true }; // device is undefined (not "print")
+ hl.ensureMimeTypes.mockClear().mockImplementation(async () => {});
+ hl.loadTheme.mockClear().mockImplementation(async () => {});
+ hl.highlight.mockClear().mockImplementation(() => ({ value: "HL" }));
+ hl.highlightAuto.mockClear().mockImplementation(() => ({ value: "AUTO" }));
+ // matchMedia is required by the color-scheme listener.
+ (window as any).matchMedia = vi.fn(() => ({
+ matches: false,
+ addEventListener: vi.fn(),
+ removeEventListener: vi.fn()
+ }));
+ });
+
+ describe("isSyntaxHighlightEnabled / getEffectiveCodeBlockTheme", () => {
+ it("uses codeBlockTheme when not matching the app, treating empty/none as disabled", async () => {
+ const mod = await freshModule();
+ setOptions({ codeBlockThemeMatchesApp: "false", codeBlockTheme: "default:vs" });
+ expect(mod.isSyntaxHighlightEnabled()).toBe(true);
+
+ setOptions({ codeBlockThemeMatchesApp: "false", codeBlockTheme: "none" });
+ expect(mod.isSyntaxHighlightEnabled()).toBe(false);
+
+ setOptions({ codeBlockThemeMatchesApp: "false", codeBlockTheme: "" });
+ expect(mod.isSyntaxHighlightEnabled()).toBe(false);
+ });
+
+ it("uses the dark/light theme option when matching the app appearance", async () => {
+ const mod = await freshModule();
+ setOptions({
+ codeBlockThemeMatchesApp: "true",
+ codeBlockThemeDark: "default:agate",
+ codeBlockThemeLight: "default:vs"
+ });
+
+ // dark
+ (window as any).matchMedia = vi.fn(() => ({ matches: true, addEventListener: vi.fn() }));
+ (window as any).glob = { isMainWindow: true, theme: "auto" };
+ expect(mod.isSyntaxHighlightEnabled()).toBe(true);
+
+ // light
+ (window as any).matchMedia = vi.fn(() => ({ matches: false, addEventListener: vi.fn() }));
+ expect(mod.isSyntaxHighlightEnabled()).toBe(true);
+ });
+
+ it("is always enabled in share mode (isShare branch)", async () => {
+ const mod = await freshModule();
+ ctrl.isShare = true;
+ expect(mod.isSyntaxHighlightEnabled()).toBe(true);
+ });
+ });
+
+ describe("loadHighlightingTheme", () => {
+ it("uses the vs theme when printing", async () => {
+ const mod = await freshModule();
+ (window as any).glob = { device: "print" };
+ await mod.loadHighlightingTheme("default:agate");
+ expect(hl.loadTheme).toHaveBeenCalledWith(expect.objectContaining({ name: "Visual Studio (Light)" }));
+ });
+
+ it("resolves a default-prefixed theme name", async () => {
+ const mod = await freshModule();
+ await mod.loadHighlightingTheme("default:agate");
+ expect(hl.loadTheme).toHaveBeenCalledWith(expect.objectContaining({ name: "Agate (Dark)" }));
+ });
+
+ it("falls back to the default theme when name is unprefixed", async () => {
+ const mod = await freshModule();
+ await mod.loadHighlightingTheme("unknown-theme");
+ expect(hl.loadTheme).toHaveBeenCalledWith(expect.objectContaining({ name: "Original (Light)" }));
+ });
+ });
+
+ describe("ensureMimeTypesForHighlighting", () => {
+ it("loads theme + all mime types on first call, then short-circuits", async () => {
+ const mod = await freshModule();
+ setOptions({ codeBlockThemeMatchesApp: "false", codeBlockTheme: "default:vs", codeNotesMimeTypes: "[]" });
+
+ await mod.ensureMimeTypesForHighlighting();
+ expect(hl.loadTheme).toHaveBeenCalledTimes(1);
+ // getMimeTypes() returns the full dictionary (an array).
+ expect(Array.isArray(hl.ensureMimeTypes.mock.calls[0][0])).toBe(true);
+
+ // second call with no hint and highlightingLoaded -> early return
+ await mod.ensureMimeTypesForHighlighting();
+ expect(hl.loadTheme).toHaveBeenCalledTimes(1);
+ expect(hl.ensureMimeTypes).toHaveBeenCalledTimes(1);
+ });
+
+ it("passes a single synthesized mime type when given a hint", async () => {
+ const mod = await freshModule();
+ setOptions({ codeBlockThemeMatchesApp: "false", codeBlockTheme: "default:vs" });
+
+ await mod.ensureMimeTypesForHighlighting("text-css");
+ expect(hl.ensureMimeTypes).toHaveBeenCalledWith([
+ { title: "text-css", enabled: true, mime: "text/css" }
+ ]);
+ // a hint always proceeds past the early return even when already loaded
+ await mod.ensureMimeTypesForHighlighting("text-x-csrc");
+ expect(hl.ensureMimeTypes).toHaveBeenLastCalledWith([
+ { title: "text-x-csrc", enabled: true, mime: "text/x-csrc" }
+ ]);
+ });
+ });
+
+ describe("applySingleBlockSyntaxHighlight", () => {
+ it("highlights a specific language and caches the result", async () => {
+ const mod = await freshModule();
+ setOptions({ codeBlockThemeMatchesApp: "false", codeBlockTheme: "default:vs" });
+ const $a = $codeBlock("const x = 1;", "text-css");
+ await mod.applySingleBlockSyntaxHighlight($a, "text-css");
+ expect($a.html()).toBe("HL");
+ expect($a.parent().hasClass("hljs")).toBe(true);
+
+ // second block, same (language, text) -> served from cache, no re-highlight
+ hl.highlight.mockClear();
+ const $b = $codeBlock("const x = 1;", "text-css");
+ await mod.applySingleBlockSyntaxHighlight($b, "text-css");
+ expect($b.html()).toBe("HL");
+ expect(hl.highlight).not.toHaveBeenCalled();
+ });
+
+ it("uses highlightAuto for the auto mime type when not in share mode", async () => {
+ const mod = await freshModule();
+ const $a = $codeBlock("auto code", "text-x-trilium-auto");
+ await mod.applySingleBlockSyntaxHighlight($a, "text-x-trilium-auto");
+ expect(hl.highlightAuto).toHaveBeenCalledWith("auto code");
+ expect($a.html()).toBe("AUTO");
+ });
+
+ it("swallows highlight errors and leaves content untouched", async () => {
+ const mod = await freshModule();
+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
+ hl.highlight.mockImplementation(() => {
+ throw new Error("boom");
+ });
+ const $a = $codeBlock("broken", "text-x-csrc");
+ await mod.applySingleBlockSyntaxHighlight($a, "text-x-csrc");
+ expect(warn).toHaveBeenCalled();
+ expect($a.html()).toBe("broken"); // unchanged, nothing cached/applied
+ });
+
+ it("does nothing extra when highlight returns null", async () => {
+ const mod = await freshModule();
+ hl.highlight.mockImplementation(() => null);
+ const $a = $codeBlock("noresult", "text-x-csrc");
+ await mod.applySingleBlockSyntaxHighlight($a, "text-x-csrc");
+ expect($a.html()).toBe("noresult");
+ });
+
+ it("does not highlight when the mime type is empty", async () => {
+ const mod = await freshModule();
+ const $a = $codeBlock("nolang");
+ await mod.applySingleBlockSyntaxHighlight($a, "");
+ expect(hl.highlight).not.toHaveBeenCalled();
+ expect(hl.highlightAuto).not.toHaveBeenCalled();
+ expect($a.html()).toBe("nolang");
+ });
+ });
+
+ describe("copy buttons", () => {
+ it("appends a copy button that copies via toast when not in share mode", async () => {
+ const mod = await freshModule();
+ const $code = $codeBlock("copy me");
+ mod.applyCopyToClipboardButton($code);
+ const $btn = $code.parent().find("button.copy-button");
+ expect($btn.length).toBe(1);
+ // exercise the click handler (non-share path)
+ $btn.trigger("click");
+ });
+
+ it("copy button uses the plain copy path in share mode", async () => {
+ const mod = await freshModule();
+ ctrl.isShare = true;
+ const $code = $codeBlock("share copy");
+ mod.applyCopyToClipboardButton($code);
+ $code.parent().find("button.copy-button").trigger("click");
+ });
+
+ it("inline code copy adds class + handler for both share and non-share", async () => {
+ const mod = await freshModule();
+ const $inline = $("<code>").text("inline");
+ mod.applyInlineCodeCopy($inline);
+ expect($inline.hasClass("copyable-inline-code")).toBe(true);
+ $inline.trigger("click"); // non-share path
+
+ ctrl.isShare = true;
+ const $inline2 = $("<code>").text("inline share");
+ mod.applyInlineCodeCopy($inline2);
+ $inline2.trigger("click"); // share path
+ });
+ });
+
+ describe("formatCodeBlocks", () => {
+ function buildContainer() {
+ const $container = $("<div>");
+ const $pre = $("<pre>");
+ const $code = $("<code>").addClass("language-text-css").text("a{}");
+ $pre.append($code);
+ const $preNoLang = $("<pre>");
+ $preNoLang.append($("<code>").text("no language here"));
+ const $inline = $("<code>").text("inline");
+ $container.append($pre, $preNoLang, $inline);
+ return { $container, $code, $inline };
+ }
+
+ it("highlights code blocks, skips unlabeled blocks, adds copy buttons + inline copy", async () => {
+ const mod = await freshModule();
+ setOptions({ codeBlockThemeMatchesApp: "false", codeBlockTheme: "default:vs" });
+ const { $container, $code, $inline } = buildContainer();
+
+ await mod.formatCodeBlocks($container);
+ await flush();
+
+ // labeled block highlighted
+ expect($code.html()).toBe("HL");
+ // copy button added only to the labeled <pre> (the unlabeled one is skipped)
+ expect($container.find("pre button.copy-button").length).toBe(1);
+ // inline code (not inside a <pre>) got the click-to-copy class
+ expect($inline.hasClass("copyable-inline-code")).toBe(true);
+ // at least one inline-copy element was registered
+ expect($container.find("code.copyable-inline-code").length).toBeGreaterThanOrEqual(1);
+ });
+
+ it("skips copy buttons and highlighting affordances entirely in print mode", async () => {
+ const mod = await freshModule();
+ setOptions({ codeBlockThemeMatchesApp: "false", codeBlockTheme: "default:vs" });
+ (window as any).glob = { device: "print" };
+ const { $container, $code } = buildContainer();
+
+ await mod.formatCodeBlocks($container);
+ await flush();
+
+ expect($container.find("button.copy-button").length).toBe(0);
+ expect($container.find("code.copyable-inline-code").length).toBe(0);
+ // highlighting still applied to the labeled block
+ expect($code.html()).toBe("HL");
+ });
+
+ it("ignores non-language classes when extracting the language tag", async () => {
+ const mod = await freshModule();
+ setOptions({ codeBlockThemeMatchesApp: "false", codeBlockTheme: "default:vs" });
+ const $container = $("<div>");
+ const $pre = $("<pre>");
+ // a non-language class precedes the language one -> exercises the
+ // "doesn't start with language-" branch before the match.
+ const $code = $("<code>").addClass("hljs").addClass("language-text-css").text("a{}");
+ $pre.append($code);
+ $container.append($pre);
+
+ await mod.formatCodeBlocks($container);
+ await flush();
+
+ expect($code.html()).toBe("HL");
+ });
+
+ it("does not highlight when syntax highlighting is disabled, but still adds copy buttons", async () => {
+ const mod = await freshModule();
+ setOptions({ codeBlockThemeMatchesApp: "false", codeBlockTheme: "none" });
+ const { $container, $code } = buildContainer();
+
+ await mod.formatCodeBlocks($container);
+ await flush();
+
+ expect($code.html()).toBe("a{}"); // untouched
+ expect(hl.highlight).not.toHaveBeenCalled();
+ // copy button added only to the labeled <pre> (the unlabeled one is skipped)
+ expect($container.find("pre button.copy-button").length).toBe(1);
+ });
+ });
+
+ describe("color scheme listener + cache eviction", () => {
+ it("registers a matchMedia listener once and re-applies theme on change", async () => {
+ const mod = await freshModule();
+ setOptions({
+ codeBlockThemeMatchesApp: "true",
+ codeBlockThemeLight: "default:vs",
+ codeBlockThemeDark: "default:agate",
+ codeNotesMimeTypes: "[]"
+ });
+
+ let changeHandler: (() => void) | undefined;
+ const addEventListener = vi.fn((_evt: string, cb: () => void) => {
+ changeHandler = cb;
+ });
+ (window as any).matchMedia = vi.fn(() => ({ matches: true, addEventListener }));
+ (window as any).glob = { isMainWindow: true, theme: "auto" };
+
+ // first ensure registers the listener and marks highlightingLoaded
+ await mod.ensureMimeTypesForHighlighting("text-css");
+ expect(addEventListener).toHaveBeenCalledTimes(1);
+
+ hl.loadTheme.mockClear();
+ // OS scheme change with matchesApp=true + highlightingLoaded -> re-load theme
+ changeHandler!();
+ expect(hl.loadTheme).toHaveBeenCalledTimes(1);
+
+ // a second ensure must NOT register the listener again
+ await mod.ensureMimeTypesForHighlighting("text-x-csrc");
+ expect(addEventListener).toHaveBeenCalledTimes(1);
+ });
+
+ it("registers the matchMedia listener at most once (idempotent)", async () => {
+ const mod = await freshModule();
+ const addEventListener = vi.fn();
+ (window as any).matchMedia = vi.fn(() => ({ matches: false, addEventListener }));
+
+ mod.ensureColorSchemeListener();
+ mod.ensureColorSchemeListener(); // second call hits the early-return
+ expect(addEventListener).toHaveBeenCalledTimes(1);
+ });
+
+ it("does not re-apply the theme on change when matchesApp is false", async () => {
+ const mod = await freshModule();
+ setOptions({ codeBlockThemeMatchesApp: "false", codeBlockTheme: "default:vs", codeNotesMimeTypes: "[]" });
+
+ let changeHandler: (() => void) | undefined;
+ const addEventListener = vi.fn((_evt: string, cb: () => void) => {
+ changeHandler = cb;
+ });
+ (window as any).matchMedia = vi.fn(() => ({ matches: false, addEventListener }));
+
+ await mod.ensureMimeTypesForHighlighting("text-css");
+ hl.loadTheme.mockClear();
+
+ setOptions({ codeBlockThemeMatchesApp: "false", codeBlockTheme: "default:vs" });
+ changeHandler!();
+ expect(hl.loadTheme).not.toHaveBeenCalled();
+ });
+
+ it("evicts the oldest cache entry once the cache is full (FIFO)", async () => {
+ const mod = await freshModule();
+ setOptions({ codeBlockThemeMatchesApp: "false", codeBlockTheme: "default:vs" });
+
+ // Fill the cache beyond its max so eviction fires.
+ for (let i = 0; i < 260; i++) {
+ hl.highlight.mockImplementation(() => ({ value: `v${i}` }));
+ const $a = $codeBlock(`code-${i}`, "text-css");
+ await mod.applySingleBlockSyntaxHighlight($a, "text-css");
+ }
+
+ // The very first entry should have been evicted: re-highlighting it
+ // calls highlight() again instead of serving a cache hit.
+ hl.highlight.mockClear().mockImplementation(() => ({ value: "fresh" }));
+ const $first = $codeBlock("code-0", "text-css");
+ await mod.applySingleBlockSyntaxHighlight($first, "text-css");
+ expect(hl.highlight).toHaveBeenCalledTimes(1);
+ expect($first.html()).toBe("fresh");
+
+ // A recent entry is still cached: no re-highlight.
+ hl.highlight.mockClear();
+ const $recent = $codeBlock("code-259", "text-css");
+ await mod.applySingleBlockSyntaxHighlight($recent, "text-css");
+ expect(hl.highlight).not.toHaveBeenCalled();
+ });
+ });
+});
diff --git a/apps/client/src/services/syntax_highlight.ts b/apps/client/src/services/syntax_highlight.ts
index e9feae4da1..e161eb21f6 100644
--- a/apps/client/src/services/syntax_highlight.ts
+++ b/apps/client/src/services/syntax_highlight.ts
@@ -21,7 +21,7 @@ function getEffectiveCodeBlockTheme(): string {
// Re-apply the highlight.js theme when the OS color scheme changes, so that
// "match app appearance" reacts in real time.
let colorSchemeListenerRegistered = false;
-function ensureColorSchemeListener() {
+export function ensureColorSchemeListener() {
if (colorSchemeListenerRegistered) return;
colorSchemeListenerRegistered = true;
@@ -48,6 +48,7 @@ function setCachedHighlight(language: string, text: string, value: string) {
const key = `${language}\x00${text}`;
if (highlightCache.size >= HIGHLIGHT_CACHE_MAX) {
const oldest = highlightCache.keys().next().value;
+ /* v8 ignore next -- size>=MAX guarantees a key exists; the undefined guard is defensive */
if (oldest !== undefined) highlightCache.delete(oldest);
}
highlightCache.set(key, value);
diff --git a/apps/client/src/services/task_states.spec.ts b/apps/client/src/services/task_states.spec.ts
new file mode 100644
index 0000000000..be8671b452
--- /dev/null
+++ b/apps/client/src/services/task_states.spec.ts
@@ -0,0 +1,152 @@
+import {
+ DEFAULT_TASK_STATES,
+ DONE_STATE_ID,
+ DONE_TASK_STATE,
+ NONE_STATE_ID,
+ NONE_TASK_STATE,
+ TASK_STATES_CONTAINER_ID
+} from "@triliumnext/commons";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+import appContext from "../components/app_context.js";
+import { buildNote } from "../test/easy-froca.js";
+import froca from "./froca.js";
+import { showError } from "./toast.js";
+
+vi.mock("./i18n.js", () => ({
+ // Echo the key so assertions stay on stable keys, not translated strings.
+ t: (key: string) => key
+}));
+
+vi.mock("./toast.js", () => ({
+ showError: vi.fn()
+}));
+
+const { getTaskStateDefinitions, openCustomTaskStateConfig } = await import("./task_states.js");
+
+/** Repoints froca's `_taskStates` lookup at a freshly built container note. */
+function useContainer(children: Parameters<typeof buildNote>[0]["children"]) {
+ const id = `_ts_${Math.random().toString(36).slice(2)}`;
+ const container = buildNote({ id, title: "Container", children });
+ froca.notes[TASK_STATES_CONTAINER_ID] = container;
+ return container;
+}
+
+describe("getTaskStateDefinitions", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ delete froca.notes[TASK_STATES_CONTAINER_ID];
+ });
+
+ it("falls back to the defaults when the container note is missing", async () => {
+ const original = froca.getNote;
+ froca.getNote = vi.fn(async () => null) as typeof froca.getNote;
+ try {
+ expect(await getTaskStateDefinitions()).toBe(DEFAULT_TASK_STATES);
+ } finally {
+ froca.getNote = original;
+ }
+ });
+
+ it("maps anchors, drops archived states and reads every custom label", async () => {
+ useContainer([
+ { id: NONE_STATE_ID, title: "None src" },
+ { id: DONE_STATE_ID, title: "Done src" },
+ { title: "Archived state", "#archived": "true" },
+ {
+ id: "_taskStateDoing",
+ title: "Doing",
+ "#stateId": "doing",
+ "#markdownSymbol": "/",
+ "#isCompleted": "true",
+ "#color": "#e6a23c",
+ "#iconClass": "bx bx-loader",
+ "#isHidden": "true"
+ }
+ ]);
+
+ const result = await getTaskStateDefinitions();
+
+ // Anchors are replaced by their canonical hardcoded definitions.
+ expect(result).toContain(NONE_TASK_STATE);
+ expect(result).toContain(DONE_TASK_STATE);
+ // The archived child is never enumerated.
+ expect(result.some((s) => s.title === "Archived state")).toBe(false);
+ // No validation errors for a fully valid set.
+ expect(showError).not.toHaveBeenCalled();
+
+ expect(result.find((s) => s.id === "_taskStateDoing")).toEqual({
+ id: "_taskStateDoing",
+ name: "doing",
+ title: "Doing",
+ markdownSymbol: "/",
+ isCompleted: true,
+ color: "#e6a23c",
+ icon: "bx bx-loader",
+ isHidden: true
+ });
+ });
+
+ it("defaults the optional custom labels to falsy when they are absent", async () => {
+ // Valid (has stateId/title/icon) but omits the optional labels, so the
+ // nullish/equality fallbacks all resolve to their falsy defaults.
+ useContainer([
+ {
+ id: "_taskStateBare",
+ title: "Bare",
+ "#stateId": "bare",
+ "#iconClass": "bx bx-x"
+ }
+ ]);
+
+ const result = await getTaskStateDefinitions();
+ expect(showError).not.toHaveBeenCalled();
+ expect(result.find((s) => s.id === "_taskStateBare")).toEqual({
+ id: "_taskStateBare",
+ name: "bare",
+ title: "Bare",
+ markdownSymbol: "",
+ isCompleted: false,
+ color: "",
+ icon: "bx bx-x",
+ isHidden: false
+ });
+ });
+
+ it("reports each dropped state once via a toast, then never again", async () => {
+ // Two non-archived states missing stateId/iconClass map to empty name/icon
+ // (covering the nullish-left branches), then get dropped by validation.
+ useContainer([
+ { id: "_taskBadA", title: "Bad A" },
+ { id: "_taskBadB", title: "Bad B" }
+ ]);
+
+ const result = await getTaskStateDefinitions();
+ // No valid custom states remain -> falls back to the defaults.
+ expect(result).toBe(DEFAULT_TASK_STATES);
+ expect(showError).toHaveBeenCalledTimes(2);
+
+ // A second invocation must not re-report (the session-level latch is set).
+ vi.mocked(showError).mockClear();
+ useContainer([{ id: "_taskBadC", title: "Bad C" }]);
+ await getTaskStateDefinitions();
+ expect(showError).not.toHaveBeenCalled();
+ });
+});
+
+describe("openCustomTaskStateConfig", () => {
+ it("opens the task-states container hoisted in a new tab", () => {
+ const openInNewTab = vi.fn();
+ (appContext as unknown as { tabManager: { openInNewTab: typeof openInNewTab } }).tabManager = {
+ openInNewTab
+ };
+
+ openCustomTaskStateConfig();
+
+ expect(openInNewTab).toHaveBeenCalledWith(
+ TASK_STATES_CONTAINER_ID,
+ TASK_STATES_CONTAINER_ID,
+ true
+ );
+ });
+});
diff --git a/apps/client/src/services/theme.spec.ts b/apps/client/src/services/theme.spec.ts
new file mode 100644
index 0000000000..a31fd1c19b
--- /dev/null
+++ b/apps/client/src/services/theme.spec.ts
@@ -0,0 +1,115 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+import { getEffectiveThemeStyle, getThemeStyle } from "./theme.js";
+
+type ThemeValue = string | undefined;
+
+const win = window as unknown as {
+ glob?: { theme?: ThemeValue } & Record<string, unknown>;
+ getComputedStyle: typeof window.getComputedStyle;
+ matchMedia?: typeof window.matchMedia;
+};
+
+const originalGetComputedStyle = win.getComputedStyle;
+const originalMatchMedia = win.matchMedia;
+const originalGlob = win.glob;
+
+/** Stub window.getComputedStyle so the CSS-variable fallback path is deterministic. */
+function stubComputedStyle(props: Record<string, string>) {
+ win.getComputedStyle = vi.fn(() => ({
+ getPropertyValue: (name: string) => props[name] ?? ""
+ })) as unknown as typeof window.getComputedStyle;
+}
+
+function setTheme(theme: ThemeValue) {
+ win.glob = { ...(win.glob ?? {}), theme };
+}
+
+afterEach(() => {
+ win.getComputedStyle = originalGetComputedStyle;
+ win.matchMedia = originalMatchMedia;
+ win.glob = originalGlob;
+ vi.restoreAllMocks();
+});
+
+describe("getThemeStyle", () => {
+ it("maps the explicit configured themes without consulting computed styles", () => {
+ const computed = vi.fn();
+ win.getComputedStyle = computed as unknown as typeof window.getComputedStyle;
+
+ setTheme("auto");
+ expect(getThemeStyle()).toBe("auto");
+ setTheme("next");
+ expect(getThemeStyle()).toBe("auto");
+ setTheme("light");
+ expect(getThemeStyle()).toBe("light");
+ setTheme("dark");
+ expect(getThemeStyle()).toBe("dark");
+ setTheme("next-light");
+ expect(getThemeStyle()).toBe("light");
+ setTheme("next-dark");
+ expect(getThemeStyle()).toBe("dark");
+
+ // None of the explicit branches should fall through to computed styles.
+ expect(computed).not.toHaveBeenCalled();
+ });
+
+ it("falls back to the --theme-style CSS variable when auto is not enforced", () => {
+ setTheme(undefined);
+
+ stubComputedStyle({ "--theme-style": "dark", "--theme-style-auto": "false" });
+ expect(getThemeStyle()).toBe("dark");
+
+ stubComputedStyle({ "--theme-style": "light", "--theme-style-auto": "" });
+ expect(getThemeStyle()).toBe("light");
+ });
+
+ it("returns auto when the CSS fallback enforces auto or has no usable value", () => {
+ setTheme(undefined);
+
+ // --theme-style-auto === "true" forces auto even if a concrete style is present.
+ stubComputedStyle({ "--theme-style": "dark", "--theme-style-auto": "true" });
+ expect(getThemeStyle()).toBe("auto");
+
+ // A non light/dark CSS value also resolves to auto.
+ stubComputedStyle({ "--theme-style": "sepia", "--theme-style-auto": "false" });
+ expect(getThemeStyle()).toBe("auto");
+ });
+
+ it("handles a missing window.glob via optional chaining", () => {
+ win.glob = undefined;
+ stubComputedStyle({ "--theme-style": "light", "--theme-style-auto": "false" });
+ expect(getThemeStyle()).toBe("light");
+ });
+});
+
+describe("getEffectiveThemeStyle", () => {
+ beforeEach(() => {
+ setTheme(undefined);
+ stubComputedStyle({});
+ });
+
+ it("returns the resolved concrete theme directly when not auto", () => {
+ setTheme("dark");
+ expect(getEffectiveThemeStyle()).toBe("dark");
+
+ setTheme("light");
+ expect(getEffectiveThemeStyle()).toBe("light");
+ });
+
+ it("uses matchMedia for the auto theme, honoring the prefers-color-scheme result", () => {
+ setTheme("auto");
+
+ win.matchMedia = vi.fn(() => ({ matches: true })) as unknown as typeof window.matchMedia;
+ expect(getEffectiveThemeStyle()).toBe("dark");
+
+ win.matchMedia = vi.fn(() => ({ matches: false })) as unknown as typeof window.matchMedia;
+ expect(getEffectiveThemeStyle()).toBe("light");
+ });
+
+ it("defaults to light for the auto theme when matchMedia is unavailable", () => {
+ setTheme("auto");
+ win.matchMedia = undefined;
+ expect(getEffectiveThemeStyle()).toBe("light");
+ });
+});
diff --git a/apps/client/src/services/toast.spec.ts b/apps/client/src/services/toast.spec.ts
new file mode 100644
index 0000000000..01878449c3
--- /dev/null
+++ b/apps/client/src/services/toast.spec.ts
@@ -0,0 +1,135 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+import { buildNote } from "../test/easy-froca";
+
+const openInNewTab = vi.fn();
+vi.mock("../components/app_context.js", () => ({
+ default: {
+ tabManager: {
+ openInNewTab: (...args: unknown[]) => openInNewTab(...args)
+ }
+ }
+}));
+
+import toast, { removeToastFromStore, showError, showErrorForScriptNote, toasts } from "./toast.js";
+
+describe("toast store", () => {
+ beforeEach(() => {
+ toasts.value = [];
+ vi.clearAllMocks();
+ });
+
+ it("showMessage adds a toast with defaults and custom values", () => {
+ toast.showMessage("hello");
+ expect(toasts.value).toHaveLength(1);
+ expect(toasts.value[0]).toMatchObject({
+ icon: "bx bx-check",
+ message: "hello",
+ timeout: 2000
+ });
+ expect(typeof toasts.value[0].id).toBe("string");
+
+ toast.showMessage("custom", 500, "bx bx-star");
+ expect(toasts.value).toHaveLength(2);
+ expect(toasts.value[1]).toMatchObject({
+ icon: "bx bx-star",
+ message: "custom",
+ timeout: 500
+ });
+ });
+
+ it("showError adds an error toast with default and custom timeout", () => {
+ showError("boom");
+ expect(toasts.value[0]).toMatchObject({
+ icon: "bx bx-error-circle",
+ message: "boom",
+ timeout: 10000
+ });
+
+ showError("boom2", 42);
+ expect(toasts.value[1].timeout).toBe(42);
+ });
+
+ it("showErrorTitleAndMessage adds a titled error toast", () => {
+ toast.showErrorTitleAndMessage("Title", "msg");
+ expect(toasts.value[0]).toMatchObject({
+ title: "Title",
+ icon: "bx bx-error-circle",
+ message: "msg",
+ timeout: 10000
+ });
+
+ toast.showErrorTitleAndMessage("T2", "m2", 99);
+ expect(toasts.value[1].timeout).toBe(99);
+ });
+
+ it("showPersistent adds a new toast then updates the existing one", () => {
+ toast.showPersistent({ id: "persist-1", icon: "bx bx-info", message: "first" });
+ expect(toasts.value).toHaveLength(1);
+ expect(toasts.value[0]).toMatchObject({ id: "persist-1", message: "first" });
+
+ // Add an unrelated toast to exercise the non-matching branch of updateToast.
+ toast.showMessage("other");
+
+ toast.showPersistent({ id: "persist-1", icon: "bx bx-info", message: "updated" });
+ expect(toasts.value).toHaveLength(2);
+ const updated = toasts.value.find(t => t.id === "persist-1");
+ expect(updated?.message).toBe("updated");
+ // The unrelated toast is unchanged.
+ expect(toasts.value.find(t => t.message === "other")).toBeDefined();
+ });
+
+ it("closePersistent / removeToastFromStore removes by id and leaves others", () => {
+ toast.showPersistent({ id: "a", icon: "i", message: "A" });
+ toast.showPersistent({ id: "b", icon: "i", message: "B" });
+ expect(toasts.value).toHaveLength(2);
+
+ toast.closePersistent("a");
+ expect(toasts.value.map(t => t.id)).toEqual(["b"]);
+
+ // removeToastFromStore for a non-existent id is a no-op.
+ removeToastFromStore("does-not-exist");
+ expect(toasts.value.map(t => t.id)).toEqual(["b"]);
+
+ removeToastFromStore("b");
+ expect(toasts.value).toHaveLength(0);
+ });
+
+ it("showErrorForScriptNote uses note title/icon and wires the open-script button", async () => {
+ const note = buildNote({ title: "My Script" });
+ // Force a deterministic icon for assertion.
+ note.getIcon = () => "bx bx-code";
+
+ await showErrorForScriptNote(note.noteId, "it failed");
+
+ const created = toasts.value.find(t => t.id === `custom-widget-failure-${note.noteId}`);
+ expect(created).toBeDefined();
+ expect(created).toMatchObject({
+ icon: "bx bx-code",
+ message: "it failed",
+ timeout: 15000
+ });
+ expect(created?.buttons).toHaveLength(1);
+
+ // Invoking the button delegates to the tab manager.
+ created!.buttons![0].onClick({ dismissToast: () => {} });
+ expect(openInNewTab).toHaveBeenCalledWith(note.noteId, null, true);
+ });
+
+ it("showErrorForScriptNote falls back when the note cannot be found", async () => {
+ const froca = (await import("./froca.js")).default;
+ const original = froca.getNote;
+ froca.getNote = vi.fn(async () => null) as typeof froca.getNote;
+
+ try {
+ await showErrorForScriptNote("missing-note", "nope");
+ const created = toasts.value.find(t => t.id === "custom-widget-failure-missing-note");
+ expect(created).toBeDefined();
+ // Falls back to the default error icon.
+ expect(created?.icon).toBe("bx bx-error-circle");
+ expect(created?.message).toBe("nope");
+ } finally {
+ froca.getNote = original;
+ }
+ });
+});
diff --git a/apps/client/src/services/tree.spec.ts b/apps/client/src/services/tree.spec.ts
new file mode 100644
index 0000000000..831e80886a
--- /dev/null
+++ b/apps/client/src/services/tree.spec.ts
@@ -0,0 +1,414 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+// tree.ts subscribes a single ws message handler at import time (for the "openNote" message).
+// We capture that callback through a hoisted ws mock so we can drive it directly. We keep the
+// froca-relevant ws surface (waitForMaxKnownEntityChangeId) intact, and install the bare global
+// `logError` that froca.ts / tree.ts rely on (normally set by the real ws.ts as a side effect).
+const { wsCallbacks, logErrorMock } = vi.hoisted(() => ({
+ wsCallbacks: [] as ((message: any) => void)[],
+ logErrorMock: vi.fn()
+}));
+
+vi.mock("./ws.js", () => {
+ (window as any).logError = logErrorMock;
+ const subscribeToMessages = (cb: (message: any) => void) => {
+ wsCallbacks.push(cb);
+ };
+ return {
+ default: {
+ subscribeToMessages,
+ waitForMaxKnownEntityChangeId: async () => {},
+ logError: logErrorMock
+ },
+ subscribeToMessages,
+ logError: logErrorMock
+ };
+});
+
+import appContext from "../components/app_context.js";
+import { buildNote } from "../test/easy-froca.js";
+import froca from "./froca.js";
+import hoistedNoteService from "./hoisted_note.js";
+import treeService, { NOTE_PATH_TITLE_SEPARATOR } from "./tree.js";
+
+/** A minimal Fancytree-node-like stub usable by the node-based helpers. */
+function fakeNode(noteId: string | undefined, parent: any = null, isProtected = false): any {
+ return {
+ data: { noteId, isProtected },
+ getParent: () => parent
+ };
+}
+
+/** Ensure a "root" note exists in froca and wire the given note as its direct child. */
+async function wireUnderRoot(note: { noteId: string; addParent: (p: string, b: string, s?: boolean) => void }) {
+ const root = froca.notes["root"] ?? buildNote({ id: "root", title: "Root" });
+ const branchId = `root_${note.noteId}`;
+ const { default: FBranch } = await import("../entities/fbranch.js");
+ froca.branches[branchId] = new FBranch(froca, {
+ branchId,
+ noteId: note.noteId,
+ parentNoteId: "root",
+ notePosition: 0,
+ fromSearchNote: false
+ } as any);
+ (root as any).addChild(note.noteId, branchId, false);
+ note.addParent("root", branchId, false);
+ return root;
+}
+
+describe("ws openNote subscriber", () => {
+ it("activates/opens the note and shows the window on an openNote message", () => {
+ expect(wsCallbacks.length).toBeGreaterThan(0);
+ const activateOrOpenNote = vi.fn();
+ const showWindow = vi.fn();
+ appContext.tabManager = { activateOrOpenNote } as any;
+ (window as any).electronApi = { window: { showWindow } };
+
+ for (const cb of wsCallbacks) {
+ cb({ type: "openNote", noteId: "abc123" });
+ }
+ expect(activateOrOpenNote).toHaveBeenCalledWith("abc123");
+ expect(showWindow).toHaveBeenCalled();
+ });
+
+ it("ignores unrelated message types and tolerates a missing electronApi", () => {
+ const activateOrOpenNote = vi.fn();
+ appContext.tabManager = { activateOrOpenNote } as any;
+ (window as any).electronApi = undefined;
+
+ for (const cb of wsCallbacks) {
+ cb({ type: "somethingElse", noteId: "abc123" });
+ }
+ expect(activateOrOpenNote).not.toHaveBeenCalled();
+ });
+});
+
+describe("getNoteIdFromUrl", () => {
+ it("returns null for empty/nullish input", () => {
+ expect(treeService.getNoteIdFromUrl(null)).toBeNull();
+ expect(treeService.getNoteIdFromUrl(undefined)).toBeNull();
+ expect(treeService.getNoteIdFromUrl("")).toBeNull();
+ });
+
+ it("returns the last path segment, ignoring a query suffix", () => {
+ expect(treeService.getNoteIdFromUrl("root/a/b?foo=bar")).toBe("b");
+ expect(treeService.getNoteIdFromUrl("solo")).toBe("solo");
+ });
+});
+
+describe("getNoteIdAndParentIdFromUrl", () => {
+ it("returns an empty object for empty input", () => {
+ expect(treeService.getNoteIdAndParentIdFromUrl("")).toEqual({});
+ });
+
+ it("maps the special 'root' path to root/none", () => {
+ expect(treeService.getNoteIdAndParentIdFromUrl("root")).toEqual({ noteId: "root", parentNoteId: "none" });
+ });
+
+ it("derives note and parent from a multi-segment path, stripping a query suffix", () => {
+ expect(treeService.getNoteIdAndParentIdFromUrl("root/aaa/bbb?x=1")).toEqual({
+ noteId: "bbb",
+ parentNoteId: "aaa"
+ });
+ });
+
+ it("defaults parent to root for a single-segment path", () => {
+ expect(treeService.getNoteIdAndParentIdFromUrl("ccc")).toEqual({
+ noteId: "ccc",
+ parentNoteId: "root"
+ });
+ });
+
+ it("leaves note/parent at their defaults when the path is empty after stripping params", () => {
+ // urlOrNotePath is truthy but notePath (the part before "?") is empty -> inner `if (notePath)` is false.
+ expect(treeService.getNoteIdAndParentIdFromUrl("?onlyparams")).toEqual({
+ noteId: "",
+ parentNoteId: "root"
+ });
+ });
+});
+
+describe("getBranchIdFromUrl", () => {
+ beforeEach(() => vi.clearAllMocks());
+
+ it("returns null when there is no resolvable parent", async () => {
+ // "root" maps to parentNoteId "none" which is falsy after the guard? -> parentNoteId is "none" (truthy)
+ // use a single-segment non-root path with no parent in cache instead
+ expect(await treeService.getBranchIdFromUrl("")).toBeNull();
+ });
+
+ it("delegates to froca.getBranchId when a parent is present", async () => {
+ const spy = vi.spyOn(froca, "getBranchId").mockResolvedValue("branch-xyz");
+ const result = await treeService.getBranchIdFromUrl("root/parentX/childY");
+ expect(spy).toHaveBeenCalledWith("parentX", "childY");
+ expect(result).toBe("branch-xyz");
+ spy.mockRestore();
+ });
+});
+
+describe("getParentProtectedStatus", () => {
+ it("returns false for a hoisted node", () => {
+ hoistedNoteService.isHoistedNode = vi.fn(() => true);
+ expect(treeService.getParentProtectedStatus(fakeNode("n1"))).toBe(false);
+ });
+
+ it("returns the parent's protected flag for a non-hoisted node", () => {
+ hoistedNoteService.isHoistedNode = vi.fn(() => false);
+ const parent = fakeNode("p1", null, true);
+ expect(treeService.getParentProtectedStatus(fakeNode("n1", parent))).toBe(true);
+ });
+});
+
+describe("getNotePath", () => {
+ beforeEach(() => vi.clearAllMocks());
+
+ it("logs and returns empty string for a null node", () => {
+ expect(treeService.getNotePath(null as any)).toBe("");
+ expect(logErrorMock).toHaveBeenCalledWith("Node is null");
+ });
+
+ it("walks ancestors and skips nodes without a noteId", () => {
+ const root = fakeNode("root");
+ const middle = fakeNode(undefined, root); // skipped (no noteId)
+ const leaf = fakeNode("leaf", middle);
+ expect(treeService.getNotePath(leaf)).toBe("root/leaf");
+ });
+});
+
+describe("getNoteTitle", () => {
+ it("returns a placeholder when the note is missing", async () => {
+ const spy = vi.spyOn(froca, "getNote").mockResolvedValue(null as any);
+ expect(await treeService.getNoteTitle("does-not-exist")).toBe("[not found]");
+ spy.mockRestore();
+ });
+
+ it("returns the plain title when no parent is given", async () => {
+ const note = buildNote({ title: "Plain title" });
+ expect(await treeService.getNoteTitle(note.noteId)).toBe("Plain title");
+ });
+
+ it("prefixes the title with the branch prefix when one exists", async () => {
+ const parent = buildNote({ title: "Parent", children: [{ title: "Child" }] });
+ const child = froca.getNoteFromCache(parent.children[0])!;
+ const branchId = child.parentToBranch[parent.noteId];
+ froca.branches[branchId].prefix = "PFX";
+ expect(await treeService.getNoteTitle(child.noteId, parent.noteId)).toBe("PFX - Child");
+ });
+
+ it("returns the unprefixed title when the branch has no prefix", async () => {
+ const parent = buildNote({ title: "Parent2", children: [{ title: "Child2" }] });
+ const child = froca.getNoteFromCache(parent.children[0])!;
+ expect(await treeService.getNoteTitle(child.noteId, parent.noteId)).toBe("Child2");
+ });
+
+ it("returns the title when the parent has no branch to the note", async () => {
+ const note = buildNote({ title: "NoBranch" });
+ expect(await treeService.getNoteTitle(note.noteId, "unrelated-parent")).toBe("NoBranch");
+ });
+});
+
+describe("getNotePathTitleComponents / getNotePathTitle / getNoteTitleWithPathAsSuffix", () => {
+ it("returns just the root title for the 'root' path", async () => {
+ buildNote({ id: "root", title: "RootTitle" });
+ expect(await treeService.getNotePathTitleComponents("root")).toEqual(["RootTitle"]);
+ });
+
+ it("strips a leading 'root/' and builds a component per segment", async () => {
+ buildNote({ id: "root", title: "RootTitle" });
+ const a = buildNote({ title: "Alpha" });
+ const b = buildNote({ title: "Beta" });
+ const components = await treeService.getNotePathTitleComponents(`root/${a.noteId}/${b.noteId}`);
+ expect(components).toEqual(["Alpha", "Beta"]);
+
+ const joined = await treeService.getNotePathTitle(`root/${a.noteId}/${b.noteId}`);
+ expect(joined).toBe(["Alpha", "Beta"].join(NOTE_PATH_TITLE_SEPARATOR));
+ });
+
+ it("builds a span with the last component as title and the rest as path", async () => {
+ const a = buildNote({ title: "Alpha2" });
+ const b = buildNote({ title: "Beta2" });
+ const $result = await treeService.getNoteTitleWithPathAsSuffix(`${a.noteId}/${b.noteId}`) as JQuery<HTMLElement>;
+ expect($result.hasClass("note-title-with-path")).toBe(true);
+ expect($result.find(".note-title").text()).toBe("Beta2");
+ // path portion contains the leading title ("Alpha2")
+ expect($result.find(".note-path").text()).toContain("Alpha2");
+ });
+
+ // The empty-components guard inside getNoteTitleWithPathAsSuffix is unreachable through the
+ // public API: getNotePathTitleComponents always pushes at least one component (the loop runs
+ // for "" via split("/") -> [""]), and the internal call is to the local function (not the
+ // exported one, so it cannot be stubbed). It is annotated with a v8-ignore in the source.
+});
+
+describe("formatNotePath", () => {
+ it("returns an empty span for an empty path", () => {
+ const $result = treeService.formatNotePath([]);
+ expect($result.hasClass("note-path")).toBe(true);
+ expect($result.find(".path-bracket").length).toBe(0);
+ });
+
+ it("renders brackets, segments and delimiters for a multi-segment path", () => {
+ const $result = treeService.formatNotePath(["one", "two", "three"]);
+ expect($result.find(".path-bracket").length).toBe(2);
+ expect($result.find(".path-delimiter").length).toBe(2); // one fewer than segments
+ expect($result.text()).toContain("one");
+ expect($result.text()).toContain("three");
+ });
+
+ it("renders no delimiter for a single-segment path", () => {
+ const $result = treeService.formatNotePath(["only"]);
+ expect($result.find(".path-delimiter").length).toBe(0);
+ });
+});
+
+describe("isNotePathInHiddenSubtree", () => {
+ it("detects the hidden subtree prefix", () => {
+ expect(treeService.isNotePathInHiddenSubtree("root/_hidden/x")).toBe(true);
+ expect(treeService.isNotePathInHiddenSubtree("root/abc")).toBe(false);
+ expect(treeService.isNotePathInHiddenSubtree(undefined as any)).toBeFalsy();
+ });
+});
+
+describe("resolveNotePath / resolveNotePathToSegments", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ appContext.tabManager = { getActiveContextNotePath: () => null } as any;
+ });
+
+ it("returns null for an empty path (after stripping a query suffix)", async () => {
+ expect(await treeService.resolveNotePathToSegments("?onlyparams")).toBeNull();
+ expect(await treeService.resolveNotePath("")).toBeNull();
+ });
+
+ it("resolves a valid root-anchored path to its segments and joined form", async () => {
+ const child = buildNote({ title: "ChildA" });
+ await wireUnderRoot(child);
+
+ const path = `root/${child.noteId}`;
+ expect(await treeService.resolveNotePathToSegments(path)).toEqual(["root", child.noteId]);
+ expect(await treeService.resolveNotePath(path)).toBe(path);
+ });
+
+ it("logs and returns null when an intermediate child note is missing", async () => {
+ // The inner getNote(childNoteId) resolves to null -> "Can't find note" branch.
+ const spy = vi.spyOn(froca, "getNote").mockResolvedValue(null as any);
+ const result = await treeService.resolveNotePathToSegments("missingParent/missingChild");
+ expect(result).toBeNull();
+ expect(logErrorMock).toHaveBeenCalled();
+ spy.mockRestore();
+ });
+
+ it("returns null silently when child is missing and logErrors is false", async () => {
+ const spy = vi.spyOn(froca, "getNote").mockResolvedValue(null as any);
+ const result = await treeService.resolveNotePathToSegments("mp2/mc2", "root", false);
+ expect(result).toBeNull();
+ expect(logErrorMock).not.toHaveBeenCalled();
+ spy.mockRestore();
+ });
+
+ it("returns null when the child note has no parents (logErrors=true)", async () => {
+ const orphan = buildNote({ title: "Orphan" });
+ // path "root/orphan": iterating, childNoteId becomes "orphan" with no parents
+ const result = await treeService.resolveNotePathToSegments(`root/${orphan.noteId}`);
+ expect(result).toBeNull();
+ expect(logErrorMock).toHaveBeenCalled();
+ });
+
+ it("returns null when the child note has no parents (logErrors=false, no logging)", async () => {
+ const orphan = buildNote({ title: "Orphan2" });
+ const result = await treeService.resolveNotePathToSegments(`root/${orphan.noteId}`, "root", false);
+ expect(result).toBeNull();
+ expect(logErrorMock).not.toHaveBeenCalled();
+ });
+
+ it("falls back to the best note path when the requested (cached) parent doesn't match", async () => {
+ // note really lives under root; we request a wrong parent that DOES exist in froca,
+ // exercising the `parent ? parent.title : "n/a"` truthy branch in the debug log.
+ const note = buildNote({ title: "Target" });
+ await wireUnderRoot(note);
+ const wrongParent = buildNote({ title: "WrongButReal" });
+
+ const result = await treeService.resolveNotePathToSegments(`${wrongParent.noteId}/${note.noteId}`);
+ expect(result).toEqual(["root", note.noteId]);
+ });
+
+ it("logs 'n/a' when the mismatched parent is not present in the cache", async () => {
+ // note lives under root; we request a parent id that is NOT in froca,
+ // exercising the `parent ? parent.title : "n/a"` falsy branch in the debug log.
+ const note = buildNote({ title: "Target2" });
+ await wireUnderRoot(note);
+
+ const result = await treeService.resolveNotePathToSegments(`not-in-cache/${note.noteId}`);
+ expect(result).toEqual(["root", note.noteId]);
+ });
+
+ it("skips the best-path extension when the mismatched child has no best path (logErrors=false)", async () => {
+ // child whose only parent is NOT root and has no route to root -> getBestNotePath() is falsy,
+ // so the mismatch block breaks without pushing extra segments. The else branch then also finds
+ // no path for the note and throws. This covers the logErrors=false + falsy-bestNotePath branches.
+ const lonelyParent = buildNote({ title: "LonelyParent" });
+ const child = buildNote({ title: "DeadEndChild" });
+ const branchId = `${lonelyParent.noteId}_${child.noteId}`;
+ const { default: FBranch } = await import("../entities/fbranch.js");
+ froca.branches[branchId] = new FBranch(froca, {
+ branchId,
+ noteId: child.noteId,
+ parentNoteId: lonelyParent.noteId,
+ notePosition: 0,
+ fromSearchNote: false
+ } as any);
+ lonelyParent.addChild(child.noteId, branchId, false);
+ child.addParent(lonelyParent.noteId, branchId, false);
+
+ await expect(
+ treeService.resolveNotePathToSegments(`wrongP/${child.noteId}`, "root", false)
+ ).rejects.toThrow();
+ expect(logErrorMock).not.toHaveBeenCalled();
+ });
+});
+
+describe("resolveNotePathToSegments error/else branches", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ appContext.tabManager = { getActiveContextNotePath: () => null } as any;
+ });
+
+ it("throws when no path segments are found for the note (else branch, no best path)", async () => {
+ // single existing note whose only parent is NOT root and NOT the hoisted id.
+ const note = buildNote({ title: "Lonely" });
+ await expect(
+ treeService.resolveNotePathToSegments(note.noteId, "hoist-XYZ")
+ ).rejects.toThrow();
+ });
+
+ it("throws in the else branch when the note cannot be found from the URL", async () => {
+ // A single-segment path so the loop pushes one (non-root) segment -> else branch.
+ // froca.getNote(noteId) resolves to null -> line-103 throw.
+ const spy = vi.spyOn(froca, "getNote").mockResolvedValue(null as any);
+ await expect(treeService.resolveNotePathToSegments("loneNoteId")).rejects.toThrow(
+ /Unable to find note/
+ );
+ spy.mockRestore();
+ });
+
+ it("returns the best note path in the else branch when it includes the hoisted note", async () => {
+ const note = buildNote({ title: "ElseTarget" });
+ await wireUnderRoot(note);
+
+ // A single-segment path equal to the note id: loop runs once, no childNoteId comparison,
+ // effectivePathSegments=[noteId] which does NOT include "root" -> else branch.
+ // hoistedNoteId default "root"; bestNotePath = ["root", noteId] which includes "root".
+ const result = await treeService.resolveNotePathToSegments(note.noteId);
+ expect(result).toEqual(["root", note.noteId]);
+ });
+
+ it("falls back to the original segments in the else branch when the best path lacks the hoisted note", async () => {
+ const note = buildNote({ title: "ElseTarget2" });
+ await wireUnderRoot(note);
+
+ // hoistedNoteId not on any path -> bestNotePath (["root", noteId]) does not include it,
+ // so the ternary returns the originally-resolved effectivePathSegments ([noteId]).
+ const result = await treeService.resolveNotePathToSegments(note.noteId, "hoist-NOPE");
+ expect(result).toEqual([note.noteId]);
+ });
+});
diff --git a/apps/client/src/services/tree.ts b/apps/client/src/services/tree.ts
index 81b439aa3d..0e2e49fff7 100644
--- a/apps/client/src/services/tree.ts
+++ b/apps/client/src/services/tree.ts
@@ -95,6 +95,7 @@ async function resolveNotePathToSegments(notePath: string, hoistedNoteId = "root
return effectivePathSegments;
} else {
const noteId = getNoteIdFromUrl(notePath);
+ /* v8 ignore next 3 -- unreachable: notePath is non-empty here (guarded at the top), so getNoteIdFromUrl always returns its last segment */
if (!noteId) {
throw new Error(`Unable to find note with ID: ${noteId}.`);
}
@@ -259,6 +260,7 @@ async function getNoteTitleWithPathAsSuffix(notePath: string) {
const titleComponents = await getNotePathTitleComponents(notePath);
+ /* v8 ignore next 3 -- unreachable: getNotePathTitleComponents always returns a non-empty array (it pushes at least one title for any path, including "") */
if (!titleComponents || titleComponents.length === 0) {
return "";
}
diff --git a/apps/client/src/services/utils.spec.ts b/apps/client/src/services/utils.spec.ts
index 2885fa270c..695489201a 100644
--- a/apps/client/src/services/utils.spec.ts
+++ b/apps/client/src/services/utils.spec.ts
@@ -1,5 +1,59 @@
-import { describe, expect, it } from "vitest";
-import { getSizeFromSvg } from "./utils.js";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+import utils, {
+ arrayEqual,
+ clearBrowserCache,
+ createImageSrcUrl,
+ escapeHtml,
+ escapeQuotes,
+ escapeRegExp,
+ formatDateTime,
+ formatSize,
+ getErrorMessage,
+ getSizeFromSvg,
+ handleRightToLeftPlacement,
+ isCtrlKey,
+ isElectron,
+ isHtmlEmpty,
+ isLaunchBarConfig,
+ isMac,
+ isMobileApp,
+ isPWA,
+ isUpdateAvailable,
+ mapToKeyValueArray,
+ numberObjectsInPlace,
+ openInAppHelpFromUrl,
+ openInReusableSplit,
+ randomString,
+ reloadFrontendApp,
+ replaceHtmlEscapedSlashes,
+ restartDesktopApp,
+ toggleBodyClass
+} from "./utils.js";
+
+// `snapdom` is used by downloadAsSvg / downloadAsPng; stub it so no real rendering happens.
+vi.mock("@zumer/snapdom", () => ({
+ snapdom: vi.fn(async () => ({
+ url: "data:image/svg+xml;base64,AAA",
+ toPng: vi.fn(async () => ({ src: "data:image/png;base64,BBB" }))
+ }))
+}));
+
+import { snapdom } from "@zumer/snapdom";
+
+// `logInfo` / `logError` are normally attached to window/globalThis by ws.ts, which is mocked
+// out by the test setup. Provide no-op globals so the few code paths that log don't crash.
+beforeEach(() => {
+ (globalThis as any).logInfo = vi.fn();
+ (globalThis as any).logError = vi.fn();
+});
+
+afterEach(() => {
+ vi.restoreAllMocks();
+ delete (window as any).electronApi;
+ delete (navigator as any).standalone;
+ delete (navigator as any).windowControlsOverlay;
+});
describe("getSizeFromSvg", () => {
it("parses width & height attribute", () => {
@@ -19,4 +73,761 @@ describe("getSizeFromSvg", () => {
height: 655
});
});
+
+ it("returns null and warns when neither dimensions nor viewBox are present", () => {
+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
+ const svg = `<svg xmlns="http://www.w3.org/2000/svg"></svg>`;
+ expect(getSizeFromSvg(svg)).toBeNull();
+ expect(warn).toHaveBeenCalled();
+ });
+});
+
+describe("string escaping helpers", () => {
+ it("escapeHtml maps every special character", () => {
+ expect(escapeHtml(`&<>"'/\`=`)).toBe("&amp;&lt;&gt;&quot;&#39;&#x2F;&#x60;&#x3D;");
+ });
+
+ it("escapeQuotes replaces all double quotes", () => {
+ expect(escapeQuotes(`a"b"c`)).toBe("a&quot;b&quot;c");
+ });
+
+ it("escapeRegExp escapes regex metacharacters", () => {
+ expect(escapeRegExp("a.b*c+(d)")).toBe("a\\.b\\*c\\+\\(d\\)");
+ });
+
+ it("replaceHtmlEscapedSlashes turns &#x2F; back into /", () => {
+ expect(replaceHtmlEscapedSlashes("a&#x2F;b&#x2F;c")).toBe("a/b/c");
+ });
+});
+
+describe("formatSize", () => {
+ it("returns empty string for null/undefined", () => {
+ expect(formatSize(null)).toBe("");
+ expect(formatSize(undefined)).toBe("");
+ });
+
+ it("returns 0 B for zero", () => {
+ expect(formatSize(0)).toBe("0 B");
+ });
+
+ it("formats bytes, KiB, MiB and GiB", () => {
+ expect(formatSize(512)).toBe("512 B");
+ expect(formatSize(2048)).toBe("2 KiB");
+ expect(formatSize(5 * 1024 * 1024)).toBe("5 MiB");
+ expect(formatSize(3 * 1024 * 1024 * 1024)).toBe("3 GiB");
+ });
+});
+
+describe("formatDateTime / date helpers", () => {
+ it("uses the default ISO date + time format when no custom format is given", () => {
+ const date = new Date(2024, 0, 5, 9, 7); // local time -> 2024-01-05 09:07
+ expect(formatDateTime(date)).toBe("2024-01-05 09:07");
+ });
+
+ it("uses a user-supplied dayjs format when provided", () => {
+ const date = new Date(2024, 0, 5, 9, 7);
+ expect(formatDateTime(date, "YYYY")).toBe("2024");
+ });
+
+ it("treats a whitespace-only custom format as absent", () => {
+ const date = new Date(2024, 11, 31, 23, 59);
+ expect(formatDateTime(date, " ")).toBe("2024-12-31 23:59");
+ });
+
+ it("formatDateISO (via default export) pads month and day", () => {
+ const date = new Date(2024, 2, 9); // March 9
+ expect(utils.formatDateISO(date)).toBe("2024-03-09");
+ });
+
+ it("formatTime (via default export) pads hours and minutes", () => {
+ const date = new Date(2024, 0, 1, 3, 4);
+ expect(utils.formatTime(date)).toBe("03:04");
+ });
+
+ it("now() returns a HH:MM:SS string", () => {
+ expect(utils.now()).toMatch(/^\d{2}:\d{2}:\d{2}$/);
+ });
+
+ it("localNowDateTime() returns a dayjs formatted timestamp", () => {
+ expect(utils.localNowDateTime()).toMatch(/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}\./);
+ });
+});
+
+describe("parseDate (default export)", () => {
+ it("parses a valid date string", () => {
+ const result = utils.parseDate("2024-01-05T00:00:00Z");
+ expect(result.getUTCFullYear()).toBe(2024);
+ });
+
+ it("wraps thrown errors with context", () => {
+ // Force Date.parse to throw so the catch branch is exercised.
+ const parseSpy = vi.spyOn(Date, "parse").mockImplementation(() => {
+ throw new Error("boom");
+ });
+ expect(() => utils.parseDate("whatever")).toThrow(/Can't parse date from 'whatever': boom/);
+ parseSpy.mockRestore();
+ });
+});
+
+describe("formatTimeInterval (default export)", () => {
+ it("returns days + hours when over a day", () => {
+ const ms = ((1 * 24 + 3) * 60 + 0) * 60 * 1000; // 1 day 3 hours
+ expect(utils.formatTimeInterval(ms)).toBe("1 day, 3 hours");
+ });
+
+ it("pluralizes multiple days", () => {
+ const ms = 3 * 24 * 60 * 60 * 1000;
+ expect(utils.formatTimeInterval(ms)).toBe("3 days");
+ });
+
+ it("returns minutes and seconds for small intervals", () => {
+ const ms = (2 * 60 + 30) * 1000; // 2 min 30 s
+ expect(utils.formatTimeInterval(ms)).toBe("2 minutes, 30 seconds");
+ });
+
+ it("omits seconds when at least 5 minutes have elapsed", () => {
+ const ms = (10 * 60 + 30) * 1000; // 10 min 30 s -> seconds dropped
+ expect(utils.formatTimeInterval(ms)).toBe("10 minutes");
+ });
+
+ it("returns a single second for one second", () => {
+ expect(utils.formatTimeInterval(1000)).toBe("1 second");
+ });
+
+ it("returns an empty string for a zero interval", () => {
+ expect(utils.formatTimeInterval(0)).toBe("");
+ });
+});
+
+describe("isHtmlEmpty", () => {
+ it("treats falsy / blank as empty", () => {
+ expect(isHtmlEmpty("")).toBe(true);
+ expect(isHtmlEmpty("<p> </p>")).toBe(true);
+ });
+
+ it("detects content via img / section / link-mention", () => {
+ expect(isHtmlEmpty("<IMG src='x'>")).toBe(false);
+ expect(isHtmlEmpty("<SECTION></section>")).toBe(false);
+ expect(isHtmlEmpty("<span class='link-mention'></span>")).toBe(false);
+ });
+
+ it("detects plain text content", () => {
+ expect(isHtmlEmpty("<p>hello</p>")).toBe(false);
+ });
+
+ it("logs and returns false for a non-string input", () => {
+ const logError = vi.fn();
+ (globalThis as any).logError = logError;
+ expect(isHtmlEmpty({} as any)).toBe(false);
+ expect(logError).toHaveBeenCalled();
+ });
+});
+
+describe("randomString", () => {
+ it("returns a string of the requested length using the allowed alphabet", () => {
+ const s = randomString(20);
+ expect(s).toHaveLength(20);
+ expect(s).toMatch(/^[A-Za-z0-9]+$/);
+ });
+
+ it("defaults to length 16", () => {
+ expect(randomString()).toHaveLength(16);
+ });
+});
+
+describe("platform / device detection", () => {
+ it("isElectron reflects presence of window.electronApi", () => {
+ expect(isElectron()).toBe(false);
+ (window as any).electronApi = {};
+ expect(isElectron()).toBe(true);
+ });
+
+ it("isMac reads navigator.platform", () => {
+ const spy = vi.spyOn(navigator, "platform", "get");
+ spy.mockReturnValue("MacIntel");
+ expect(isMac()).toBe(true);
+ spy.mockReturnValue("Win32");
+ expect(isMac()).toBe(false);
+ });
+
+ it("isCtrlKey uses ctrlKey on non-Mac and metaKey on Mac", () => {
+ const platformSpy = vi.spyOn(navigator, "platform", "get");
+ platformSpy.mockReturnValue("Win32");
+ expect(isCtrlKey({ ctrlKey: true, metaKey: false } as any)).toBe(true);
+ expect(isCtrlKey({ ctrlKey: false, metaKey: true } as any)).toBe(false);
+
+ platformSpy.mockReturnValue("MacIntel");
+ expect(isCtrlKey({ ctrlKey: true, metaKey: false } as any)).toBe(false);
+ expect(isCtrlKey({ ctrlKey: false, metaKey: true } as any)).toBe(true);
+ });
+
+ it("isMobileApp reflects Capacitor native platform", () => {
+ expect(isMobileApp()).toBe(false);
+ (window as any).Capacitor = { isNativePlatform: () => true };
+ expect(isMobileApp()).toBe(true);
+ delete (window as any).Capacitor;
+ });
+
+ it("isMobile / isDesktop respond to glob.device", () => {
+ const original = window.glob.device;
+ window.glob.device = "mobile";
+ expect(utils.isMobile()).toBe(true);
+ expect(utils.isDesktop()).toBe(false);
+
+ window.glob.device = "desktop";
+ expect(utils.isMobile()).toBe(false);
+ expect(utils.isDesktop()).toBe(true);
+
+ window.glob.device = original;
+ });
+
+ it("isMobile / isDesktop fall back to the user agent when device is unset", () => {
+ const original = window.glob.device;
+ window.glob.device = undefined as any;
+ const uaSpy = vi.spyOn(navigator, "userAgent", "get");
+
+ uaSpy.mockReturnValue("Mozilla/5.0 (Linux; Android) Mobile Safari");
+ expect(utils.isMobile()).toBe(true);
+ expect(utils.isDesktop()).toBe(false);
+
+ uaSpy.mockReturnValue("Mozilla/5.0 (Windows NT 10.0) Safari");
+ expect(utils.isMobile()).toBe(false);
+ expect(utils.isDesktop()).toBe(true);
+
+ window.glob.device = original;
+ });
+
+ it("isPWA detects standalone display mode", () => {
+ const mmSpy = vi.spyOn(window, "matchMedia");
+ mmSpy.mockImplementation((q: string) => ({ matches: q.includes("standalone") }) as MediaQueryList);
+ expect(isPWA()).toBe(true);
+
+ mmSpy.mockImplementation(() => ({ matches: false }) as MediaQueryList);
+ expect(isPWA()).toBeFalsy();
+
+ (navigator as any).standalone = true;
+ expect(isPWA()).toBe(true);
+ });
+});
+
+describe("isIOS (named export)", () => {
+ it("returns true for iOS-like user agents and false otherwise", async () => {
+ const { isIOS } = await import("./utils.js");
+ const uaSpy = vi.spyOn(navigator, "userAgent", "get");
+ uaSpy.mockReturnValue("iPad");
+ expect(isIOS()).toBe(true);
+ uaSpy.mockReturnValue("Windows");
+ expect(isIOS()).toBe(false);
+ });
+});
+
+describe("electron-aware helpers", () => {
+ it("reloadFrontendApp uses electronApi when present and logs the reason", () => {
+ const reloadAllWindows = vi.fn();
+ (window as any).electronApi = { window: { reloadAllWindows } };
+ reloadFrontendApp("a reason");
+ expect((globalThis as any).logInfo).toHaveBeenCalled();
+ expect(reloadAllWindows).toHaveBeenCalled();
+ });
+
+ it("reloadFrontendApp falls back to location.reload without electron and skips logging when no reason", () => {
+ const reloadSpy = vi.spyOn(window.location, "reload").mockImplementation(() => {});
+ reloadFrontendApp();
+ expect(reloadSpy).toHaveBeenCalled();
+ expect((globalThis as any).logInfo).not.toHaveBeenCalled();
+ });
+
+ it("restartDesktopApp restarts via electron or reloads otherwise", () => {
+ const restartApp = vi.fn();
+ (window as any).electronApi = { window: { restartApp } };
+ restartDesktopApp();
+ expect(restartApp).toHaveBeenCalled();
+
+ delete (window as any).electronApi;
+ const reloadSpy = vi.spyOn(window.location, "reload").mockImplementation(() => {});
+ restartDesktopApp();
+ expect(reloadSpy).toHaveBeenCalled();
+ });
+
+ it("reloadTray invokes electron tray when present and is a no-op otherwise", () => {
+ const reloadTray = vi.fn();
+ (window as any).electronApi = { tray: { reloadTray } };
+ utils.reloadTray();
+ expect(reloadTray).toHaveBeenCalled();
+
+ delete (window as any).electronApi;
+ expect(() => utils.reloadTray()).not.toThrow();
+ });
+
+ it("clearBrowserCache calls electron clearCache when available", async () => {
+ const clearCache = vi.fn(async () => {});
+ (window as any).electronApi = { window: { clearCache } };
+ await clearBrowserCache();
+ expect(clearCache).toHaveBeenCalled();
+
+ delete (window as any).electronApi;
+ await expect(clearBrowserCache()).resolves.toBeUndefined();
+ });
+});
+
+describe("DOM / clipboard helpers (default export)", () => {
+ it("assertArguments traces falsy arguments", () => {
+ const trace = vi.spyOn(console, "trace").mockImplementation(() => {});
+ utils.assertArguments("ok", "", "alsoOk");
+ expect(trace).toHaveBeenCalledTimes(1);
+ });
+
+ it("setCookie writes a document.cookie entry", () => {
+ utils.setCookie("myCookie", "myValue");
+ expect(document.cookie).toContain("myCookie=myValue");
+ });
+
+ it("setCookie writes an empty value when falsy", () => {
+ utils.setCookie("emptyCookie", "");
+ expect(document.cookie).toContain("emptyCookie=");
+ });
+
+ it("getNoteTypeClass / getMimeTypeClass produce CSS-safe class names", () => {
+ expect(utils.getNoteTypeClass("text")).toBe("type-text");
+ expect(utils.getMimeTypeClass("")).toBe("");
+ expect(utils.getMimeTypeClass("text/html; charset=utf-8")).toBe("mime-text-html");
+ expect(utils.getMimeTypeClass("application/JSON")).toBe("mime-application-json");
+ });
+
+ it("copySelectionToClipboard writes the current selection", () => {
+ const writeText = vi.fn();
+ vi.spyOn(window, "getSelection").mockReturnValue({ toString: () => "hello" } as any);
+ vi.spyOn(navigator, "clipboard", "get").mockReturnValue({ writeText } as any);
+ utils.copySelectionToClipboard();
+ expect(writeText).toHaveBeenCalledWith("hello");
+ });
+
+ it("copySelectionToClipboard does nothing when there is no selection", () => {
+ const writeText = vi.fn();
+ vi.spyOn(window, "getSelection").mockReturnValue({ toString: () => "" } as any);
+ vi.spyOn(navigator, "clipboard", "get").mockReturnValue({ writeText } as any);
+ utils.copySelectionToClipboard();
+ expect(writeText).not.toHaveBeenCalled();
+ });
+
+ it("copyHtmlToClipboard sets clipboard data through the copy event", () => {
+ const setData = vi.fn();
+ // happy-dom doesn't implement execCommand; provide a stub that fires the copy event.
+ const execSpy = vi.fn(() => {
+ const evt: any = new Event("copy");
+ evt.clipboardData = { setData };
+ document.dispatchEvent(evt);
+ return true;
+ });
+ (document as any).execCommand = execSpy;
+ utils.copyHtmlToClipboard("<b>x</b>");
+ expect(execSpy).toHaveBeenCalledWith("copy");
+ expect(setData).toHaveBeenCalledWith("text/html", "<b>x</b>");
+ expect(setData).toHaveBeenCalledWith("text/plain", "<b>x</b>");
+ delete (document as any).execCommand;
+ });
+
+ it("copyHtmlToClipboard tolerates a copy event without clipboardData", () => {
+ const execSpy = vi.fn(() => {
+ document.dispatchEvent(new Event("copy"));
+ return true;
+ });
+ (document as any).execCommand = execSpy;
+ expect(() => utils.copyHtmlToClipboard("<b>x</b>")).not.toThrow();
+ expect(execSpy).toHaveBeenCalled();
+ delete (document as any).execCommand;
+ });
+
+ it("triggerDownload creates and clicks an anchor", () => {
+ const clickSpy = vi.spyOn(HTMLAnchorElement.prototype, "click").mockImplementation(() => {});
+ utils.triggerDownload("file.txt", "data:text/plain,hi");
+ expect(clickSpy).toHaveBeenCalled();
+ });
+
+ it("initHelpDropdown stops propagation of clicks inside the dropdown menu", () => {
+ const $el = window.$(`<div class="wrapper"><div class="help-dropdown"><div class="dropdown-menu"><a class="inner">x</a></div></div></div>`);
+ utils.initHelpDropdown($el);
+ const event = window.$.Event("click");
+ $el.find(".help-dropdown .dropdown-menu").trigger(event);
+ expect(event.isPropagationStopped()).toBe(true);
+ });
+
+ it("toggleBodyClass removes existing prefixed classes, keeps unrelated ones, and adds the new one", () => {
+ const $body = window.$("body");
+ $body.addClass("heading-style-old");
+ $body.addClass("unrelated-class");
+ toggleBodyClass("heading-style-", "markdown");
+ expect($body.hasClass("heading-style-old")).toBe(false);
+ expect($body.hasClass("unrelated-class")).toBe(true);
+ expect($body.hasClass("heading-style-markdown")).toBe(true);
+ $body.removeClass("heading-style-markdown unrelated-class");
+ });
+});
+
+describe("formatHtml (default export)", () => {
+ it("indents nested tags and preserves <pre> content", () => {
+ const out = utils.formatHtml("<div><pre>raw text</pre><span>hi</span></div>");
+ expect(out).toContain("<pre>");
+ expect(out).toContain("raw text");
+ expect(out).toContain("<span>");
+ // Output begins with the first tag (leading newline stripped).
+ expect(out.startsWith("<div>")).toBe(true);
+ });
+
+ it("handles self-closing tags", () => {
+ const out = utils.formatHtml("<div><br><img src=x></div>");
+ expect(out).toContain("<br>");
+ expect(out).toContain("<img");
+ });
+
+ it("handles a close tag followed by trailing text and non-newline-leading output", () => {
+ const out = utils.formatHtml("<div>x</div>y");
+ // close tag chunk "</div>y" doesn't end with ">", and the result doesn't start with a newline
+ expect(out).toBe("<div>\n\tx\n</div>\ny");
+ });
+
+ it("returns plain text unchanged when there are no tags", () => {
+ expect(utils.formatHtml("text only no tags")).toBe("text only no tags");
+ });
+
+ it("tolerates a degenerate tag with no parseable tag name", () => {
+ const out = utils.formatHtml("<div>a</>b</div>");
+ expect(out).toContain("</>");
+ expect(out).toContain("<div>");
+ });
+});
+
+describe("timeLimit (default export)", () => {
+ beforeEach(() => vi.useFakeTimers());
+ afterEach(() => vi.useRealTimers());
+
+ it("returns the input unchanged when it is not a promise", () => {
+ expect(utils.timeLimit(42 as any, 1000)).toBe(42);
+ });
+
+ it("resolves when the promise settles before the limit (timer sees it as resolved)", async () => {
+ const result = utils.timeLimit(Promise.resolve("done"), 1000);
+ await expect(result).resolves.toBe("done");
+ // Advance past the limit so the timeout callback runs and observes `resolved === true`.
+ await vi.advanceTimersByTimeAsync(1000);
+ await expect(result).resolves.toBe("done");
+ });
+
+ it("rejects with the custom message when the limit is exceeded", async () => {
+ const never = new Promise(() => {});
+ const limited = utils.timeLimit(never, 50, "too slow");
+ const assertion = expect(limited).rejects.toThrow("too slow");
+ await vi.advanceTimersByTimeAsync(60);
+ await assertion;
+ });
+
+ it("uses a default error message when none is supplied", async () => {
+ const never = new Promise(() => {});
+ const limited = utils.timeLimit(never, 50);
+ const assertion = expect(limited).rejects.toThrow(/Process exceeded time limit 50/);
+ await vi.advanceTimersByTimeAsync(60);
+ await assertion;
+ });
+});
+
+describe("sleep (default export)", () => {
+ it("resolves after the timer fires", async () => {
+ vi.useFakeTimers();
+ const p = utils.sleep(100);
+ let resolved = false;
+ p.then(() => (resolved = true));
+ await vi.advanceTimersByTimeAsync(100);
+ await p;
+ expect(resolved).toBe(true);
+ vi.useRealTimers();
+ });
+});
+
+describe("attribute name helpers (default export)", () => {
+ it("filterAttributeName keeps only letters, numbers, underscore and colon", () => {
+ expect(utils.filterAttributeName("a b#c:d_1!")).toBe("abc:d_1");
+ });
+
+ it("isValidAttributeName validates against the allowed character set", () => {
+ expect(utils.isValidAttributeName("valid_name:1")).toBe(true);
+ expect(utils.isValidAttributeName("has space")).toBe(false);
+ expect(utils.isValidAttributeName("")).toBe(false);
+ });
+});
+
+describe("toObject (default export)", () => {
+ it("builds a record from an array via the mapping function", () => {
+ const result = utils.toObject([1, 2], (n) => [`k${n}`, n * 10]);
+ expect(result).toEqual({ k1: 10, k2: 20 });
+ });
+});
+
+describe("areObjectsEqual (default export)", () => {
+ it("returns true with fewer than two arguments", () => {
+ expect(utils.areObjectsEqual()).toBe(true);
+ expect(utils.areObjectsEqual({ a: 1 })).toBe(true);
+ });
+
+ it("treats NaN as equal to NaN", () => {
+ expect(utils.areObjectsEqual(NaN, NaN)).toBe(true);
+ });
+
+ it("compares primitives, functions, dates and regexes by value", () => {
+ const fn = () => 1;
+ expect(utils.areObjectsEqual(fn, fn)).toBe(true);
+ expect(utils.areObjectsEqual(new Date(0), new Date(0))).toBe(true);
+ expect(utils.areObjectsEqual(/abc/, /abc/)).toBe(true);
+ expect(utils.areObjectsEqual(new String("x"), new String("x"))).toBe(true);
+ expect(utils.areObjectsEqual(new Number(1), new Number(1))).toBe(true);
+ });
+
+ it("returns false when only one argument is a function", () => {
+ // typeof x === "function" is true but typeof y === "function" is false, so the
+ // function-vs-function short-circuit fails and the constructor check rejects them.
+ expect(utils.areObjectsEqual(() => 1, {})).toBe(false);
+ });
+
+ it("returns false when one side is not an object", () => {
+ expect(utils.areObjectsEqual({ a: 1 }, 5)).toBe(false);
+ });
+
+ it("returns false when prototypes are linked", () => {
+ const proto = { a: 1 };
+ const child = Object.create(proto);
+ child.a = 1;
+ expect(utils.areObjectsEqual(proto, child)).toBe(false);
+ });
+
+ it("returns false when constructors differ", () => {
+ class A { x = 1; }
+ class B { x = 1; }
+ expect(utils.areObjectsEqual(new A(), new B())).toBe(false);
+ });
+
+ it("detects differing keys, types and nested objects", () => {
+ expect(utils.areObjectsEqual({ a: 1 }, { b: 1 })).toBe(false);
+ expect(utils.areObjectsEqual({ a: 1 }, { a: "1" })).toBe(false);
+ expect(utils.areObjectsEqual({ a: { b: 1 } }, { a: { b: 2 } })).toBe(false);
+ expect(utils.areObjectsEqual({ a: 1, b: 2 }, { a: 1, c: 2 })).toBe(false);
+ });
+
+ it("returns false when objects carry differing `prototype` own properties", () => {
+ // Plain objects (same constructor) with a literal `prototype` property of differing value.
+ expect(utils.areObjectsEqual({ prototype: 1, a: 1 }, { prototype: 2, a: 1 })).toBe(false);
+ });
+
+ it("returns false when the second loop finds a key missing on the other side", () => {
+ // x has an extra own key that y lacks; y is a subset so the first loop passes.
+ expect(utils.areObjectsEqual({ a: 1, extra: 2 }, { a: 1 })).toBe(false);
+ });
+
+ it("returns false when a non-enumerable own property differs in type in the second loop", () => {
+ const x = { a: 1 };
+ const y = {};
+ // Non-enumerable so the first (for..in y) loop skips it, but hasOwnProperty still sees it.
+ Object.defineProperty(y, "a", { value: "1", enumerable: false });
+ expect(utils.areObjectsEqual(x, y)).toBe(false);
+ });
+
+ it("returns true for deeply equal objects", () => {
+ expect(utils.areObjectsEqual({ a: 1, b: { c: 2 } }, { a: 1, b: { c: 2 } })).toBe(true);
+ });
+
+ it("guards against infinite reference loops", () => {
+ const x: any = { self: null };
+ x.self = x;
+ const y: any = { self: null };
+ y.self = y;
+ expect(utils.areObjectsEqual(x, y)).toBe(false);
+ });
+});
+
+describe("createImageSrcUrl", () => {
+ it("builds an encoded api/images URL", () => {
+ const url = createImageSrcUrl({ noteId: "abc", title: "My Note/With Slash" } as any);
+ expect(url).toMatch(/^api\/images\/abc\/My%20Note%2FWith%20Slash\?timestamp=\d+$/);
+ });
+});
+
+describe("snapdom downloads (default export)", () => {
+ it("downloadAsSvg parses an SVG string with the SVG mime type, renders it and triggers a download", async () => {
+ const clickSpy = vi.spyOn(HTMLAnchorElement.prototype, "click").mockImplementation(() => {});
+ // happy-dom's image/svg+xml documentElement lacks a writable `.style`, so return a real
+ // HTML element from the parser while still asserting the SVG mime branch was taken.
+ const parseSpy = vi.spyOn(DOMParser.prototype, "parseFromString").mockImplementation(() => {
+ const doc = document.implementation.createHTMLDocument("");
+ return doc;
+ });
+ await utils.downloadAsSvg("diagram", " <svg><rect/></svg>");
+ expect(parseSpy).toHaveBeenCalledWith(" <svg><rect/></svg>", "image/svg+xml");
+ expect(snapdom).toHaveBeenCalled();
+ expect(clickSpy).toHaveBeenCalled();
+ });
+
+ it("downloadAsSvg accepts an existing element without attaching it", async () => {
+ const clickSpy = vi.spyOn(HTMLAnchorElement.prototype, "click").mockImplementation(() => {});
+ const el = document.createElement("div");
+ await utils.downloadAsSvg("diagram", el);
+ expect(snapdom).toHaveBeenCalled();
+ expect(clickSpy).toHaveBeenCalled();
+ });
+
+ it("downloadAsPng renders an HTML string to PNG and downloads it", async () => {
+ const clickSpy = vi.spyOn(HTMLAnchorElement.prototype, "click").mockImplementation(() => {});
+ await utils.downloadAsPng("diagram", "<div>hello</div>");
+ expect(snapdom).toHaveBeenCalled();
+ expect(clickSpy).toHaveBeenCalled();
+ });
+});
+
+describe("version comparison", () => {
+ it("compareVersions handles greater/less/equal and prefixes", () => {
+ expect(utils.compareVersions("v2.0.0", "1.9.9")).toBe(1);
+ expect(utils.compareVersions("1.0.0", "2.0.0")).toBe(-1);
+ expect(utils.compareVersions("1.0.0", "1.0.1")).toBe(-1);
+ expect(utils.compareVersions("1.2.3", "1.2.3")).toBe(0);
+ expect(utils.compareVersions("1.3.0", "1.2.0")).toBe(1);
+ expect(utils.compareVersions("1.2.0", "1.3.0")).toBe(-1);
+ expect(utils.compareVersions("1.2.4", "1.2.3")).toBe(1);
+ expect(utils.compareVersions("1.0.0-beta", "1.0.0")).toBe(0);
+ });
+
+ it("pads shorter version strings with zeros before comparing", () => {
+ // "1.2" -> [1,2,0] and "1" -> [1,0,0], exercising the zero-padding loops on both sides.
+ expect(utils.compareVersions("1.2", "1.2.0")).toBe(0);
+ expect(utils.compareVersions("1", "1.0.1")).toBe(-1);
+ // Pad the second (right) version too.
+ expect(utils.compareVersions("1.0.1", "1")).toBe(1);
+ });
+
+ it("isUpdateAvailable returns false for missing latest version", () => {
+ expect(isUpdateAvailable(null, "1.0.0")).toBe(false);
+ expect(isUpdateAvailable(undefined, "1.0.0")).toBe(false);
+ });
+
+ it("isUpdateAvailable compares the two versions", () => {
+ expect(isUpdateAvailable("1.1.0", "1.0.0")).toBe(true);
+ expect(isUpdateAvailable("1.0.0", "1.0.0")).toBe(false);
+ });
+});
+
+describe("isLaunchBarConfig", () => {
+ it("recognizes the launch bar config note ids", () => {
+ expect(isLaunchBarConfig("_lbRoot")).toBe(true);
+ expect(isLaunchBarConfig("_lbMobileVisibleLaunchers")).toBe(true);
+ expect(isLaunchBarConfig("someOtherNote")).toBe(false);
+ });
+});
+
+describe("array & object helpers", () => {
+ it("arrayEqual covers identity, length and element comparisons", () => {
+ const a = [1, 2, 3];
+ expect(arrayEqual(a, a)).toBe(true);
+ expect(arrayEqual([1, 2], [1, 2])).toBe(true);
+ expect(arrayEqual([1, 2], [1, 2, 3])).toBe(false);
+ expect(arrayEqual([1, 2], [1, 3])).toBe(false);
+ });
+
+ it("numberObjectsInPlace assigns sequential indices and returns the same array", () => {
+ const items = [{ a: 1 }, { a: 2 }];
+ const result = numberObjectsInPlace(items);
+ expect(result).toBe(items as any);
+ expect(result.map((i) => i.index)).toEqual([0, 1]);
+ });
+
+ it("mapToKeyValueArray turns a record into key/value pairs", () => {
+ expect(mapToKeyValueArray({ a: 1, b: 2 })).toEqual([
+ { key: "a", value: 1 },
+ { key: "b", value: 2 }
+ ]);
+ });
+});
+
+describe("getErrorMessage", () => {
+ it("extracts a message from error-like objects, else returns a fallback", () => {
+ expect(getErrorMessage(new Error("kaboom"))).toBe("kaboom");
+ expect(getErrorMessage({ message: "custom" })).toBe("custom");
+ expect(getErrorMessage("plain string")).toBe("Unknown error");
+ expect(getErrorMessage({ message: 5 })).toBe("Unknown error");
+ expect(getErrorMessage(null)).toBe("Unknown error");
+ });
+});
+
+describe("handleRightToLeftPlacement", () => {
+ it("returns the placement unchanged in LTR mode", () => {
+ const original = window.glob.isRtl;
+ window.glob.isRtl = false;
+ expect(handleRightToLeftPlacement("left")).toBe("left");
+ window.glob.isRtl = original;
+ });
+
+ it("swaps left/right in RTL mode and leaves other values alone", () => {
+ const original = window.glob.isRtl;
+ window.glob.isRtl = true;
+ expect(handleRightToLeftPlacement("left")).toBe("right");
+ expect(handleRightToLeftPlacement("right")).toBe("left");
+ expect(handleRightToLeftPlacement("top")).toBe("top");
+ window.glob.isRtl = original;
+ });
+});
+
+describe("openInReusableSplit / openInAppHelpFromUrl", () => {
+ afterEach(() => {
+ delete (window.glob as any).appContext;
+ });
+
+ it("does nothing when there is no active context", async () => {
+ (window.glob as any).appContext = { tabManager: { getActiveContext: () => null } };
+ await expect(openInReusableSplit("note1", "contextual-help")).resolves.toBeUndefined();
+ });
+
+ it("opens a new split when no sub-context matches the target view mode", async () => {
+ const triggerCommand = vi.fn();
+ const activeContext = {
+ getSubContexts: () => [
+ { viewScope: { viewMode: "default" }, ntxId: "ntx-last" }
+ ]
+ };
+ (window.glob as any).appContext = {
+ tabManager: { getActiveContext: () => activeContext },
+ triggerCommand
+ };
+ await openInReusableSplit("note1", "contextual-help", { hoistedNoteId: "h1" });
+ expect(triggerCommand).toHaveBeenCalledWith("openNewNoteSplit", {
+ ntxId: "ntx-last",
+ notePath: "note1",
+ hoistedNoteId: "h1",
+ viewScope: { viewMode: "contextual-help" }
+ });
+ });
+
+ it("reuses an existing matching split", async () => {
+ const setNote = vi.fn();
+ const activeContext = {
+ getSubContexts: () => [
+ { viewScope: { viewMode: "contextual-help" }, setNote }
+ ]
+ };
+ (window.glob as any).appContext = {
+ tabManager: { getActiveContext: () => activeContext },
+ triggerCommand: vi.fn()
+ };
+ await openInReusableSplit("note2", "contextual-help");
+ expect(setNote).toHaveBeenCalledWith("note2", { viewScope: { viewMode: "contextual-help" } });
+ });
+
+ it("openInAppHelpFromUrl delegates to openInReusableSplit with the _help_ prefix", async () => {
+ const setNote = vi.fn();
+ const activeContext = {
+ getSubContexts: () => [
+ { viewScope: { viewMode: "contextual-help" }, setNote }
+ ]
+ };
+ (window.glob as any).appContext = {
+ tabManager: { getActiveContext: () => activeContext },
+ triggerCommand: vi.fn()
+ };
+ await openInAppHelpFromUrl("MyPage");
+ expect(setNote).toHaveBeenCalledWith("_help_MyPage", { viewScope: { viewMode: "contextual-help" } });
+ });
});
diff --git a/apps/client/src/services/validation_error.spec.ts b/apps/client/src/services/validation_error.spec.ts
new file mode 100644
index 0000000000..f22b9d3e3d
--- /dev/null
+++ b/apps/client/src/services/validation_error.spec.ts
@@ -0,0 +1,20 @@
+import { describe, expect, it } from "vitest";
+
+import ValidationError from "./validation_error.js";
+
+describe("ValidationError", () => {
+ it("copies every key from the response onto the instance", () => {
+ const err = new ValidationError({ message: "bad request", status: 400 }) as any;
+
+ expect(err.message).toBe("bad request");
+ expect(err.status).toBe(400);
+ expect(err).toBeInstanceOf(ValidationError);
+ });
+
+ it("handles an empty response without copying any keys", () => {
+ const err = new ValidationError({}) as any;
+
+ expect(Object.keys(err)).toEqual([]);
+ expect(err).toBeInstanceOf(ValidationError);
+ });
+});
diff --git a/apps/client/src/services/ws.spec.ts b/apps/client/src/services/ws.spec.ts
new file mode 100644
index 0000000000..1bc5950e32
--- /dev/null
+++ b/apps/client/src/services/ws.spec.ts
@@ -0,0 +1,466 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+import type { WebSocketMessage } from "@triliumnext/commons";
+import { buildNote } from "../test/easy-froca";
+
+// Mutable spies the mocked dependencies delegate to, so we can assert on them
+// and swap behaviour per test without re-mocking.
+const toast = vi.hoisted(() => ({
+ showError: vi.fn(),
+ showMessage: vi.fn(),
+ showPersistent: vi.fn(),
+ closePersistent: vi.fn()
+}));
+const bundle = vi.hoisted(() => ({ getAndExecuteBundle: vi.fn() }));
+const appCtx = vi.hoisted(() => ({ triggerEvent: vi.fn() }));
+const frocaUpdater = vi.hoisted(() => ({ processEntityChanges: vi.fn(async () => {}) }));
+const utilsCtrl = vi.hoisted(() => ({
+ reloadFrontendApp: vi.fn(),
+ timeLimit: vi.fn(async (p: Promise<unknown>, _ms?: number) => p)
+}));
+const optionsCtrl = vi.hoisted(() => ({ is: vi.fn(() => false) }));
+
+vi.mock("./toast.js", () => ({ default: toast }));
+vi.mock("./bundle.js", () => ({ default: bundle }));
+vi.mock("../components/app_context.js", () => ({ default: appCtx }));
+vi.mock("./froca_updater.js", () => ({ default: frocaUpdater }));
+vi.mock("./options.js", () => ({ default: optionsCtrl }));
+vi.mock("./utils.js", async (orig) => {
+ const actual = (await orig()) as Record<string, unknown>;
+ return {
+ ...actual,
+ default: {
+ ...(actual.default as object),
+ now: () => "now",
+ reloadFrontendApp: (...args: unknown[]) => utilsCtrl.reloadFrontendApp(...args),
+ timeLimit: (...args: [Promise<unknown>, number]) => utilsCtrl.timeLimit(...args)
+ }
+ };
+});
+
+type WsModule = typeof import("./ws.js");
+
+/** Loads the REAL ws module (setup.ts globally mocks ./ws.js). */
+async function loadWs(): Promise<WsModule> {
+ return (await vi.importActual<WsModule>("./ws.js"));
+}
+
+const baseGlob = { isMainWindow: true } as any;
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ optionsCtrl.is.mockReturnValue(false);
+ utilsCtrl.timeLimit.mockImplementation(async (p: Promise<unknown>) => p);
+ frocaUpdater.processEntityChanges.mockImplementation(async () => {});
+ (window as any).glob = { ...baseGlob };
+ delete (window as any).electronApi;
+});
+
+afterEach(() => {
+ vi.useRealTimers();
+});
+
+describe("dispatchMessage", () => {
+ it("notifies subscribers and unsubscribes correctly", async () => {
+ const ws = await loadWs();
+ const received: WebSocketMessage[] = [];
+ const handler = (m: WebSocketMessage) => received.push(m);
+ ws.subscribeToMessages(handler);
+
+ const ping = { type: "ping" } as WebSocketMessage;
+ await ws.dispatchMessage(ping);
+ expect(received).toEqual([ping]);
+
+ ws.unsubscribeToMessage(handler);
+ await ws.dispatchMessage({ type: "ping" } as WebSocketMessage);
+ // unsubscribed -> no further messages
+ expect(received).toEqual([ping]);
+ });
+
+ it("routes each message type to the right side effect", async () => {
+ const ws = await loadWs();
+
+ await ws.dispatchMessage({ type: "reload-frontend", reason: "x" } as WebSocketMessage);
+ expect(utilsCtrl.reloadFrontendApp).toHaveBeenCalledWith(expect.stringContaining("reload"));
+
+ await ws.dispatchMessage({ type: "sync-hash-check-failed" } as any);
+ await ws.dispatchMessage({ type: "consistency-checks-failed" } as any);
+ expect(toast.showError).toHaveBeenCalledTimes(2);
+
+ await ws.dispatchMessage({ type: "api-log-messages", noteId: "n1", messages: ["a"] } as any);
+ expect(appCtx.triggerEvent).toHaveBeenCalledWith("apiLogMessages", { noteId: "n1", messages: ["a"] });
+
+ await ws.dispatchMessage({ type: "toast", message: "hi", timeout: 5 } as any);
+ expect(toast.showMessage).toHaveBeenCalledWith("hi", 5);
+ });
+
+ it("execute-script resolves the origin entity from froca when an id is present", async () => {
+ const ws = await loadWs();
+ const note = buildNote({ title: "Origin" });
+
+ await ws.dispatchMessage({
+ type: "execute-script",
+ originEntityId: note.noteId,
+ currentNoteId: "cur",
+ script: "return 1;",
+ params: [1, 2]
+ } as any);
+ expect(bundle.getAndExecuteBundle).toHaveBeenCalledWith("cur", note, "return 1;", [1, 2]);
+ });
+
+ it("execute-script passes a null origin entity when no id is provided", async () => {
+ const ws = await loadWs();
+
+ await ws.dispatchMessage({
+ type: "execute-script",
+ currentNoteId: "cur2",
+ script: "x",
+ params: []
+ } as any);
+ expect(bundle.getAndExecuteBundle).toHaveBeenCalledWith("cur2", null, "x", []);
+ });
+
+ it("ignores unknown message types", async () => {
+ const ws = await loadWs();
+ await ws.dispatchMessage({ type: "totally-unknown" } as any);
+ expect(toast.showError).not.toHaveBeenCalled();
+ expect(bundle.getAndExecuteBundle).not.toHaveBeenCalled();
+ });
+});
+
+describe("frontend-update / executeFrontendUpdate", () => {
+ it("does nothing extra when there are no entity changes", async () => {
+ const ws = await loadWs();
+ await ws.dispatchMessage({ type: "frontend-update", data: { entityChanges: [] } } as any);
+ expect(frocaUpdater.processEntityChanges).not.toHaveBeenCalled();
+ });
+
+ it("queues changes, tracks accepted ids and processes them once", async () => {
+ const ws = await loadWs();
+ const changes = [
+ { id: 5, entityName: "notes", entityId: "n1", isSynced: true },
+ { id: 7, entityName: "options", entityId: "openNoteContexts", isSynced: false },
+ { id: undefined, entityName: "notes", entityId: "n2" }
+ ];
+ await ws.dispatchMessage({ type: "frontend-update", data: { entityChanges: changes } } as any);
+
+ expect(frocaUpdater.processEntityChanges).toHaveBeenCalledTimes(1);
+ // synced id 5 advances the sync watermark
+ expect(ws.default.getMaxKnownEntityChangeSyncId()).toBeGreaterThanOrEqual(5);
+
+ // re-dispatching the same already-processed ids is a no-op for the updater
+ frocaUpdater.processEntityChanges.mockClear();
+ await ws.dispatchMessage({ type: "frontend-update", data: { entityChanges: [{ id: 5, entityName: "notes", entityId: "n1" }] } } as any);
+ expect(frocaUpdater.processEntityChanges).toHaveBeenCalledWith([]);
+ });
+
+ it("reloads the frontend when processing fails outside dev/debug mode", async () => {
+ const ws = await loadWs();
+ utilsCtrl.timeLimit.mockRejectedValueOnce(Object.assign(new Error("boom"), { stack: "stk" }));
+ optionsCtrl.is.mockReturnValue(false);
+ (window as any).glob.isDev = false;
+
+ await ws.dispatchMessage({ type: "frontend-update", data: { entityChanges: [{ id: 101, entityName: "notes", entityId: "nA" }] } } as any);
+ expect(utilsCtrl.reloadFrontendApp).toHaveBeenCalled();
+ });
+
+ it("shows a toast instead of reloading when debug mode is enabled", async () => {
+ const ws = await loadWs();
+ utilsCtrl.timeLimit.mockRejectedValueOnce(Object.assign(new Error("boom2"), { stack: "stk" }));
+ optionsCtrl.is.mockReturnValue(true);
+ (window as any).glob.isDev = false;
+
+ await ws.dispatchMessage({ type: "frontend-update", data: { entityChanges: [{ id: 102, entityName: "notes", entityId: "nB" }] } } as any);
+ expect(toast.showError).toHaveBeenCalled();
+ expect(utilsCtrl.reloadFrontendApp).not.toHaveBeenCalled();
+ });
+
+ it("serializes concurrent updates, and a later consumer finds the queue already drained", async () => {
+ const ws = await loadWs();
+ let resolveFirst!: () => void;
+ // Hold the first consumer open so the 2nd and 3rd dispatches both queue
+ // their changes behind it. When the first consumer's body finally runs,
+ // it drains ALL queued changes; the trailing consumer then sees an empty
+ // queue (the false branch of `frontendUpdateDataQueue.length > 0`).
+ frocaUpdater.processEntityChanges
+ .mockImplementationOnce(() => new Promise<void>((res) => { resolveFirst = () => res(); }))
+ .mockImplementation(async () => {});
+
+ const p1 = ws.dispatchMessage({ type: "frontend-update", data: { entityChanges: [{ id: 201, entityName: "notes", entityId: "q1" }] } } as any);
+ await Promise.resolve();
+ const p2 = ws.dispatchMessage({ type: "frontend-update", data: { entityChanges: [{ id: 202, entityName: "notes", entityId: "q2" }] } } as any);
+ const p3 = ws.dispatchMessage({ type: "frontend-update", data: { entityChanges: [{ id: 203, entityName: "notes", entityId: "q3" }] } } as any);
+
+ resolveFirst();
+ await Promise.all([p1, p2, p3]);
+ // first consumer (held) processed q1; the second consumer drained q2+q3;
+ // the third consumer found nothing left -> only 2 real processing calls
+ expect(frocaUpdater.processEntityChanges).toHaveBeenCalledTimes(2);
+ });
+});
+
+describe("waitForMaxKnownEntityChangeId", () => {
+ it("resolves immediately when the desired id is already processed", async () => {
+ const ws = await loadWs();
+ const server = (await import("./server.js")).default;
+ server.getMaxKnownEntityChangeId = vi.fn(() => 0);
+ await expect(ws.default.waitForMaxKnownEntityChangeId()).resolves.toBeUndefined();
+ });
+
+ it("waits for a pending id and resolves once changes catch up", async () => {
+ const ws = await loadWs();
+ const server = (await import("./server.js")).default;
+ // pick an id far above whatever has been processed by earlier tests
+ server.getMaxKnownEntityChangeId = vi.fn(() => 999999);
+
+ let resolved = false;
+ const wait = ws.default.waitForMaxKnownEntityChangeId().then(() => { resolved = true; });
+
+ // not yet
+ await Promise.resolve();
+ expect(resolved).toBe(false);
+
+ // a frontend-update past the desired id triggers checkEntityChangeIdListeners
+ await ws.dispatchMessage({ type: "frontend-update", data: { entityChanges: [{ id: 999999, entityName: "notes", entityId: "catchup" }] } } as any);
+ await wait;
+ expect(resolved).toBe(true);
+ });
+});
+
+describe("logError / logInfo / throwError and outgoing transport", () => {
+ it("throwError logs and throws", async () => {
+ const ws = await loadWs();
+ const errSpy = vi.spyOn(console, "error").mockImplementation(() => {});
+ expect(() => ws.throwError("kaboom")).toThrow("kaboom");
+ expect(errSpy).toHaveBeenCalled();
+ });
+
+ it("window.logError / window.logInfo are wired up", async () => {
+ await loadWs();
+ const errSpy = vi.spyOn(console, "error").mockImplementation(() => {});
+ const logSpy = vi.spyOn(console, "log").mockImplementation(() => {});
+ (window as any).logError("oops");
+ (window as any).logInfo("note");
+ expect(errSpy).toHaveBeenCalled();
+ expect(logSpy).toHaveBeenCalled();
+ });
+
+ it("sends outgoing log messages over the IPC bridge when present", async () => {
+ const send = vi.fn();
+ (window as any).electronApi = { ws: { send, onMessage: vi.fn() } };
+ vi.resetModules();
+ const ws = await loadWs();
+ vi.spyOn(console, "error").mockImplementation(() => {});
+
+ ws.logError("via-ipc");
+ expect(send).toHaveBeenCalledWith(expect.objectContaining({ type: "log-error", error: "via-ipc" }));
+ });
+});
+
+// --- Transport / module-load scenarios -------------------------------------
+// The `connectWebSocket`/`sendPing` paths and the top-level connection
+// bootstrap only run when the module is loaded in WebSocket mode with a live
+// `WebSocket` global, so we reload the module per scenario under fake timers.
+
+let lastSocket: FakeSocket;
+
+class FakeSocket {
+ static OPEN = 1;
+ static CLOSED = 3;
+ static CLOSING = 2;
+ OPEN = 1;
+ CLOSED = 3;
+ CLOSING = 2;
+ readyState = 1;
+ onopen: (() => void) | null = null;
+ onmessage: ((e: MessageEvent<string>) => void) | null = null;
+ sent: string[] = [];
+ url: string;
+ constructor(url: string) {
+ this.url = url;
+ lastSocket = this;
+ }
+ send(data: string) {
+ this.sent.push(data);
+ }
+}
+
+async function loadWsFresh(): Promise<WsModule> {
+ vi.resetModules();
+ return loadWs();
+}
+
+describe("WebSocket transport", () => {
+ beforeEach(() => {
+ vi.useFakeTimers();
+ (window as any).WebSocket = FakeSocket;
+ (window as any).glob = { ...baseGlob, dbInitialized: true };
+ vi.spyOn(console, "debug").mockImplementation(() => {});
+ vi.spyOn(console, "log").mockImplementation(() => {});
+ vi.spyOn(console, "warn").mockImplementation(() => {});
+ vi.spyOn(console, "error").mockImplementation(() => {});
+ });
+
+ it("connects on bootstrap, wiring onopen/onmessage and deriving the URI from the origin", async () => {
+ const ws = await loadWsFresh();
+ vi.advanceTimersByTime(0); // run the bootstrap setTimeout(..., 0)
+
+ expect(lastSocket).toBeTruthy();
+ // ws: scheme derived from non-https origin + host + pathname
+ expect(lastSocket.url.startsWith("ws:")).toBe(true);
+
+ // onopen just logs (debug) and onmessage dispatches a parsed message
+ lastSocket.onopen?.();
+ const handled: string[] = [];
+ ws.subscribeToMessages((m) => handled.push((m as any).type));
+ lastSocket.onmessage?.({ data: JSON.stringify({ type: "ping" }) } as MessageEvent<string>);
+ await vi.waitFor(() => expect(handled).toContain("ping"));
+ });
+
+ it("derives a wss:// URI from an https origin", async () => {
+ const realLocation = window.location;
+ (window as any).location = { protocol: "https:", host: "example.com", pathname: "/" };
+ try {
+ await loadWsFresh();
+ vi.advanceTimersByTime(0);
+ expect(lastSocket.url).toBe("wss://example.com/");
+ } finally {
+ (window as any).location = realLocation;
+ }
+ });
+
+ it("uses the injected wsBaseUrl when provided", async () => {
+ (window as any).glob = { ...baseGlob, dbInitialized: true, wsBaseUrl: "ws://127.0.0.1:9999/" };
+ await loadWsFresh();
+ vi.advanceTimersByTime(0);
+ expect(lastSocket.url).toBe("ws://127.0.0.1:9999/");
+ });
+
+ it("pings over an open socket and clears the lost-connection toast", async () => {
+ await loadWsFresh();
+ vi.advanceTimersByTime(0);
+ lastSocket.readyState = FakeSocket.OPEN;
+
+ // interval fires sendPing
+ vi.advanceTimersByTime(1000);
+ expect(toast.closePersistent).toHaveBeenCalledWith("lost-websocket-connection");
+ const ping = JSON.parse(lastSocket.sent.at(-1)!);
+ expect(ping.type).toBe("ping");
+ });
+
+ it("shows a persistent toast after the connection is considered lost", async () => {
+ await loadWsFresh();
+ vi.advanceTimersByTime(0);
+ lastSocket.readyState = FakeSocket.OPEN;
+
+ // advance > 30s so Date.now() - lastPingTs exceeds the threshold
+ vi.advanceTimersByTime(31000);
+ expect(toast.showPersistent).toHaveBeenCalledWith(expect.objectContaining({ id: "lost-websocket-connection" }));
+ });
+
+ it("reconnects when the socket is closed or closing", async () => {
+ await loadWsFresh();
+ vi.advanceTimersByTime(0);
+ const first = lastSocket;
+ first.readyState = FakeSocket.CLOSED;
+
+ vi.advanceTimersByTime(1000);
+ // a brand-new socket was created by connectWebSocket()
+ expect(lastSocket).not.toBe(first);
+ });
+
+ it("does not bootstrap a socket in print mode", async () => {
+ lastSocket = undefined as any;
+ (window as any).glob = { ...baseGlob, dbInitialized: true, device: "print" };
+ await loadWsFresh();
+ vi.advanceTimersByTime(0);
+ expect(lastSocket).toBeUndefined();
+ });
+
+ it("does not bootstrap a socket before the DB is initialized", async () => {
+ lastSocket = undefined as any;
+ (window as any).glob = { ...baseGlob, dbInitialized: false };
+ await loadWsFresh();
+ vi.advanceTimersByTime(0);
+ expect(lastSocket).toBeUndefined();
+ });
+
+ it("listens for worker custom events in standalone mode (no socket)", async () => {
+ lastSocket = undefined as any;
+ (window as any).glob = { ...baseGlob, dbInitialized: true, isStandalone: true };
+ const ws = await loadWsFresh();
+ vi.advanceTimersByTime(0);
+ expect(lastSocket).toBeUndefined();
+
+ const seen: string[] = [];
+ ws.subscribeToMessages((m) => seen.push((m as any).type));
+ window.dispatchEvent(new CustomEvent("trilium:ws-message", { detail: { type: "ping" } }));
+ expect(seen).toContain("ping");
+ });
+
+ it("listens over the IPC bridge in electron mode and pings without a socket", async () => {
+ lastSocket = undefined as any;
+ let ipcHandler: ((m: unknown) => void) | undefined;
+ const send = vi.fn();
+ (window as any).glob = { ...baseGlob, dbInitialized: true };
+ (window as any).electronApi = {
+ ws: {
+ send,
+ onMessage: (cb: (m: unknown) => void) => { ipcHandler = cb; return () => {}; }
+ }
+ };
+ const ws = await loadWsFresh();
+ vi.advanceTimersByTime(0);
+ expect(lastSocket).toBeUndefined();
+ expect(ipcHandler).toBeTypeOf("function");
+
+ const seen: string[] = [];
+ ws.subscribeToMessages((m) => seen.push((m as any).type));
+ ipcHandler?.({ type: "ping" });
+ await vi.waitFor(() => expect(seen).toContain("ping"));
+
+ // the interval ping uses sendOutgoing over IPC, not a socket
+ vi.advanceTimersByTime(1000);
+ expect(send).toHaveBeenCalledWith(expect.objectContaining({ type: "ping" }));
+ });
+
+ it("logError over the socket transport stringifies and sends when the socket is open", async () => {
+ const ws = await loadWsFresh();
+ vi.advanceTimersByTime(0);
+ lastSocket.readyState = FakeSocket.OPEN;
+ ws.logError("socket-error");
+ const payload = JSON.parse(lastSocket.sent.at(-1)!);
+ expect(payload).toMatchObject({ type: "log-error", error: "socket-error" });
+ });
+
+ it("sendOutgoing returns false (no message sent) when the socket is not open and no IPC bridge exists", async () => {
+ const ws = await loadWsFresh();
+ vi.advanceTimersByTime(0);
+ lastSocket.readyState = 0; // CONNECTING -> sendOutgoing's `readyState === 1` check fails
+ lastSocket.sent = [];
+ ws.logError("dropped");
+ // not open -> nothing queued on the socket
+ expect(lastSocket.sent).toEqual([]);
+ });
+});
+
+describe("checkEntityChangeIdListeners timeout logging", () => {
+ it("logs still-waiting listeners that started in the past", async () => {
+ const ws = await loadWs();
+ const server = (await import("./server.js")).default;
+ server.getMaxKnownEntityChangeId = vi.fn(() => 10_000_000);
+ const logSpy = vi.spyOn(console, "log").mockImplementation(() => {});
+
+ // register a listener that will stay pending
+ const wait = ws.default.waitForMaxKnownEntityChangeId();
+ // a frontend-update that does NOT reach the desired id still runs
+ // checkEntityChangeIdListeners, which logs the long-waiting listener
+ await ws.dispatchMessage({ type: "frontend-update", data: { entityChanges: [{ id: 1, entityName: "notes", entityId: "z" }] } } as any);
+ expect(logSpy.mock.calls.some((c) => String(c.join(" ")).includes("Waiting for entityChangeId"))).toBe(true);
+
+ // resolve it so the promise doesn't dangle
+ server.getMaxKnownEntityChangeId = vi.fn(() => 0);
+ await ws.dispatchMessage({ type: "frontend-update", data: { entityChanges: [{ id: 10_000_001, entityName: "notes", entityId: "z2" }] } } as any);
+ await wait;
+ });
+});
diff --git a/apps/client/src/services/ws.ts b/apps/client/src/services/ws.ts
index b807f10134..c38413e4c2 100644
--- a/apps/client/src/services/ws.ts
+++ b/apps/client/src/services/ws.ts
@@ -18,6 +18,7 @@ let ws: WebSocket;
// In Electron desktop, messaging goes over Chromium IPC (no TCP socket,
// no auth). The bridge is exposed by the preload script; when present we
// skip the WebSocket entirely.
+/* v8 ignore next -- `window` is always defined wherever this module loads (browser/electron); the SSR-style guard's else arm is unreachable */
const ipcWs = typeof window !== "undefined" ? window.electronApi?.ws : undefined;
let lastAcceptedEntityChangeId = window.glob.maxEntityChangeIdAtLoad ?? 0;
let lastAcceptedEntityChangeSyncId = window.glob.maxEntityChangeSyncIdAtLoad ?? 0;