Skip to content

Build your personal knowledge base with Trilium Notes

fix(attributes): clipboard and selection defects found in review

Elian Doran572724332e80
diff --git a/apps/client/src/services/attribute_clipboard.spec.ts b/apps/client/src/services/attribute_clipboard.spec.ts
index d4f9e3cd1b..bba7e6c6d9 100644
--- a/apps/client/src/services/attribute_clipboard.spec.ts
+++ b/apps/client/src/services/attribute_clipboard.spec.ts
@@ -50,6 +50,13 @@ describe("serializeAttributes", () => {
{ type: "relation", name: "parent", value: "abc123", isInheritable: false }
]);
});
+
+ it("keeps backslashes, which the parser reads as escapes inside quotes as well", () => {
+ const values = [ "C:\\notes", "ends with\\", "\"a\" 'b' `c` \\d" ];
+
+ expect(attribute_parser.lexAndParse(serializeAttributes(values.map((value) => label("path", value))))
+ .map((attribute) => attribute.value)).toEqual(values);
+ });
});
describe("serializeAttributesAsHtml", () => {
@@ -114,8 +121,11 @@ describe("writeAttributes", () => {
writeAttributes(null, copied);
expect(getHeldAttributes()).toEqual(copied);
- // A copy of the list, so that editing the rows it was taken from does not edit the clipboard.
+ // A copy of the list and of each attribute, so that editing the rows it was taken from does
+ // not edit the clipboard.
expect(getHeldAttributes()).not.toBe(copied);
+ copied[0].value = "Someone else";
+ expect(getHeldAttributes()[0].value).toBe("Elian");
writeAttributes(null, []);
expect(getHeldAttributes()).toEqual([]);
@@ -167,6 +177,25 @@ describe("mergePastedAttributes", () => {
expect(added).toBe(1);
});
+ it("reads whether a name holds a set from a definition pasted alongside it, over the note's own", () => {
+ const { attributes } = mergePastedAttributes(
+ [ label("tag", "book") ],
+ [ label("label:tag", "promoted,multi"), label("tag", "read"), label("status", "draft") ],
+ single
+ );
+ expect(attributes.filter((attribute) => attribute.name === "tag").map((attribute) => attribute.value))
+ .toEqual([ "book", "read" ]);
+
+ // A pasted single-valued definition replaces what the note defined as a set.
+ const { attributes: replaced } = mergePastedAttributes(
+ [ label("tag", "book") ],
+ [ label("tag", "read"), label("label:tag", "promoted,single") ],
+ () => true
+ );
+ expect(replaced.filter((attribute) => attribute.name === "tag").map((attribute) => attribute.value))
+ .toEqual([ "read" ]);
+ });
+
it("tells a label from a relation of the same name", () => {
const { attributes } = mergePastedAttributes([ label("owner", "me") ], [ relation("owner", "abc123") ], single);
diff --git a/apps/client/src/services/attribute_clipboard.ts b/apps/client/src/services/attribute_clipboard.ts
index cbcc520ddd..d9cf1ad64f 100644
--- a/apps/client/src/services/attribute_clipboard.ts
+++ b/apps/client/src/services/attribute_clipboard.ts
@@ -1,3 +1,5 @@
+import { promotedAttributeDefinitionParser } from "@triliumnext/commons";
+
import attribute_parser, { Attribute } from "./attribute_parser.js";
import { formatValue } from "./attribute_renderer.js";
import froca from "./froca.js";
@@ -40,7 +42,7 @@ export function getHeldAttributes(): Attribute[] {
* all — is settled at once, rather than after a round trip to the system clipboard.
*/
export function holdAttributes(attributes: Attribute[]) {
- held = [ ...attributes ];
+ held = attributes.map((attribute) => ({ ...attribute }));
}
/** Reads whichever flavour the clipboard offers. Throws what the parser throws over text that is not
@@ -196,6 +198,7 @@ export interface PasteResult {
* already taken depends on what the name is defined as: a field holding a set takes another entry
* (unless it already holds that very one — pasting the same thing twice is not two of it), while a
* field holding one value has that value replaced, the attribute itself staying the one it was.
+ * A definition in the paste takes precedence over `isMultiValued`, which reads the note's own.
*
* Nothing is carried over from the attribute a paste came from beyond what is written down: the
* parser builds its attributes out of text alone, so none of them arrives with an id, and pasting is
@@ -209,6 +212,12 @@ export function mergePastedAttributes(
const attributes = [ ...existing ];
let added = 0;
let replaced = 0;
+ const pastedMultiplicity = new Map(pasted
+ .filter((attribute) => attribute.type === "label" && /^(label|relation):/.test(attribute.name))
+ .map((attribute) => [
+ attribute.name,
+ promotedAttributeDefinitionParser.parse(attribute.value ?? "").multiplicity === "multi"
+ ]));
for (const incoming of pasted) {
const candidate: Attribute = {
@@ -219,7 +228,7 @@ export function mergePastedAttributes(
};
const matches = (attribute: Attribute) => attribute.type === candidate.type && attribute.name === candidate.name;
- if (isMultiValued(candidate)) {
+ if (pastedMultiplicity.get(`${candidate.type}:${candidate.name}`) ?? isMultiValued(candidate)) {
if (!attributes.some((attribute) => matches(attribute) && (attribute.value ?? "") === candidate.value)) {
attributes.push(candidate);
added++;
diff --git a/apps/client/src/services/attribute_renderer.ts b/apps/client/src/services/attribute_renderer.ts
index 1dfe770be4..edc4e00963 100644
--- a/apps/client/src/services/attribute_renderer.ts
+++ b/apps/client/src/services/attribute_renderer.ts
@@ -40,14 +40,18 @@ async function renderAttribute(attribute: FAttribute, renderIsInheritable: boole
export function formatValue(val: string) {
if (/^[\p{L}\p{N}\-_,.]+$/u.test(val)) {
return val;
- } else if (!val.includes('"')) {
- return `"${val}"`;
+ }
+
+ // The lexer reads a backslash as an escape inside quotes too.
+ const escaped = val.replace(/\\/g, "\\\\");
+ if (!val.includes('"')) {
+ return `"${escaped}"`;
} else if (!val.includes("'")) {
- return `'${val}'`;
+ return `'${escaped}'`;
} else if (!val.includes("`")) {
- return `\`${val}\``;
+ return `\`${escaped}\``;
} else {
- return `"${val.replace(/"/g, '\\"')}"`;
+ return `"${escaped.replace(/"/g, '\\"')}"`;
}
}
diff --git a/apps/client/src/widgets/sidebar/AttributeList.mobile.spec.tsx b/apps/client/src/widgets/sidebar/AttributeList.mobile.spec.tsx
index b7fee2fb41..847cbea0b3 100644
--- a/apps/client/src/widgets/sidebar/AttributeList.mobile.spec.tsx
+++ b/apps/client/src/widgets/sidebar/AttributeList.mobile.spec.tsx
@@ -58,15 +58,15 @@ describe("AttributeList on a phone", () => {
it("draws a card per run", () => {
renderPanel(noteWithRuns());
- expect(sectionIds()).toEqual([ "attributes-owned", "attributes-inherited", "attributes-definitions" ]);
+ expect(sectionIds()).toEqual([ "attributes", "attributes-inherited", "attributes-definitions" ]);
// Each card counts its rows in its title.
- expect(section("attributes-owned").querySelector(".attribute-run-count")?.textContent).toBe("2");
+ expect(section("attributes").querySelector(".attribute-run-count")?.textContent).toBe("2");
expect(section("attributes-definitions").querySelector(".attribute-run-count")?.textContent).toBe("2");
// The rows themselves are unchanged — menu items, which is what a phone's lists are made of.
- expect(namesIn(section("attributes-owned"))).toEqual([ "author", "template" ]);
- expect(section("attributes-owned").querySelector(".attribute-row")?.className).toContain("dropdown-item");
+ expect(namesIn(section("attributes"))).toEqual([ "author", "template" ]);
+ expect(section("attributes").querySelector(".attribute-row")?.className).toContain("dropdown-item");
});
it("adds from the toolbar and the cards' own headers, there being no row to hover for one", () => {
@@ -75,7 +75,7 @@ describe("AttributeList on a phone", () => {
// The toolbar's menu adds any kind; it is also the only way to a relation here, whose creation
// editor is a pointer's.
expect(iconsIn(toolbar())).toEqual([ "bx bx-plus" ]);
- expect(iconsIn(header("attributes-owned"))).toEqual([ "bx bx-help-circle" ]);
+ expect(iconsIn(header("attributes"))).toEqual([ "bx bx-help-circle" ]);
// Each card has its own help. A run that can be added to also has an add button, definitions
// included; the inherited run, whose attributes belong to another note, has none.
expect(iconsIn(header("attributes-definitions"))).toEqual([ "bx bx-help-circle", "bx bx-plus" ]);
@@ -92,9 +92,9 @@ describe("AttributeList on a phone", () => {
// in the card's header, so there is no add row inside it to imply the run is waiting to be
// filled. AttributeList.spec asserts the other half — that a pointer gets no such notice.
expect(container.querySelectorAll(".attribute-row")).toHaveLength(0);
- expect(section("attributes-owned").querySelector(".no-items")).not.toBeNull();
+ expect(section("attributes").querySelector(".no-items")).not.toBeNull();
// Only the note's own run is ever shown empty; the rest are left out when they hold nothing.
- expect(sectionIds()).toEqual([ "attributes-owned" ]);
+ expect(sectionIds()).toEqual([ "attributes" ]);
});
it("offers pasting from the toolbar, which is a phone's only way to it", async () => {
@@ -136,7 +136,7 @@ describe("AttributeList on a phone", () => {
vi.useFakeTimers();
renderPanel(noteWithRuns());
- const row = section("attributes-owned").querySelector(".attribute-row");
+ const row = section("attributes").querySelector(".attribute-row");
act(() => {
row?.dispatchEvent(new Event("touchstart", { bubbles: true }));
});
@@ -151,7 +151,7 @@ describe("AttributeList on a phone", () => {
// The toolbar above the cards turns over to the selection.
expect(iconsIn(toolbar())).toEqual([ "bx bx-copy", "bx bx-trash", "bx bx-plus" ]);
- expect(toolbar()?.compareDocumentPosition(section("attributes-owned")))
+ expect(toolbar()?.compareDocumentPosition(section("attributes")))
.toBe(Node.DOCUMENT_POSITION_FOLLOWING);
});
@@ -162,7 +162,7 @@ describe("AttributeList on a phone", () => {
function sectionIds() {
return [ ...container.querySelectorAll(".options-section") ]
- .map((el) => [ ...el.classList ].find((name) => name.startsWith("attributes-")));
+ .map((el) => [ ...el.classList ].find((name) => /^attributes(-|$)/.test(name)));
}
function toolbar() {
diff --git a/apps/client/src/widgets/sidebar/AttributeList.spec.tsx b/apps/client/src/widgets/sidebar/AttributeList.spec.tsx
index 9370fa1e8e..5ec039ec51 100644
--- a/apps/client/src/widgets/sidebar/AttributeList.spec.tsx
+++ b/apps/client/src/widgets/sidebar/AttributeList.spec.tsx
@@ -189,14 +189,14 @@ describe("AttributeList", () => {
// Each card counts its rows in its title.
expect(card("attributes-inherited").querySelector(".attribute-run-count")?.textContent).toBe("2");
- expect(cardIds()).toEqual([ "attributes-owned", "attributes-inherited", "attributes-definitions" ]);
- expect(namesIn(card("attributes-owned"))).toEqual([ "author", "cssClass", "template" ]);
+ expect(cardIds()).toEqual([ "attributes", "attributes-inherited", "attributes-definitions" ]);
+ expect(namesIn(card("attributes"))).toEqual([ "author", "cssClass", "template" ]);
expect(namesIn(card("attributes-inherited"))).toEqual([ "inheritedLabel", "archived" ]);
// The definitions of both notes share a group, the note's own first, and lose their prefix.
expect(namesIn(card("attributes-definitions"))).toEqual([ "priority", "status" ]);
// The kind is carried by the icon; a definition takes the icon of the field it sets up.
- expect(iconsIn(card("attributes-owned"))).toEqual([ "bx bx-hash", "bx bx-hash", "bx bx-transfer" ]);
+ expect(iconsIn(card("attributes"))).toEqual([ "bx bx-hash", "bx bx-hash", "bx bx-transfer" ]);
// The icon also carries the row's one tooltip — the row itself has none to compete with it.
// Only its presence: the wording is translated, and translations stay unloaded here.
@@ -206,14 +206,14 @@ describe("AttributeList", () => {
expect(iconsIn(card("attributes-definitions"))).toEqual([ "bx bx-calendar", "bx bx-text" ]);
// The names Trilium reads for itself come last, below a rule, and are marked as such.
- expect(card("attributes-owned").querySelectorAll("hr.attribute-rows-divider")).toHaveLength(1);
- expect([ ...card("attributes-owned").querySelectorAll(".attribute-kind") ]
+ expect(card("attributes").querySelectorAll("hr.attribute-rows-divider")).toHaveLength(1);
+ expect([ ...card("attributes").querySelectorAll(".attribute-kind") ]
.map((kind) => kind.className.includes("marker-system")))
.toEqual([ false, true, true ]);
// A row of the note's own is deletable and unattributed; an inherited one names its note instead.
- expect(card("attributes-owned").querySelectorAll(".attribute-delete-button")).toHaveLength(3);
- expect(card("attributes-owned").querySelectorAll(".attribute-owner")).toHaveLength(0);
+ expect(card("attributes").querySelectorAll(".attribute-delete-button")).toHaveLength(3);
+ expect(card("attributes").querySelectorAll(".attribute-owner")).toHaveLength(0);
expect(card("attributes-inherited").querySelectorAll(".attribute-delete-button")).toHaveLength(0);
expect(card("attributes-inherited").querySelectorAll(".attribute-owner")).toHaveLength(2);
// Only what the note may edit is deletable, whichever run it is in.
@@ -231,9 +231,9 @@ describe("AttributeList", () => {
note.isContentWritable = false;
renderPanel(note);
- expect(namesIn(card("attributes-owned"))).toEqual([ "author", "cssClass", "template" ]);
+ expect(namesIn(card("attributes"))).toEqual([ "author", "cssClass", "template" ]);
// Read as any other note's: Trilium's own names below the rule, inherited ones naming their note.
- expect(card("attributes-owned").querySelectorAll("hr.attribute-rows-divider")).toHaveLength(1);
+ expect(card("attributes").querySelectorAll("hr.attribute-rows-divider")).toHaveLength(1);
expect(card("attributes-inherited").querySelectorAll(".attribute-owner")).toHaveLength(2);
expect(container.querySelectorAll(".attribute-delete-button")).toHaveLength(0);
expect(container.querySelectorAll(".attribute-edit-button")).toHaveLength(0);
@@ -242,12 +242,14 @@ describe("AttributeList", () => {
});
it("collapses a card by its header, and remembers it collapsed", async () => {
- options.set("rightPaneCollapsedItems", JSON.stringify([ "attributes-inherited" ]));
+ options.set("rightPaneCollapsedItems", JSON.stringify([ "attributes-inherited", "attributes" ]));
renderPanel(noteWithAttributes());
- // A card remembered as collapsed renders without its rows.
+ // A card remembered as collapsed renders without its rows. The owned card reads the key the
+ // whole panel was remembered under before it was split into cards.
expect(card("attributes-inherited").className).toContain("collapsed");
expect(namesIn(card("attributes-inherited"))).toEqual([]);
+ expect(card("attributes").className).toContain("collapsed");
await act(async () => cardHeader("attributes-inherited").click());
expect(card("attributes-inherited").className).not.toContain("collapsed");
@@ -261,7 +263,7 @@ describe("AttributeList", () => {
// A note with one card has nothing to collapse it in favor of.
render(null, container);
renderPanel(buildNote({ id: "bare", title: "Bare", "#author": "Elian" }));
- expect(card("attributes-owned").className).toContain("not-collapsible");
+ expect(card("attributes").className).toContain("not-collapsible");
});
it("leaves a note carrying no attributes its heading and the way in, and says nothing besides", () => {
@@ -272,9 +274,9 @@ describe("AttributeList", () => {
// would be a third telling of the one fact, and the loudest of the three at that.
expect(container.querySelectorAll(".attribute-row")).toHaveLength(0);
expect(container.querySelector(".no-items")).toBeNull();
- expect(cardIds()).toEqual([ "attributes-owned" ]);
- expect(card("attributes-owned").querySelector(".attribute-run-count")?.textContent).toBe("0");
- expect(card("attributes-owned").querySelector(".attribute-add-row")).not.toBeNull();
+ expect(cardIds()).toEqual([ "attributes" ]);
+ expect(card("attributes").querySelector(".attribute-run-count")?.textContent).toBe("0");
+ expect(card("attributes").querySelector(".attribute-add-row")).not.toBeNull();
// Adding takes the placeholder's place: there is a row again, draft though it still is.
act(() => container.querySelector<HTMLElement>(".attribute-add-row")?.click());
@@ -287,14 +289,14 @@ describe("AttributeList", () => {
const note = buildNote({ id: "linking", title: "Linking", "#author": "Elian", "~internalLink": "target" });
renderPanel(note);
- expect(cardIds()).toEqual([ "attributes-owned" ]);
+ expect(cardIds()).toEqual([ "attributes" ]);
// Unmounted first, the panel collecting the attributes of the note it is handed as it mounts.
setDevBuild(true);
render(null, container);
renderPanel(note);
- expect(cardIds()).toEqual([ "attributes-owned", "attributes-internal" ]);
+ expect(cardIds()).toEqual([ "attributes", "attributes-internal" ]);
const internal = card("attributes-internal");
expect(namesIn(internal)).toEqual([ "internalLink" ]);
// Nothing on such a row is the note's to change, and nothing marks it as Trilium's own: the
@@ -479,7 +481,7 @@ describe("AttributeList", () => {
// ...in a row at the foot of the list, where the press that opened it was — and not where
// the sort would file a name it does not have yet, above the ones Trilium reads for itself.
- const ownedRun = card("attributes-owned");
+ const ownedRun = card("attributes");
expect(namesIn(ownedRun)).toEqual([ "author", "cssClass", "template", "" ]);
expect([ ...ownedRun.querySelectorAll(".attribute-row") ].at(-1)?.contains(editor ?? null)).toBe(true);
@@ -869,6 +871,36 @@ describe("AttributeList", () => {
expect(container.querySelector(".attribute-creation-editor")).toBeNull();
});
+ it("leaves the paste key and the right press inside an open field to the field", async () => {
+ holdAttributes([ plain("held") ]);
+ renderPanel(noteWithAttributes());
+
+ act(() => firstRow().querySelector<HTMLElement>(".attribute-value")?.click());
+ const input = container.querySelector<HTMLInputElement>(".attribute-value-editor input");
+ expect(input).not.toBeNull();
+
+ const paste = clipboardEvent("paste", { getData: (type: string) => type === "text/plain" ? "#tag=new" : "" });
+ await act(async () => void input?.dispatchEvent(paste));
+ expect(paste.defaultPrevented).toBe(false);
+ expect(put).not.toHaveBeenCalled();
+ expect(container.querySelector(".attribute-value-editor")).not.toBeNull();
+
+ const valuePress = new MouseEvent("contextmenu", { bubbles: true, cancelable: true });
+ act(() => void input?.dispatchEvent(valuePress));
+ expect(valuePress.defaultPrevented).toBe(false);
+
+ // The creation row stands outside any row, where the panel's own menu would take the press.
+ act(() => container.querySelector<HTMLElement>(".attribute-add-row")?.click());
+ const nameField = container.querySelector<HTMLInputElement>(".attribute-creation-editor input");
+ expect(nameField).not.toBeNull();
+ const namePress = new MouseEvent("contextmenu", { bubbles: true, cancelable: true });
+ act(() => void nameField?.dispatchEvent(namePress));
+ expect(namePress.defaultPrevented).toBe(false);
+ expect(showContextMenu).not.toHaveBeenCalled();
+
+ holdAttributes([]);
+ });
+
it("discards what the popup was told when it is closed rather than pressed away from", async () => {
renderPanel(noteWithAttributes());
@@ -925,6 +957,21 @@ describe("AttributeList", () => {
expect(document.querySelector(".attr-detail")).not.toBeNull();
});
+ it("draws a range from the last row still picked out once the anchor row is deleted elsewhere", () => {
+ const note = noteWithAttributes();
+ renderPanel(note, true);
+
+ pick(1, { ctrlKey: true });
+ pick(0, { ctrlKey: true });
+ note.attributes = note.attributes.filter((attributeId) => froca.attributes[attributeId]?.name !== "author");
+ act(() => fireEntitiesReloaded(() => affectingRows(note)));
+ expect(selectedNames()).toEqual([ "cssClass" ]);
+
+ // The rows are now cssClass, template, then the inherited card's inheritedLabel.
+ pick(2, { shiftKey: true });
+ expect(selectedNames()).toEqual([ "cssClass", "template", "inheritedLabel" ]);
+ });
+
it("keeps a press on a picked row from whatever it lands on within it", () => {
renderPanel(noteWithAttributes());
diff --git a/apps/client/src/widgets/sidebar/AttributeList.tsx b/apps/client/src/widgets/sidebar/AttributeList.tsx
index 7b5d22325f..cca832eb3e 100644
--- a/apps/client/src/widgets/sidebar/AttributeList.tsx
+++ b/apps/client/src/widgets/sidebar/AttributeList.tsx
@@ -362,7 +362,10 @@ export default function AttributeList() {
setSelection(new Set(selectableIds));
}
- /** Drops from the selection whatever the note no longer holds, so what is copied is what is shown. */
+ /**
+ * Drops from the selection whatever the note no longer holds, so what is copied is what is shown.
+ * A dropped anchor moves to the row picked out last among those left.
+ */
function pruneSelection() {
setSelection((current) => {
if (current.size === 0) {
@@ -372,6 +375,10 @@ export default function AttributeList() {
const shown = new Set([ ...owned.current, ...inherited.current ].flatMap((attribute) => attribute.attributeId ?? []));
const next = new Set([ ...current ].filter((attributeId) => shown.has(attributeId)));
+ if (selectionAnchor.current && !shown.has(selectionAnchor.current)) {
+ selectionAnchor.current = [ ...next ].at(-1) ?? null;
+ }
+
return next.size === current.size ? current : next;
});
}
@@ -445,7 +452,7 @@ export default function AttributeList() {
* from either lands here whole, as does one written out by hand.
*/
async function pasteAttributes(e: ClipboardEvent) {
- if (!canEdit) {
+ if (!canEdit || isInEditor(e)) {
return;
}
e.preventDefault();
@@ -498,6 +505,9 @@ export default function AttributeList() {
* the source note's to delete.
*/
function showRowMenu(attribute: Attribute, e: MouseEvent) {
+ if (isInEditor(e)) {
+ return;
+ }
e.preventDefault();
e.stopPropagation();
@@ -549,7 +559,7 @@ export default function AttributeList() {
*/
function showPanelMenu(e: MouseEvent) {
const items = pasteMenuItems();
- if (items.length === 0) {
+ if (items.length === 0 || isInEditor(e)) {
return;
}
@@ -612,7 +622,7 @@ export default function AttributeList() {
}
},
onMouseDownCapture: (e: MouseEvent) => {
- if (e.target instanceof Element && e.target.closest(".attribute-editor-overlay")) {
+ if (isInEditor(e)) {
return;
}
@@ -695,7 +705,7 @@ export default function AttributeList() {
};
// The runs of the panel, in display order; each is drawn as a card.
const runs: AttributeRun[] = [ {
- id: "attributes-owned",
+ id: "attributes",
title: t("attribute_list_panel.section_owned"),
count: sections.owned.length,
help: "attributes",
@@ -1319,6 +1329,11 @@ export function isMultiValued(note: FNote | null | undefined, attribute: Attribu
return definition?.multiplicity === "multi";
}
+/** Whether the event comes from an inline editor's field, whose own clipboard and menu it is left to. */
+function isInEditor(e: Event) {
+ return e.target instanceof Element && !!e.target.closest(".attribute-editor-overlay");
+}
+
/**
* The badge the kind icon carries on its corner, where there is one to carry: a cog for the names
* Trilium reads for itself, and a chevron for a definition whose field is promoted — lifted, that is,