Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
feat(attributes): select and copy/paste attributes in the sidebar panel
Elian Doran1389e69080d2
diff --git a/apps/client/src/services/attribute_clipboard.spec.ts b/apps/client/src/services/attribute_clipboard.spec.tsnew file mode 100644index 0000000000..ab30396a03--- /dev/null+++ b/apps/client/src/services/attribute_clipboard.spec.ts@@ -0,0 +1,207 @@+import { describe, expect, it, vi } from "vitest";++// Only the titles of the notes relations point at are read, and only to make the links readable.+const titles: Record<string, string> = { abc123: "Some note", evil: "Tom & <Jerry>" };+vi.mock("./froca", () => ({+ default: {+ getNoteFromCache: (noteId: string) => titles[noteId] ? { title: titles[noteId] } : undefined+ }+}));++import attribute_parser, { Attribute } from "./attribute_parser";+import {+ getHeldAttributes,+ getPreprocessedData,+ mergePastedAttributes,+ readAttributes,+ serializeAttributes,+ serializeAttributesAsHtml,+ writeAttributes+} from "./attribute_clipboard";++describe("serializeAttributes", () => {+ it("writes the attributes as the line the attributes editor spells them out in", () => {+ expect(serializeAttributes([+ label("author", "Elian"),+ label("archived"),+ { ...label("tag", "to read"), isInheritable: true },+ relation("parent", "abc123")+ ])).toBe("#author=Elian #archived #tag(inheritable)=\"to read\" ~parent=#root/abc123");+ });++ it("leaves out a relation with no target, which there is nothing to write down for", () => {+ expect(serializeAttributes([ relation("parent", ""), label("kept", "yes") ])).toBe("#kept=yes");+ });++ it("round-trips through the parser, values needing quotes and all", () => {+ const attributes = [+ label("author", "Elian"),+ label("quote", 'he said "hi"'),+ label("bare"),+ { ...label("inherited", "yes"), isInheritable: true },+ relation("parent", "abc123")+ ];++ expect(attribute_parser.lexAndParse(serializeAttributes(attributes))).toMatchObject([+ { type: "label", name: "author", value: "Elian", isInheritable: false },+ { type: "label", name: "quote", value: 'he said "hi"', isInheritable: false },+ { type: "label", name: "bare", isInheritable: false },+ { type: "label", name: "inherited", value: "yes", isInheritable: true },+ { type: "relation", name: "parent", value: "abc123", isInheritable: false }+ ]);+ });+});++describe("serializeAttributesAsHtml", () => {+ it("writes the relations as the reference links the editor holds, the title standing for the path", () => {+ expect(serializeAttributesAsHtml([ label("author", "Elian"), relation("parent", "abc123") ]))+ .toBe('#author=Elian ~parent=<a href="#root/abc123" class="reference-link">Some note</a>');+ });++ it("names an unknown target by its id, there being no title to show for it", () => {+ expect(serializeAttributesAsHtml([ relation("parent", "unknown") ]))+ .toContain(">unknown</a>");+ });++ it("leaves a title that looks like markup a title", () => {+ expect(serializeAttributesAsHtml([ relation("parent", "evil") ]))+ .toContain(">Tom & <Jerry></a>");+ });++ it("reads back as the text it stands for", () => {+ const html = serializeAttributesAsHtml([ label("author", "Elian"), relation("parent", "abc123") ]);++ expect(getPreprocessedData(html)).toBe("#author=Elian ~parent=#root/abc123");+ });+});++describe("readAttributes", () => {+ it("prefers the HTML flavour, which is the one a relation's target survives in", () => {+ const attributes = readAttributes(clipboard({+ "text/html": '~parent=<a class="reference-link" href="#root/abc123">Some note</a>',+ // What a copy out of the editor leaves as plain text: the title, which names no note.+ "text/plain": "~parent=Some note"+ }));++ expect(attributes).toMatchObject([ { type: "relation", name: "parent", value: "abc123" } ]);+ });++ it("falls back to the plain text where there is no HTML, and reads an empty clipboard as nothing", () => {+ expect(readAttributes(clipboard({ "text/plain": "#author=Elian" })))+ .toMatchObject([ { type: "label", name: "author", value: "Elian" } ]);++ expect(readAttributes(clipboard({ "text/plain": " " }))).toEqual([]);+ expect(readAttributes(null)).toEqual([]);+ });++ it("throws what the parser makes of text that is not attributes", () => {+ expect(() => readAttributes(clipboard({ "text/plain": "just some prose" })))+ .toThrow(/Invalid attribute/);+ });+});++describe("writeAttributes", () => {+ it("puts both flavours on the clipboard", () => {+ const setData = vi.fn();+ writeAttributes({ setData } as unknown as DataTransfer, [ relation("parent", "abc123") ]);++ expect(setData).toHaveBeenCalledWith("text/plain", "~parent=#root/abc123");+ expect(setData).toHaveBeenCalledWith("text/html", expect.stringContaining("reference-link"));+ });++ it("holds on to what it wrote, which is what a menu pastes", () => {+ const copied = [ label("author", "Elian") ];+ 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.+ expect(getHeldAttributes()).not.toBe(copied);++ writeAttributes(null, []);+ expect(getHeldAttributes()).toEqual([]);+ });+});++describe("mergePastedAttributes", () => {+ const single = () => false;++ it("adds what the note does not carry, and never carries an id across", () => {+ const { attributes, added, replaced } = mergePastedAttributes(+ [ label("existing", "kept") ],+ [ { ...label("author", "Elian"), attributeId: "fromElsewhere", noteId: "otherNote" } ],+ single+ );++ expect(attributes).toEqual([+ label("existing", "kept"),+ { type: "label", name: "author", value: "Elian", isInheritable: false }+ ]);+ expect(attributes[1].attributeId).toBeUndefined();+ expect(attributes[1].noteId).toBeUndefined();+ expect([ added, replaced ]).toEqual([ 1, 0 ]);+ });++ it("replaces a single-valued name in place, the attribute staying the one it was", () => {+ const existing: Attribute = { ...label("author", "Someone"), attributeId: "own" };+ const { attributes, added, replaced } = mergePastedAttributes(+ [ existing ],+ [ { ...label("author", "Elian"), isInheritable: true } ],+ single+ );++ expect(attributes).toHaveLength(1);+ // Kept: this is the same attribute given another value, not a new one put beside it.+ expect(attributes[0]).toMatchObject({ attributeId: "own", value: "Elian", isInheritable: true });+ expect([ added, replaced ]).toEqual([ 0, 1 ]);+ });++ it("puts another entry into a name that holds a set, but not one it already holds", () => {+ const multi = (attribute: Attribute) => attribute.name === "tag";+ const { attributes, added } = mergePastedAttributes(+ [ label("tag", "book") ],+ [ label("tag", "read"), label("tag", "book") ],+ multi+ );++ expect(attributes.map((attribute) => attribute.value)).toEqual([ "book", "read" ]);+ expect(added).toBe(1);+ });++ it("tells a label from a relation of the same name", () => {+ const { attributes } = mergePastedAttributes([ label("owner", "me") ], [ relation("owner", "abc123") ], single);++ expect(attributes).toHaveLength(2);+ });++ it("leaves the list it was given alone", () => {+ const existing = [ label("author", "Someone") ];+ mergePastedAttributes(existing, [ label("author", "Elian"), label("other", "x") ], single);++ expect(existing).toEqual([ label("author", "Someone") ]);+ });+});++describe("getPreprocessedData", () => {+ it("reduces a reference link back to the note path it stands for, and resolves the entities around it", () => {+ expect(getPreprocessedData(+ "<p>#author=Elian ~parent=<a class=\"reference-link\" href=\"#root/abc123\">Some note</a> </p>"+ )).toBe("#author=Elian ~parent=#root/abc123 ");++ // A link to anywhere else is not a note path, so it is left to the text extraction below it.+ expect(getPreprocessedData("<a href=\"https://example.com\">Example</a>")).toBe("Example");+ expect(getPreprocessedData("#a&b")).toBe("#a&b");+ });+});++function label(name: string, value?: string): Attribute {+ return { type: "label", name, value: value ?? "", isInheritable: false };+}++function relation(name: string, value: string): Attribute {+ return { type: "relation", name, value, isInheritable: false };+}++/** A clipboard holding the given flavours and nothing else, as an event hands one over. */+function clipboard(flavours: Record<string, string>) {+ return { getData: (type: string) => flavours[type] ?? "" } as unknown as DataTransfer;+}diff --git a/apps/client/src/services/attribute_clipboard.ts b/apps/client/src/services/attribute_clipboard.tsnew file mode 100644index 0000000000..4df24bab39--- /dev/null+++ b/apps/client/src/services/attribute_clipboard.ts@@ -0,0 +1,239 @@+import attribute_parser, { Attribute } from "./attribute_parser.js";+import { formatValue } from "./attribute_renderer.js";+import froca from "./froca.js";++/**+ * Attributes travel through the clipboard as the text the attributes editor spells them out in —+ * `#author=Elian ~parent=#root/abc123 #tag(inheritable)`. That is Trilium's one written form for them+ * and it loses nothing: the kind, the name, the value, whether the attribute is inheritable, and the+ * note a relation points at (as the note path the editor holds behind its links, not as the title the+ * rows show). So nothing here is a format of its own — what is copied out of a row pastes into the+ * attributes editor, into a note, or into anything else that takes text, and what is copied from any+ * of those pastes back into the rows.+ *+ * Two flavours are written: that text, and the HTML the editor holds it as — the same thing with the+ * relations as reference links, so a paste into a note keeps them clickable and reading a paste back+ * keeps the target's title readable. The HTML is preferred when reading, being the richer of the two;+ * {@link getPreprocessedData} takes it back down to the text the parser reads.+ */++/**+ * What was last copied, kept here as well as on the system clipboard — which is what a menu pastes+ * from, the note tree's own clipboard working the same way (see clipboard.ts): reading the system+ * clipboard outside of a paste key press is withheld outside a secure context and asks a permission+ * besides, where what Trilium copied itself is simply still here.+ *+ * It follows from that that this and the system clipboard can drift apart — something else copied in+ * another window leaves this untouched — which is the note tree's behaviour too: a menu pastes what+ * Trilium last copied, and the paste key pastes what the system clipboard holds.+ */+let held: Attribute[] = [];++/** What a menu pastes: the attributes last copied out of a panel, or none if none were. */+export function getHeldAttributes(): Attribute[] {+ return held;+}++/** Reads whichever flavour the clipboard offers. Throws what the parser throws over text that is not+ * attributes, which the caller is the one to put to the user. */+export function readAttributes(data: DataTransfer | null): Attribute[] {+ // Preferred over the plain text because it is the flavour a relation survives in: the editor+ // writes its target as a link, whose text is the note's title and whose href is the path.+ const html = data?.getData("text/html");+ const source = html ? getPreprocessedData(html) : data?.getData("text/plain");++ if (!source?.trim()) {+ return [];+ }++ return attribute_parser.lexAndParse(source);+}++/** Writes both flavours of the attributes onto a clipboard event's data, and holds on to them. */+export function writeAttributes(data: DataTransfer | null, attributes: Attribute[]) {+ held = [ ...attributes ];++ if (!data) {+ return;+ }++ data.setData("text/plain", serializeAttributes(attributes));+ data.setData("text/html", serializeAttributesAsHtml(attributes));+}++/**+ * Puts the attributes on the system clipboard outside of a copy key press — from a menu, that is,+ * where there is no event to write onto. Only the text flavour goes across: the richer one is a+ * convenience for pasting into a note (the relations staying clickable) and the text loses nothing.+ *+ * The clipboard API where it is to be had, and the old command where it is not: it is withheld+ * outside a secure context, and Trilium is served over plain HTTP as readily as over TLS. The+ * command needs something selected to copy, hence the field held off-screen for the moment it takes.+ */+export async function copyAttributesToClipboard(attributes: Attribute[]) {+ held = [ ...attributes ];+ const text = serializeAttributes(attributes);++ try {+ if (navigator.clipboard?.writeText) {+ await navigator.clipboard.writeText(text);+ return;+ }+ } catch {+ // Withheld after all — a permission refused, or a window that had lost the focus. Below.+ }++ const field = document.createElement("textarea");+ field.value = text;+ // Off-screen rather than hidden: what is not rendered cannot hold a selection to be copied.+ field.style.position = "fixed";+ field.style.opacity = "0";+ document.body.append(field);++ const previouslyFocused = document.activeElement;+ field.select();+ document.execCommand("copy");+ field.remove();++ // The panel had the focus and needs it back: it is what the paste key reaches the panel through.+ if (previouslyFocused instanceof HTMLElement) {+ previouslyFocused.focus({ preventScroll: true });+ }+}++/**+ * The attributes as the one line of text the editor spells them out in. A relation is written as the+ * path of the note it points at rather than that note's title: the title is what a link shows, and a+ * paste is read by the parser, which resolves a path and could only guess at a title.+ *+ * A relation with no target yet is left out — there is nothing to write down for it, and the parser+ * would refuse the line over it.+ */+export function serializeAttributes(attributes: Attribute[]): string {+ return attributes+ .map(serializeAttribute)+ .filter((text) => text !== null)+ .join(" ");+}++/**+ * The same, as the HTML the attributes editor holds: the relations as the reference links it renders+ * them into, so a paste into a note lands as a link to the target and a paste back reads the path out+ * of it again. Built as DOM rather than as a string, so a title with a `<` in it stays a title.+ */+export function serializeAttributesAsHtml(attributes: Attribute[]): string {+ const $container = $("<span>");++ for (const attribute of attributes) {+ const text = serializeAttribute(attribute);+ if (text === null) {+ continue;+ }++ if ($container.contents().length > 0) {+ $container.append(document.createTextNode(" "));+ }++ if (attribute.type === "relation" && attribute.value) {+ $container.append(document.createTextNode(`~${attribute.name}${inheritableSuffix(attribute)}=`));+ $container.append($("<a>", {+ href: `#root/${attribute.value}`,+ class: "reference-link"+ // The title where the note is one the client already holds, and the id where it is+ // not: the href is what a paste reads, so the text is free to be the readable half.+ }).text(froca.getNoteFromCache(attribute.value)?.title ?? attribute.value));+ } else {+ $container.append(document.createTextNode(text));+ }+ }++ return $container.html();+}++/** One attribute written out, or `null` where there is nothing to write (a relation with no target). */+function serializeAttribute(attribute: Attribute): string | null {+ const head = `${attribute.type === "relation" ? "~" : "#"}${attribute.name}${inheritableSuffix(attribute)}`;++ if (attribute.type === "relation") {+ return attribute.value ? `${head}=#root/${attribute.value}` : null;+ }++ // A label with no value is its name alone: `#archived=` would not parse, and `#archived` is what+ // a bare label means anyway.+ return attribute.value ? `${head}=${formatValue(attribute.value)}` : head;+}++/** Written between the name and the value, which is where the parser looks for it. */+function inheritableSuffix(attribute: Attribute) {+ return attribute.isInheritable ? "(inheritable)" : "";+}++export interface PasteResult {+ /** The note's owned attributes with the pasted ones folded in. */+ attributes: Attribute[];+ /** How many joined the list, and how many were an existing attribute given another value. */+ added: number;+ replaced: number;+}++/**+ * The pasted attributes folded into the ones the note already owns. What happens where a name is+ * 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.+ *+ * 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+ * always a note being given an attribute rather than one being moved across from somewhere else.+ */+export function mergePastedAttributes(+ existing: Attribute[],+ pasted: Attribute[],+ isMultiValued: (attribute: Attribute) => boolean+): PasteResult {+ const attributes = [ ...existing ];+ let added = 0;+ let replaced = 0;++ for (const incoming of pasted) {+ const candidate: Attribute = {+ type: incoming.type,+ name: incoming.name,+ value: incoming.value ?? "",+ isInheritable: incoming.isInheritable ?? false+ };+ const matches = (attribute: Attribute) => attribute.type === candidate.type && attribute.name === candidate.name;++ if (isMultiValued(candidate)) {+ if (!attributes.some((attribute) => matches(attribute) && (attribute.value ?? "") === candidate.value)) {+ attributes.push(candidate);+ added++;+ }+ continue;+ }++ const index = attributes.findIndex(matches);+ if (index >= 0) {+ attributes[index] = {+ ...attributes[index],+ value: candidate.value,+ isInheritable: candidate.isInheritable+ };+ replaced++;+ } else {+ attributes.push(candidate);+ added++;+ }+ }++ return { attributes, added, replaced };+}++/** The attributes as plain text: reference links back down to their note path, entities resolved. */+export function getPreprocessedData(currentValue: string) {+ const str = currentValue+ .replace(/<a[^>]+href="(#[A-Za-z0-9_/]*)"[^>]*>[^<]*<\/a>/g, "$1")+ .replace(/ /g, " "); // otherwise .text() below outputs non-breaking space in unicode++ return $("<div>").html(str).text();+}diff --git a/apps/client/src/services/attribute_renderer.ts b/apps/client/src/services/attribute_renderer.tsindex c93620b3b2..8a848de737 100644--- a/apps/client/src/services/attribute_renderer.ts+++ b/apps/client/src/services/attribute_renderer.ts@@ -36,7 +36,8 @@ async function renderAttribute(attribute: FAttribute, renderIsInheritable: boolereturn $attr;}-function formatValue(val: string) {+/** A value as the lexer reads it back: bare where it can be, quoted with whichever quote it spares. */+export function formatValue(val: string) {if (/^[\p{L}\p{N}\-_,.]+$/u.test(val)) {return val;} else if (!val.includes('"')) {diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex f444cd26eb..a0f3e87f55 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -827,7 +827,20 @@"system_hint": "System: this name has a built-in meaning","add_attribute": "Add attribute","creation_kind_label": "Label: press here, or type ~, to make it a relation",- "creation_kind_relation": "Relation: press here, or type #, to make it a label"+ "creation_kind_relation": "Relation: press here, or type #, to make it a label",+ "copy_one": "Copy attribute",+ "copy_other": "Copy {{count}} attributes",+ "paste_one": "Paste attribute",+ "paste_other": "Paste {{count}} attributes",+ "copied_one": "{{count}} attribute copied",+ "copied_other": "{{count}} attributes copied",+ "pasted_one": "{{count}} attribute pasted",+ "pasted_other": "{{count}} attributes pasted",+ "nothing_to_paste": "The clipboard holds no attributes.",+ "paste_failed": "The clipboard could not be read as attributes: {{- message}}",+ "delete_selection_one": "Delete attribute",+ "delete_selection_other": "Delete {{count}} attributes",+ "delete_selection_confirm": "Delete the {{count}} selected attributes?"},"attribute_names": {"system": "System",diff --git a/apps/client/src/widgets/ribbon/components/AttributeEditor.spec.tsx b/apps/client/src/widgets/ribbon/components/AttributeEditor.spec.tsxindex 87064d86a1..17fd6bb536 100644--- a/apps/client/src/widgets/ribbon/components/AttributeEditor.spec.tsx+++ b/apps/client/src/widgets/ribbon/components/AttributeEditor.spec.tsx@@ -2,7 +2,7 @@ import type { ModelPosition } from "@triliumnext/ckeditor5";import { describe, expect, it, vi } from "vitest";import server from "../../../services/server";-import { fetchAttributeNames, getClickIndex, getPreprocessedData, renderAttributeName } from "./AttributeEditor";+import { fetchAttributeNames, getClickIndex, renderAttributeName } from "./AttributeEditor";describe("fetchAttributeNames", () => {it("prefixes each name with the marker that inserts it, and asks for the names by an escaped query", async () => {@@ -38,18 +38,6 @@ describe("renderAttributeName", () => {});});-describe("getPreprocessedData", () => {- it("reduces a reference link back to the note path it stands for, and resolves the entities around it", () => {- expect(getPreprocessedData(- "<p>#author=Elian ~parent=<a class=\"reference-link\" href=\"#root/abc123\">Some note</a> </p>"- )).toBe("#author=Elian ~parent=#root/abc123 ");-- // A link to anywhere else is not a note path, so it is left to the text extraction below it.- expect(getPreprocessedData("<a href=\"https://example.com\">Example</a>")).toBe("Example");- expect(getPreprocessedData("#a&b")).toBe("#a&b");- });-});-describe("getClickIndex", () => {it("measures every sibling before the pressed one as the text it stands for", () => {const reference = { name: "reference", getAttribute: () => "#root/abc123" };diff --git a/apps/client/src/widgets/ribbon/components/AttributeEditor.tsx b/apps/client/src/widgets/ribbon/components/AttributeEditor.tsxindex 8818e852d9..e953ca849f 100644--- a/apps/client/src/widgets/ribbon/components/AttributeEditor.tsx+++ b/apps/client/src/widgets/ribbon/components/AttributeEditor.tsx@@ -11,6 +11,7 @@ import type { CommandData, FilteredCommandNames } from "../../../components/app_import FAttribute from "../../../entities/fattribute";import FNote from "../../../entities/fnote";import contextMenu from "../../../menus/context_menu";+import { getPreprocessedData } from "../../../services/attribute_clipboard";import attribute_parser, { Attribute } from "../../../services/attribute_parser";import attribute_renderer from "../../../services/attribute_renderer";import attributes, { isBuiltinAttribute } from "../../../services/attributes";@@ -495,15 +496,6 @@ export function renderAttributeName(type: "label" | "relation", name: string) {return button;}-/** The attributes as plain text: reference links back down to their note path, entities resolved. */-export function getPreprocessedData(currentValue: string) {- const str = currentValue- .replace(/<a[^>]+href="(#[A-Za-z0-9_/]*)"[^>]*>[^<]*<\/a>/g, "$1")- .replace(/ /g, " "); // otherwise .text() below outputs non-breaking space in unicode-- return $("<div>").html(str).text();-}-/*** Where the press landed in {@link getPreprocessedData}'s text, which is what the parsed attributes* carry their offsets in: the editor's own offset counts a reference link as one node, so everydiff --git a/apps/client/src/widgets/sidebar/AttributeList.css b/apps/client/src/widgets/sidebar/AttributeList.cssindex 22fd266f48..9ea42da046 100644--- a/apps/client/src/widgets/sidebar/AttributeList.css+++ b/apps/client/src/widgets/sidebar/AttributeList.css@@ -3,6 +3,14 @@flex-direction: column;}+/* The card takes the focus when it is pressed, which is how the copy and paste keys reach the panel+ (see AttributeList.tsx) — a way in rather than a place to arrive at, so it is not drawn as focused:+ the rows picked out are what says where those keys will land. */+.attribute-list-panel:focus,+.attribute-list-panel:focus-visible {+ outline: none;+}+.attribute-list-panel ul.attribute-rows {margin: 0;padding-inline-start: 0;@@ -30,6 +38,25 @@background-color: var(--hover-item-background-color);}+/* Picked out to be copied. Held apart from the row merely being pointed at or shown in the popup —+ which come and go with the pointer — by the standing mark of a filled leading edge, and by a+ ground that outweighs the hover film so a picked row pointed at still reads as picked. */+.attribute-list-panel .attribute-row.selected,+.attribute-list-panel .attribute-row.selected:hover {+ background-color: var(--active-item-background-color);+}++.attribute-list-panel .attribute-row.selected::before {+ content: "";+ position: absolute;+ inset-block: 2px;+ inset-inline-start: 0;+ width: 2px;+ border-radius: 1px;+ background-color: var(--main-text-color);+ opacity: 0.5;+}+/* While its value is edited (or the attribute created), the row lets the editor standing over it(see AttributeEditorOverlay.css) spill past the one line the row keeps to, and comes forward sothe editor is drawn over the rows below rather than under them. */diff --git a/apps/client/src/widgets/sidebar/AttributeList.spec.tsx b/apps/client/src/widgets/sidebar/AttributeList.spec.tsxindex 5b256aa9c6..b458a64d07 100644--- a/apps/client/src/widgets/sidebar/AttributeList.spec.tsx+++ b/apps/client/src/widgets/sidebar/AttributeList.spec.tsx@@ -34,9 +34,13 @@ vi.mock("../../menus/context_menu", () => ({ default: { show: showContextMenu }/** What the add button asks the context menu to show: a kind per entry, and a rule between groups. */interface AddMenuCall {- items: { kind?: string; handler?: () => void }[];+ items: { kind?: string; uiIcon?: string; handler?: () => void }[];}+// Copying and pasting report what they did; the toasts themselves belong to no widget.+const toast = vi.hoisted(() => ({ showMessage: vi.fn(), showError: vi.fn() }));+vi.mock("../../services/toast", () => ({ default: toast }));+// A relation's target is picked in an Algolia autocomplete bound to jQuery, which is not loaded here:// a bare box stands in, reporting whatever is typed into it as the noteId picked.vi.mock("../react/NoteAutocomplete", async () => {@@ -55,6 +59,7 @@ vi.mock("../react/NoteAutocomplete", async () => {import appContext from "../../components/app_context";import type Component from "../../components/component";import FAttribute, { FAttributeRow } from "../../entities/fattribute";+import { writeAttributes } from "../../services/attribute_clipboard";import type { Attribute } from "../../services/attribute_parser";import froca from "../../services/froca";import type LoadResults from "../../services/load_results";@@ -824,6 +829,211 @@ describe("AttributeList", () => {/** What the panel subscribed to, when rendered under a parent component that can tell it. */let eventHandlers: Map<string, (data: unknown) => void>;+ it("picks rows out with the modifiers, across the cards, and lets a plain press take over again", () => {+ renderPanel(noteWithAttributes());++ // Control adds and removes the one row, as a list of files is picked through.+ pick(0, { ctrlKey: true });+ expect(selectedNames()).toEqual([ "author" ]);+ pick(0, { ctrlKey: true });+ expect(selectedNames()).toEqual([]);+ // The rows are not what the press was about, so no form is opened over them.+ expect(document.querySelector(".attr-detail")).toBeNull();++ // Shift draws a range from the row last picked out, over the cards' boundaries: the owned+ // card's three rows and the first of the inherited card's.+ pick(0, { ctrlKey: true });+ pick(3, { shiftKey: true });+ expect(selectedNames()).toEqual([ "author", "cssClass", "template", "inheritedLabel" ]);++ // A press with nothing held down is about the one attribute it landed on, and takes over.+ act(() => rows()[1].click());+ expect(selectedNames()).toEqual([]);+ expect(document.querySelector(".attr-detail")).not.toBeNull();+ });++ it("copies the picked rows as the text the attributes editor spells them out in", () => {+ renderPanel(noteWithAttributes());++ // Nothing picked out: the press is about whatever text is selected, and is left alone.+ const untouched = copyFrom(firstPanel());+ expect(untouched.defaultPrevented).toBe(false);+ expect(untouched.written).toEqual({});++ pick(0, { ctrlKey: true });+ pick(2, { ctrlKey: true });++ const copied = copyFrom(firstPanel());+ expect(copied.defaultPrevented).toBe(true);+ // Both flavours, the relation as the path in the one and as a reference link in the other.+ expect(copied.written["text/plain"]).toBe("#author=Elian ~template=#root/tpl");+ expect(copied.written["text/html"]).toContain('href="#root/tpl"');+ expect(toast.showMessage).toHaveBeenCalledOnce();+ });++ it("pastes attributes onto the note, replacing a name it already carries and adding the rest", async () => {+ // A note of its own: the effective-attribute cache is shared between the tests, so a note+ // named as another test's would arrive carrying that one's inherited attributes.+ const note = buildNote({ id: "pastee", title: "Pastee", "#author": "Someone" });+ const existingId = note.getOwnedAttributes()[0].attributeId;+ renderPanel(note);++ await act(async () => pasteInto(firstPanel(), { "text/plain": "#author=Elian #tag=new ~parent=#root/tpl" }));++ expect(put).toHaveBeenCalledOnce();+ const [ url, saved ] = put.mock.calls[0] as [ string, Attribute[] ];+ expect(url).toBe("notes/pastee/attributes");+ expect(saved).toMatchObject([+ // Replaced in place, the attribute staying the one it was rather than a second `author`.+ { type: "label", name: "author", value: "Elian", attributeId: existingId },+ { type: "label", name: "tag", value: "new" },+ { type: "relation", name: "parent", value: "tpl" }+ ]);+ // Nothing of the note the attributes were copied from comes across with them.+ expect(saved[1].attributeId).toBeUndefined();+ expect(namesIn(container)).toEqual([ "author", "tag", "parent" ]);+ });++ it("says what it made of a clipboard that is not attributes, and saves nothing over it", async () => {+ renderPanel(buildNote({ id: "subject", title: "Subject", "#author": "Someone" }));++ await act(async () => pasteInto(firstPanel(), { "text/plain": "just some prose" }));+ expect(toast.showError).toHaveBeenCalledOnce();+ expect(put).not.toHaveBeenCalled();++ // An empty clipboard is not an error, only nothing to do.+ await act(async () => pasteInto(firstPanel(), { "text/plain": "" }));+ expect(toast.showError).toHaveBeenCalledOnce();+ expect(put).not.toHaveBeenCalled();+ });++ it("offers the picked rows to a right press, narrowing down to the one row pressed outside them", async () => {+ renderPanel(noteWithAttributes());+ pick(0, { ctrlKey: true });+ pick(1, { ctrlKey: true });++ // A right press on a row among those picked out is about all of them.+ rightPress(1);+ expect(selectedNames()).toEqual([ "author", "cssClass" ]);++ // Deleting the lot is confirmed once, as a single row's deletion is.+ confirm.mockResolvedValueOnce(true);+ await act(async () => menuItem("bx bx-trash")?.handler?.());+ expect(confirm).toHaveBeenCalledOnce();+ const [ , saved ] = put.mock.calls[0] as [ string, Attribute[] ];+ expect(saved.map((attribute) => attribute.name)).toEqual([ "template", "label:priority" ]);++ // A right press on a row outside them narrows down to that row alone.+ rightPress(0);+ expect(selectedNames()).toEqual([ "template" ]);+ // An inherited row is the source note's to delete, so only copying is offered over it.+ rightPress(1);+ expect(menuItem("bx bx-trash")).toBeUndefined();+ expect(menuItem("bx bx-copy")).toBeDefined();+ });++ it("pastes from a menu what Trilium last copied, beside the rows as well as on them", async () => {+ renderPanel(buildNote({ id: "source", title: "Source", "#author": "Elian", "#tag": "book" }));+ pick(0, { ctrlKey: true });+ pick(1, { ctrlKey: true });+ // Copied from the menu, which is the way in that holds on to them for a menu to paste.+ rightPress(0);+ expect(menuItem("bx bx-copy")).toBeDefined();+ await act(async () => menuItem("bx bx-copy")?.handler?.());++ // A note with no attributes at all has no row to press: the card itself offers the paste.+ renderPanel(buildNote({ id: "blank", title: "Blank" }));+ expect(container.querySelectorAll(".attribute-row")).toHaveLength(0);+ act(() => {+ firstPanel().dispatchEvent(new MouseEvent("contextmenu", { bubbles: true, cancelable: true }));+ });++ await act(async () => menuItem("bx bx-paste")?.handler?.());+ const [ url, saved ] = put.mock.calls[0] as [ string, Attribute[] ];+ expect(url).toBe("notes/blank/attributes");+ expect(saved).toMatchObject([+ { type: "label", name: "author", value: "Elian" },+ { type: "label", name: "tag", value: "book" }+ ]);+ expect(namesIn(container)).toEqual([ "author", "tag" ]);+ });++ it("offers no menu of its own beside the rows while there is nothing to paste", () => {+ // Whatever an earlier test copied is still held, the store being the module's own — as the+ // note tree's clipboard is. Copying nothing is how a session that has copied nothing looks.+ writeAttributes(null, []);+ renderPanel(buildNote({ id: "blank", title: "Blank" }));++ const event = new MouseEvent("contextmenu", { bubbles: true, cancelable: true });+ act(() => {+ firstPanel().dispatchEvent(event);+ });++ // Left to the browser's own menu, rather than shown an empty one of ours.+ expect(showContextMenu).not.toHaveBeenCalled();+ expect(event.defaultPrevented).toBe(false);+ });++ function rows() {+ return [ ...container.querySelectorAll<HTMLElement>(".attribute-row") ];+ }++ function selectedNames() {+ return [ ...container.querySelectorAll(".attribute-row.selected .attribute-name") ]+ .map((name) => name.textContent);+ }++ function firstPanel() {+ const panel = container.querySelector<HTMLElement>(".attribute-list-panel");+ expect(panel).not.toBeNull();+ return panel as HTMLElement;+ }++ /** A press on a row with the modifiers held down that pick it out rather than open it. */+ function pick(index: number, modifiers: { ctrlKey?: boolean; shiftKey?: boolean }) {+ act(() => {+ rows()[index].dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true, ...modifiers }));+ });+ }++ function rightPress(index: number) {+ act(() => {+ rows()[index].dispatchEvent(new MouseEvent("contextmenu", { bubbles: true, cancelable: true }));+ });+ }++ /** The copy key over the panel, reporting what it wrote onto the clipboard it was handed. */+ function copyFrom(panel: HTMLElement) {+ const written: Record<string, string> = {};+ const event = clipboardEvent("copy", { setData: (type: string, data: string) => { written[type] = data; } });+ panel.dispatchEvent(event);++ return { written, defaultPrevented: event.defaultPrevented };+ }++ /** The paste key over the panel, the clipboard holding the given flavours. */+ function pasteInto(panel: HTMLElement, flavours: Record<string, string>) {+ panel.dispatchEvent(clipboardEvent("paste", { getData: (type: string) => flavours[type] ?? "" }));+ }++ /**+ * A clipboard event carrying the given stand-in for the system clipboard: the constructor takes+ * no data of its own, so it is hung on the event as the browser hangs the real one.+ */+ function clipboardEvent(type: string, clipboardData: Partial<DataTransfer>) {+ const event = new Event(type, { bubbles: true, cancelable: true });+ Object.assign(event, { clipboardData });++ return event;+ }++ /** The entry of the menu last shown carrying the given icon, which is what names it here: the+ * titles are translated, and translations stay unloaded in these tests. */+ function menuItem(icon: string) {+ const call = showContextMenu.mock.lastCall?.[0];+ return call?.items.find((item) => item.uiIcon === icon);+ }+function renderPanel(note: FNote, withEvents = false) {shownNote.current = note;if (!withEvents) {diff --git a/apps/client/src/widgets/sidebar/AttributeList.tsx b/apps/client/src/widgets/sidebar/AttributeList.tsxindex 73285fb4f1..f3058a22d8 100644--- a/apps/client/src/widgets/sidebar/AttributeList.tsx+++ b/apps/client/src/widgets/sidebar/AttributeList.tsx@@ -9,12 +9,14 @@ import { useContext, useEffect, useRef, useState } from "preact/hooks";import FAttribute from "../../entities/fattribute";import FNote from "../../entities/fnote";import contextMenu, { MenuItem } from "../../menus/context_menu";+import { copyAttributesToClipboard, getHeldAttributes, mergePastedAttributes, readAttributes, writeAttributes } from "../../services/attribute_clipboard";import type { Attribute } from "../../services/attribute_parser";import attributes, { isBuiltinAttribute } from "../../services/attributes";import dialog from "../../services/dialog";import { t } from "../../services/i18n";import server from "../../services/server";-import { isMobile } from "../../services/utils";+import toast from "../../services/toast";+import { getErrorMessage, isMobile } from "../../services/utils";import { AttributeDetail, AttributeDetailOpts, AttributeForm, AttrType, DEFINITION_TYPES, getAttrType, RELATION_DEFINITION_TYPE } from "../attribute_widgets/attribute_detail";import { ColorChip, renderLabelValue } from "../attribute_widgets/label_value_display";import ActionButton from "../react/ActionButton";@@ -57,6 +59,11 @@ export default function AttributeList() {// The draft a label or relation is created through in a row of its own, already among the owned// rows; un-creating it is taking it back out of them.const [ creating, setCreating ] = useState<Attribute | null>(null);+ // The rows picked out to be copied, by attributeId: a selection outlives the row objects, which a+ // reload rebuilds, and an attribute not yet saved has nothing to be copied by anyway.+ const [ selection, setSelection ] = useState<ReadonlySet<string>>(EMPTY_SELECTION);+ // Where a range drawn with shift is measured from: the row last picked out on its own.+ const selectionAnchor = useRef<string | null>(null);const componentId = parentComponent?.componentId;// The owned rows double as the detail popup's working copy: it edits the very objects it is handed,@@ -94,10 +101,13 @@ export default function AttributeList() {}// Every editor works on one attribute of the note being left, so all of them close with the note.+ // The selection goes with them: it picks out rows of the note being left, and the clipboard holds+ // whatever was copied out of it already.useEffect(() => {setDetail(null);setValueEdit(null);setCreating(null);+ clearSelection();const draft = draftToFlush.current;draftToFlush.current = null;@@ -126,6 +136,10 @@ export default function AttributeList() {setCreating(null);}+ // A row deleted elsewhere takes its place in the selection with it, so what is copied is+ // always what is still shown.+ pruneSelection();+rerender();}});@@ -144,6 +158,10 @@ export default function AttributeList() {}function openDetail(attribute: Attribute, isOwned: boolean, anchor: HTMLElement | null, e: MouseEvent) {+ // A press with no modifier on it is about the one attribute it landed on, so it takes the+ // selection over rather than leaving it standing behind the form to be copied by surprise.+ clearSelection();+setDetail({allAttributes: isOwned ? owned.current : undefined,attribute,@@ -297,6 +315,266 @@ export default function AttributeList() {const sections = splitIntoSections(owned.current, inherited.current);const internalRows = internal.current.map((attribute) => toEntry(attribute, true));++ //#region Selection and the clipboard+ /**+ * Every row that can be picked out, in the order the panel draws them — the three cards read as+ * one list, so a range drawn with shift runs from any row to any other. The internal card is left+ * out: its rows are Trilium's own bookkeeping, rewritten whenever the note's content is saved,+ * which there is nothing to be gained by carrying elsewhere. A row is picked out by its+ * attributeId, so a draft still being created is not among them — it is not an attribute yet.+ */+ const selectableRows = [ ...sections.owned, ...sections.inherited, ...sections.definitions ]+ .filter((entry) => entry.attribute.attributeId);+ const selectableIds = selectableRows.flatMap((entry) => entry.attribute.attributeId ?? []);++ /** The picked-out rows in the order they are drawn, whichever cards they were picked out from. */+ function selectedAttributes() {+ return selectableRows+ .filter((entry) => entry.attribute.attributeId && selection.has(entry.attribute.attributeId))+ .map((entry) => entry.attribute);+ }++ function clearSelection() {+ selectionAnchor.current = null;+ setSelection(EMPTY_SELECTION);+ }++ /** Drops from the selection whatever the note no longer holds, so what is copied is what is shown. */+ function pruneSelection() {+ setSelection((current) => {+ if (current.size === 0) {+ return current;+ }++ const shown = new Set([ ...owned.current, ...inherited.current ].flatMap((attribute) => attribute.attributeId ?? []));+ const next = new Set([ ...current ].filter((attributeId) => shown.has(attributeId)));++ return next.size === current.size ? current : next;+ });+ }++ /**+ * Picks a row out or takes it back out: control adds and removes the one row, as a list of files+ * is picked through, and shift draws a range from the row last picked out on its own, replacing+ * whatever was picked out before it.+ */+ function selectRow(attributeId: string, e: MouseEvent) {+ // Whatever is being edited is wrapped up: picking rows out is about the rows, not the value.+ commit();+ commitValueEdit();+ commitCreation();++ if (e.shiftKey && selectionAnchor.current) {+ const from = selectableIds.indexOf(selectionAnchor.current);+ const to = selectableIds.indexOf(attributeId);++ if (from >= 0 && to >= 0) {+ setSelection(new Set(selectableIds.slice(Math.min(from, to), Math.max(from, to) + 1)));+ return;+ }+ }++ const next = new Set(selection);+ if (next.has(attributeId)) {+ next.delete(attributeId);+ } else {+ next.add(attributeId);+ }++ selectionAnchor.current = attributeId;+ setSelection(next);+ }++ /**+ * The copy key, which the panel receives by holding the focus (see {@link clipboardProps}). With+ * no rows picked out it is left alone: the press is then about whatever text is selected in the+ * panel, which is the browser's to copy.+ */+ function copySelection(e: ClipboardEvent) {+ const picked = selectedAttributes();+ if (picked.length === 0) {+ return;+ }++ e.preventDefault();+ writeAttributes(e.clipboardData, picked);+ toast.showMessage(t("attribute_list_panel.copied", { count: picked.length }));+ }++ /**+ * The paste key. What the clipboard holds is read as the text the attributes editor spells+ * attributes out in — which is what this panel copies, and what that editor holds — so a paste+ * from either lands here whole, as does one written out by hand.+ */+ async function pasteAttributes(e: ClipboardEvent) {+ if (!note) {+ return;+ }+ e.preventDefault();++ let pasted: Attribute[];+ try {+ pasted = readAttributes(e.clipboardData);+ } catch (error: unknown) {+ // What was on the clipboard was not attributes; the parser says what it made of it.+ toast.showError(t("attribute_list_panel.paste_failed", { message: getErrorMessage(error) }));+ return;+ }++ if (pasted.length === 0) {+ toast.showMessage(t("attribute_list_panel.nothing_to_paste"));+ return;+ }++ await applyPaste(pasted);+ }++ /** The attributes folded into the note's own and saved, wherever the paste came from. */+ async function applyPaste(pasted: Attribute[]) {+ if (!note) {+ return;+ }++ // The edit in flight is wrapped up first, so the paste folds into a settled list.+ commit();+ commitValueEdit();+ commitCreation();++ const { attributes, added, replaced } = mergePastedAttributes(+ owned.current,+ pasted,+ (attribute) => isMultiValued(note, attribute)+ );++ owned.current = attributes;+ rerender();+ await save();++ toast.showMessage(t("attribute_list_panel.pasted", { count: added + replaced }));+ }++ /**+ * The menu a row is right-pressed for, over the rows picked out — which a press on a row that is+ * not among them narrows down to that row alone, as a file manager does. Copying is offered for+ * any row and deleting only where every picked row is the note's own: an inherited attribute is+ * the source note's to delete.+ */+ function showRowMenu(attribute: Attribute, e: MouseEvent) {+ e.preventDefault();+ e.stopPropagation();++ const attributeId = attribute.attributeId;+ let picked = selectedAttributes();++ if (!attributeId || !selection.has(attributeId)) {+ picked = [ attribute ];+ selectionAnchor.current = attributeId ?? null;+ setSelection(attributeId ? new Set([ attributeId ]) : EMPTY_SELECTION);+ }++ const items: MenuItem<never>[] = [+ {+ title: t("attribute_list_panel.copy", { count: picked.length }),+ uiIcon: "bx bx-copy",+ handler: () => void copyAttributesToClipboard(picked)+ },+ ...pasteMenuItems()+ ];++ if (picked.every((candidate) => owned.current.includes(candidate))) {+ items.push({ kind: "separator" });+ items.push({+ title: t("attribute_list_panel.delete_selection", { count: picked.length }),+ uiIcon: "bx bx-trash",+ handler: () => void deleteSelection(picked)+ });+ }++ void contextMenu.show({ x: e.pageX, y: e.pageY, items, selectMenuItemHandler: () => {} });+ }++ /**+ * The menu the card itself is right-pressed for, beside the rows — which is where a note with no+ * attributes at all is pasted onto, there being no row to press. Nothing is shown where there is+ * nothing to paste: the browser's own menu is the better answer then.+ */+ function showPanelMenu(e: MouseEvent) {+ const items = pasteMenuItems();+ if (items.length === 0) {+ return;+ }++ e.preventDefault();+ void contextMenu.show({ x: e.pageX, y: e.pageY, items, selectMenuItemHandler: () => {} });+ }++ /**+ * Pasting as a menu offers it, which is what Trilium last copied rather than what the system+ * clipboard holds — a menu cannot read that one (see the clipboard service), and the note tree's+ * own paste works from the same kind of store. The paste key is the way in to everything else,+ * the attributes editor's text included.+ */+ function pasteMenuItems(): MenuItem<never>[] {+ const heldAttributes = getHeldAttributes();+ if (heldAttributes.length === 0 || !note) {+ return [];+ }++ return [ {+ title: t("attribute_list_panel.paste", { count: heldAttributes.length }),+ uiIcon: "bx bx-paste",+ handler: () => void applyPaste(heldAttributes)+ } ];+ }++ /** Deletes the rows picked out, confirmed once for the lot as a single row's press is for the one. */+ async function deleteSelection(picked: Attribute[]) {+ if (picked.length === 1) {+ await deleteAttribute(picked[0]);+ return;+ }++ if (!await dialog.confirm(t("attribute_list_panel.delete_selection_confirm", { count: picked.length }))) {+ return;+ }++ owned.current = owned.current.filter((candidate) => !picked.includes(candidate));+ clearSelection();+ setDetail(null);+ rerender();++ await save();+ }++ /**+ * What every card carries so that the copy and paste keys reach the panel rather than the note+ * behind it: a clipboard event goes to whatever holds the focus, so a press anywhere in a card+ * takes it. Presses inside an open editor are left alone — taking the focus off a field would+ * commit the very edit the press is part of.+ */+ const clipboardProps = {+ tabIndex: -1,+ onCopy: copySelection,+ onPaste: (e: ClipboardEvent) => void pasteAttributes(e),+ onKeyDown: (e: KeyboardEvent) => {+ if (e.key === "Escape" && selection.size > 0) {+ e.stopPropagation();+ clearSelection();+ }+ },+ onMouseDownCapture: (e: MouseEvent) => {+ if (e.target instanceof Element && e.target.closest(".attribute-editor-overlay")) {+ return;+ }++ if (e.currentTarget instanceof HTMLElement) {+ e.currentTarget.focus({ preventScroll: true });+ }+ }+ };+ //#endregion+// Not built for an attribute the list no longer holds: a reload can rebuild the rows out from// under the editor within this very render, before the state has caught up (see above).const activeValueEdit = valueEdit && owned.current.includes(valueEdit.attribute) ? valueEdit : null;@@ -333,7 +611,10 @@ export default function AttributeList() {note,activeAttribute: detail?.attribute,valueEditor,+ selection,onOpen: openDetail,+ onSelect: selectRow,+ onShowMenu: showRowMenu,onEditValue: startValueEdit,onDelete: (attribute: Attribute) => void deleteAttribute(attribute)};@@ -389,7 +670,15 @@ export default function AttributeList() {{/* The values read from the trailing edge here and in the inherited card below,the two lists of plain attributes reading as one ledger. The definitions keepprose order: their "value" is a summary of settings, not a value. */}- <div class="attribute-list-panel align-values-end" ref={containerRef} onClick={commit}>+ {/* The card the note's own attributes are pasted onto, so it is the one that+ offers pasting beside its rows as well as on them. */}+ <div+ class="attribute-list-panel align-values-end"+ ref={containerRef}+ onClick={commit}+ onContextMenu={showPanelMenu}+ {...clipboardProps}+ >{sections.owned.length > 0 ? (<AttributeRowList rows={sections.owned} {...rowProps} />) : (@@ -408,7 +697,7 @@ export default function AttributeList() {id="attributes-inherited"title={t("attribute_list_panel.inherited", { count: sections.inherited.length })}>- <div class="attribute-list-panel align-values-end" onClick={commit}>+ <div class="attribute-list-panel align-values-end" onClick={commit} {...clipboardProps}><AttributeRowList rows={sections.inherited} {...rowProps} /></div></AttributeSection>@@ -426,7 +715,7 @@ export default function AttributeList() {/>)}>- <div class="attribute-list-panel" onClick={commit}>+ <div class="attribute-list-panel" onClick={commit} {...clipboardProps}><AttributeRowList rows={sections.definitions} {...rowProps} /></div></AttributeSection>@@ -522,14 +811,20 @@ interface AttributeRowListProps {activeAttribute?: Attribute;/** The in-place editor over one row's value, shown by that row in the value's place. */valueEditor?: { attribute: Attribute; element: ComponentChildren };+ /** The attributeIds of the rows picked out to be copied. */+ selection: ReadonlySet<string>;/*** The rows stand for attributes Trilium writes and keeps up to date itself, which leaves them* nothing to offer: nothing to edit, nothing to delete, no note to name as their source (they are- * always the current one's), and no split to draw between the note's own names and Trilium's —- * every one of them is Trilium's, which is what the card they are in says.+ * always the current one's), no split to draw between the note's own names and Trilium's — every+ * one of them is Trilium's, which is what the card they are in says — and nothing to be picked+ * out for, being rewritten from the note's content rather than carried anywhere.*/readOnly?: boolean;onOpen: (attribute: Attribute, isOwned: boolean, anchor: HTMLElement | null, e: MouseEvent) => void;+ /** Picks the row out, or takes it back out of the selection. */+ onSelect: (attributeId: string, e: MouseEvent) => void;+ onShowMenu: (attribute: Attribute, e: MouseEvent) => void;/** Asks for the in-place editor over the attribute's value; wired to editable labels alone. */onEditValue: (attribute: Attribute) => void;onDelete: (attribute: Attribute) => void;@@ -540,7 +835,7 @@ interface AttributeRowListProps {* Trilium reads for itself. What a row offers follows from whether the note owns its attribute rather* than from the card it is in: the definitions card holds the note's own alongside a template's.*/-function AttributeRowList({ rows, note, activeAttribute, valueEditor, readOnly, onOpen, onEditValue, onDelete }: AttributeRowListProps) {+function AttributeRowList({ rows, note, activeAttribute, valueEditor, selection, readOnly, onOpen, onSelect, onShowMenu, onEditValue, onDelete }: AttributeRowListProps) {function renderRows(group: AttributeEntry[]) {return (// The rows are menu items on a phone (see AttributeRow), and the theme dresses a menu item@@ -556,6 +851,13 @@ function AttributeRowList({ rows, note, activeAttribute, valueEditor, readOnly,active={activeAttribute === attribute}valueEditor={valueEditor?.attribute === attribute ? valueEditor.element : undefined}isSystem={isSystem && !readOnly}+ // A row is picked out by the attribute behind it, which a draft has yet to+ // become; the internal card's rows are not picked out at all (see above).+ selected={!readOnly && !!attribute.attributeId && selection.has(attribute.attributeId)}+ onSelect={!readOnly && attribute.attributeId+ ? (e) => onSelect(attribute.attributeId ?? "", e)+ : undefined}+ onShowMenu={!readOnly ? (e) => onShowMenu(attribute, e) : undefined}// An attribute of another note names it; the current note's own would name itself.showOwner={!isOwned && !readOnly}// A read-only row opens the popup as an inherited one does: to be read, not edited.@@ -598,25 +900,41 @@ interface AttributeRowProps {valueEditor?: ComponentChildren;/** Whether the name is one Trilium reads for itself rather than one the note was given. */isSystem?: boolean;+ /** Whether the row is picked out to be copied. */+ selected?: boolean;/** Names the note the attribute is inherited from, for attributes not owned by the current note. */showOwner?: boolean;onOpen: (anchor: HTMLElement | null, e: MouseEvent) => void;+ /** Picks the row out; absent for the rows that are not picked out at all (see the list above). */+ onSelect?: (e: MouseEvent) => void;+ onShowMenu?: (e: MouseEvent) => void;/** Starts the in-place edit of the value; absent for rows whose value is not edited in place. */onEditValue?: () => void;onDelete?: () => void;}-function AttributeRow({ attribute, note, active, valueEditor, isSystem, showOwner, onOpen, onEditValue, onDelete }: AttributeRowProps) {+function AttributeRow({ attribute, note, active, valueEditor, isSystem, selected, showOwner, onOpen, onSelect, onShowMenu, onEditValue, onDelete }: AttributeRowProps) {const rowRef = useRef<HTMLLIElement>(null);const attrType = getAttributeKind(attribute);const markerClass = getKindMarkerClass(attribute, attrType, isSystem);const kindIcon = getKindIcon(attribute, attrType);const kindTooltip = getKindTooltip(attribute, attrType, isSystem);- const rowClass = clsx("attribute-row", active && "active", valueEditor && "editing");+ const rowClass = clsx("attribute-row", active && "active", valueEditor && "editing", selected && "selected");function open(e: MouseEvent) {// Keep the container's closing handler from undoing this.e.stopPropagation();++ // Held down, the modifiers that pick rows out mean the press is about the selection rather+ // than about the one attribute the popup would show.+ if (onSelect && (e.ctrlKey || e.metaKey || e.shiftKey)) {+ // Nothing of the press is the browser's here: a shift-press would otherwise take the text+ // between the two rows as a selection, over the rows being picked out.+ e.preventDefault();+ onSelect(e);+ return;+ }+onOpen(rowRef.current, e);}@@ -698,7 +1016,7 @@ function AttributeRow({ attribute, note, active, valueEditor, isSystem, showOwne}return (- <li ref={rowRef} class={rowClass} onClick={open}>+ <li ref={rowRef} class={rowClass} onClick={open} onContextMenu={onShowMenu}>{/* The icon is what carries the row's one tooltip: everything else about a row is alreadywritten on it, and what the icon (badge and all) stands for is exactly what is not. */}<span class={clsx("attribute-kind", markerClass)} title={kindTooltip}>@@ -716,6 +1034,22 @@ function AttributeRow({ attribute, note, active, valueEditor, isSystem, showOwne*/const IS_MOBILE = isMobile();+/** Shared so that clearing a selection that is already empty is not a change to be redrawn for. */+const EMPTY_SELECTION: ReadonlySet<string> = new Set();++/**+ * Whether the note's definitions say the attribute's field holds a set rather than a single value,+ * which is what a paste over a name the note already carries turns on: a set takes the pasted value+ * alongside what it holds, where a single value is replaced by it.+ */+export function isMultiValued(note: FNote | null | undefined, attribute: Attribute) {+ const definition = note?.getAttributeDefinitions()+ .find((candidate) => candidate.name === `${attribute.type}:${attribute.name}`)+ ?.getDefinition();++ return definition?.multiplicity === "multi";+}+/*** What the attribute is, as an icon. A definition takes the icon of the field it sets up, the same one* the popup offers that field under — it needs no marker of its own, being only ever listed in a card