Skip to content

Build your personal knowledge base with Trilium Notes

test(client): teach easy-froca inheritance and repeated attributes

Elian Doran124e02f9c571
diff --git a/apps/client/src/services/note_create.spec.ts b/apps/client/src/services/note_create.spec.ts
index 53664644cc..248ad0c9b6 100644
--- a/apps/client/src/services/note_create.spec.ts
+++ b/apps/client/src/services/note_create.spec.ts
@@ -1,9 +1,7 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
-import FAttribute from "../entities/fattribute.js";
import { buildNote } from "../test/easy-froca";
import froca from "./froca";
-import noteAttributeCache from "./note_attribute_cache.js";
import server from "./server.js";
import ws from "./ws.js";
@@ -341,16 +339,15 @@ describe("chooseNoteType", () => {
{ id: "people", title: "People" },
{ id: "advisors", title: "Advisors" },
{ id: "person-tpl", title: "Person", "#template": "", "~template:newNoteDefaultParent": "people" },
- { id: "multi-tpl", title: "Multi", "#template": "", "~template:newNoteDefaultParent": "people" },
- { id: "inheriting-tpl", title: "Inheriting", "#template": "" },
- { id: "overriding-tpl", title: "Overriding", "#template": "", "~template:newNoteDefaultParent": "people" },
+ { id: "multi-tpl", title: "Multi", "#template": "", "~template:newNoteDefaultParent": ["people", "advisors"] },
+ { id: "tpl-folder", title: "Templates", "~template:newNoteDefaultParent(inheritable)": "advisors", children: [
+ { id: "inheriting-tpl", title: "Inheriting", "#template": "" },
+ { id: "overriding-tpl", title: "Overriding", "#template": "", "~template:newNoteDefaultParent": "people" }
+ ] },
{ id: "plain-tpl", title: "Plain", "#template": "" }
]
});
expect(root.noteId).toBe("root");
- addOwnedRelation("multi-tpl", "template:newNoteDefaultParent", "advisors");
- addInheritedRelation("inheriting-tpl", "template:newNoteDefaultParent", "advisors");
- addInheritedRelation("overriding-tpl", "template:newNoteDefaultParent", "advisors");
function choose(response: Record<string, unknown>) {
triggerCommand.mockImplementation((_name: string, data: any) => data.callback(response));
@@ -428,36 +425,3 @@ describe("duplicateSubtree", () => {
expect(showMessage).toHaveBeenCalled();
});
});
-
-// easy-froca note definitions are object literals, so a repeated or inherited relation cannot be
-// declared there; these append the attribute to an already-built fixture note instead.
-
-function addOwnedRelation(noteId: string, name: string, value: string) {
- const note = froca.getNoteFromCache(noteId);
- if (!note) {
- throw new Error(`Missing fixture note '${noteId}'`);
- }
-
- const attr = buildRelation(noteId, name, value);
- froca.attributes[attr.attributeId] = attr;
- note.attributes.push(attr.attributeId);
- (noteAttributeCache.attributes[noteId] ??= []).push(attr);
-}
-
-/** The relation is served by the attribute cache (getRelations) but is owned by another note. */
-function addInheritedRelation(noteId: string, name: string, value: string) {
- const attr = buildRelation(`ancestor-of-${noteId}`, name, value);
- (noteAttributeCache.attributes[noteId] ??= []).push(attr);
-}
-
-function buildRelation(ownerNoteId: string, name: string, value: string) {
- return new FAttribute(froca, {
- noteId: ownerNoteId,
- attributeId: `${ownerNoteId}_${name}_${value}`,
- type: "relation",
- name,
- value,
- position: 100,
- isInheritable: false
- });
-}
diff --git a/apps/client/src/test/easy-froca.spec.ts b/apps/client/src/test/easy-froca.spec.ts
new file mode 100644
index 0000000000..0ac4338720
--- /dev/null
+++ b/apps/client/src/test/easy-froca.spec.ts
@@ -0,0 +1,72 @@
+import { describe, expect, it } from "vitest";
+
+import froca from "../services/froca.js";
+import { buildNote, buildNotes } from "./easy-froca.js";
+
+describe("buildNote", () => {
+ it("registers the note with its type, content and blob in the froca", async () => {
+ const note = buildNote({ title: "Code", type: "code", mime: "text/plain", content: "hello" });
+
+ expect(froca.getNoteFromCache(note.noteId)).toBe(note);
+ expect(note.type).toBe("code");
+ expect(note.mime).toBe("text/plain");
+ await expect(note.getContent()).resolves.toBe("hello");
+ await expect(note.getBlob().then((blob) => blob?.content)).resolves.toBe("hello");
+ });
+
+ it("links children to their parent in both directions, with branches", () => {
+ const parent = buildNote({ title: "Parent", children: [{ id: "kid", title: "Kid" }] });
+ const child = froca.getNoteFromCache("kid");
+
+ expect(parent.children).toEqual(["kid"]);
+ expect(child?.parents).toEqual([parent.noteId]);
+ expect(froca.getBranch(`${parent.noteId}_kid`)?.parentNoteId).toBe(parent.noteId);
+ });
+
+ it("creates owned labels via # and relations via ~", () => {
+ const note = buildNote({ title: "N", "#color": "red", "~template": "tpl" });
+
+ expect(note.getLabelValue("color")).toBe("red");
+ expect(note.getOwnedRelations("template").map((attr) => attr.value)).toEqual(["tpl"]);
+ });
+
+ it("creates one attribute per element when the value is an array, in order", () => {
+ const note = buildNote({ title: "N", "~worksFor": ["acme", "globex"], "#tag": ["a", "b"] });
+
+ expect(note.getRelations("worksFor").map((attr) => attr.value)).toEqual(["acme", "globex"]);
+ expect(note.getLabels("tag").map((attr) => attr.value)).toEqual(["a", "b"]);
+ });
+
+ it("spreads an (inheritable) attribute to every descendant, but keeps it off the owned set", () => {
+ buildNote({
+ id: "grandparent",
+ title: "Grandparent",
+ "#shared(inheritable)": "x",
+ children: [{
+ id: "parent-with-attrs",
+ title: "Parent",
+ // The cached attribute list is seeded from these, which is what would hide the
+ // inherited attribute without the spreading step.
+ "#own": "y",
+ children: [{ id: "grandchild", title: "Grandchild", "#own": "z" }]
+ }]
+ });
+
+ for (const noteId of ["parent-with-attrs", "grandchild"]) {
+ const note = froca.getNoteFromCache(noteId);
+ expect(note?.getLabelValue("shared"), noteId).toBe("x");
+ expect(note?.getOwnedLabelValue("shared"), noteId).toBeNull();
+ }
+ });
+
+ it("does not leak inheritable attributes to notes outside the subtree", () => {
+ buildNotes([
+ { id: "tree-a", title: "A", "#leaky(inheritable)": "x", children: [{ id: "a-kid", title: "AK" }] },
+ { id: "tree-b", title: "B", children: [{ id: "b-kid", title: "BK" }] }
+ ]);
+
+ expect(froca.getNoteFromCache("a-kid")?.getLabelValue("leaky")).toBe("x");
+ expect(froca.getNoteFromCache("tree-b")?.getLabelValue("leaky")).toBeNull();
+ expect(froca.getNoteFromCache("b-kid")?.getLabelValue("leaky")).toBeNull();
+ });
+});
diff --git a/apps/client/src/test/easy-froca.ts b/apps/client/src/test/easy-froca.ts
index 049ce07ad3..7d177b1788 100644
--- a/apps/client/src/test/easy-froca.ts
+++ b/apps/client/src/test/easy-froca.ts
@@ -8,8 +8,8 @@ import froca from "../services/froca.js";
import noteAttributeCache from "../services/note_attribute_cache.js";
import utils from "../services/utils.js";
-type AttributeDefinitions = { [key in `#${string}`]: string; };
-type RelationDefinitions = { [key in `~${string}`]: string; };
+type AttributeDefinitions = { [key in `#${string}`]: string | string[]; };
+type RelationDefinitions = { [key in `~${string}`]: string | string[]; };
interface NoteDefinition extends AttributeDefinitions, RelationDefinitions {
id?: string | undefined;
@@ -23,7 +23,10 @@ interface NoteDefinition extends AttributeDefinitions, RelationDefinitions {
/**
* Creates the given notes with the given title and optionally one or more attributes.
*
- * For a label to be created, simply pass on a key prefixed with `#` and any desired value.
+ * For a label to be created, simply pass on a key prefixed with `#` and any desired value; `~` makes
+ * a relation. An array value creates one attribute per element, since an object literal cannot repeat
+ * a key. An `(inheritable)` suffix on the name marks the attribute inheritable, and the descendants
+ * built here see it through `note.getAttributes()`, like in the application.
*
* The notes and attributes will be injected in the froca.
*
@@ -32,7 +35,8 @@ interface NoteDefinition extends AttributeDefinitions, RelationDefinitions {
* @example
* buildNotes([
* { title: "A", "#startDate": "2025-05-05" },
- * { title: "B", "#startDate": "2025-05-07" }
+ * { title: "B", "#startDate": "2025-05-07" },
+ * { title: "C", "#shared(inheritable)": "x", "~template": ["tpl1", "tpl2"] }
* ]);
*/
export function buildNotes(notes: NoteDefinition[]) {
@@ -71,53 +75,43 @@ export function buildNote(noteDef: NoteDefinition) {
note.getBlob = async () => blob;
let position = 0;
- for (const [ key, value ] of Object.entries(noteDef)) {
- const attributeId = utils.randomString(12);
+ for (const [ key, rawValue ] of Object.entries(noteDef)) {
+ if (!key.startsWith("#") && !key.startsWith("~")) {
+ continue;
+ }
+
+ const type = key.startsWith("#") ? "label" : "relation";
let name = key.substring(1);
- const isInheritable = key.endsWith("(inheritable)");
+ const isInheritable = name.endsWith("(inheritable)");
if (isInheritable) {
name = name.substring(0, name.length - "(inheritable)".length);
}
- let attribute: FAttribute | null = null;
- if (key.startsWith("#")) {
- attribute = new FAttribute(froca, {
+ // An array stands for several attributes of the same name.
+ const values = Array.isArray(rawValue) ? rawValue : [ rawValue as string ];
+ for (const value of values) {
+ const attributeId = utils.randomString(12);
+ const attribute = new FAttribute(froca, {
noteId: note.noteId,
attributeId,
- type: "label",
+ type,
name,
value,
position,
isInheritable
});
- }
-
- if (key.startsWith("~")) {
- attribute = new FAttribute(froca, {
- noteId: note.noteId,
- attributeId,
- type: "relation",
- name,
- value,
- position,
- isInheritable
- });
- }
-
- if (!attribute) {
- continue;
- }
- froca.attributes[attributeId] = attribute;
- note.attributes.push(attributeId);
- position++;
+ froca.attributes[attributeId] = attribute;
+ note.attributes.push(attributeId);
+ position++;
- // Inject the attribute into the note attribute cache, since FNote.getAttribute() doesn't always work.
- // If we add support for templates into froca, this might cause issues.
- if (!noteAttributeCache.attributes[note.noteId]) {
- noteAttributeCache.attributes[note.noteId] = [];
+ // Inject the attribute into the note attribute cache, since FNote.getAttribute() doesn't always work.
+ // If we add support for templates into froca, this might cause issues.
+ if (!noteAttributeCache.attributes[note.noteId]) {
+ noteAttributeCache.attributes[note.noteId] = [];
+ }
+ noteAttributeCache.attributes[note.noteId].push(attribute);
}
- noteAttributeCache.attributes[note.noteId].push(attribute);
}
// Manage children.
@@ -137,7 +131,41 @@ export function buildNote(noteDef: NoteDefinition) {
childNote.addParent(note.noteId, branchId, false);
childNotePosition += 10;
}
+
+ spreadInheritableAttributes(note);
}
return note;
}
+
+/**
+ * Appends the note's inheritable attributes (own and already-inherited alike) to the cached
+ * attribute list of every descendant, the way the application's attribute inheritance resolves
+ * them. Needed because a note whose attributes were seeded into the cache above never computes
+ * its inherited ones.
+ */
+function spreadInheritableAttributes(note: FNote) {
+ const inheritableAttributes =
+ (noteAttributeCache.attributes[note.noteId] ?? []).filter((attr) => attr.isInheritable);
+ if (inheritableAttributes.length === 0) {
+ return;
+ }
+
+ for (const childNoteId of note.children) {
+ const childNote = froca.getNoteFromCache(childNoteId);
+ if (!childNote) {
+ continue;
+ }
+
+ if (!noteAttributeCache.attributes[childNoteId]) {
+ noteAttributeCache.attributes[childNoteId] = [];
+ }
+ for (const attr of inheritableAttributes) {
+ if (!noteAttributeCache.attributes[childNoteId].includes(attr)) {
+ noteAttributeCache.attributes[childNoteId].push(attr);
+ }
+ }
+
+ spreadInheritableAttributes(childNote);
+ }
+}