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
client/collections/board/copy reference: add support for pasting as links in text notes
Adorian Doran9d947359f780
diff --git a/apps/client/src/services/clipboard_ext.spec.ts b/apps/client/src/services/clipboard_ext.spec.tsindex e625a1b08b..88745d444a 100644--- a/apps/client/src/services/clipboard_ext.spec.ts+++ b/apps/client/src/services/clipboard_ext.spec.ts@@ -2,7 +2,10 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import toast from "./toast.js";import utils from "./utils.js";-import { copyHtml, copyHtmlWithToast, copyText, copyTextWithToast } from "./clipboard_ext.js";+import { buildNote } from "../test/easy-froca";+import {+ copyHtml, copyHtmlWithToast, copyReferenceWithToast, copyText, copyTextWithToast+} from "./clipboard_ext.js";const originalClipboard = Object.getOwnPropertyDescriptor(navigator, "clipboard");@@ -196,3 +199,27 @@ describe("copyHtmlWithToast", () => {expect(showMessage).not.toHaveBeenCalled();});});++describe("copyReferenceWithToast", () => {+ it("copies a reference link drawn from what the href points at", async () => {+ setClipboard(undefined);+ const copyHtmlToClipboard = vi.spyOn(utils, "copyHtmlToClipboard").mockReturnValue(true);+ const showMessage = vi.spyOn(toast, "showMessage").mockImplementation(() => {});+ const board = buildNote({ title: "Board" });+ const href = `#root/${board.noteId}?column=colTodo00001&columnTitle=To%20Do`;++ await copyReferenceWithToast(href);++ const [ html, plainText ] = copyHtmlToClipboard.mock.calls[0];+ // The editor keeps only the class and the href, and draws the rest from the href itself,+ // so the markup is read back the way a paste parses it.+ const parsed = document.createElement("div");+ parsed.innerHTML = html;+ const $anchor = parsed.querySelector("a.reference-link");+ expect($anchor?.getAttribute("href")).toBe(href);+ expect($anchor?.textContent).toContain("Board");+ // What a Markdown or code note pastes, where the rich flavour is of no use.+ expect(plainText).toBe(href);+ expect(showMessage).toHaveBeenCalledTimes(1);+ });+});diff --git a/apps/client/src/services/clipboard_ext.ts b/apps/client/src/services/clipboard_ext.tsindex 36e38a866b..ded51bfcf5 100644--- a/apps/client/src/services/clipboard_ext.ts+++ b/apps/client/src/services/clipboard_ext.ts@@ -1,4 +1,5 @@import { t } from "./i18n.js";+import link from "./link.js";import toast from "./toast.js";import utils from "./utils.js";@@ -80,3 +81,19 @@ export async function copyHtmlWithToast(html: string, plainText: string = html)toast.showError(t("clipboard.copy_failed"));}}++/**+ * Copies `href` as a reference link, so that pasting it into a note's content gives the title, icon+ * and colour of what it points at rather than the address itself. Reports the outcome as a toast.+ *+ * The plain-text alternative is the address, which is what a target taking no HTML — a code note, a+ * Markdown note, a terminal — needs to build a link of its own. The editor keeps only the `href`+ * when it takes the rich flavour in and draws the rest from it, so the markup built here is what a+ * non-Trilium target gets.+ */+export async function copyReferenceWithToast(href: string) {+ const $link = $("<a>").addClass("reference-link").attr("href", href);+ await link.loadReferenceLinkTitle($link, href);++ await copyHtmlWithToast($link[0].outerHTML, href);+}diff --git a/apps/client/src/services/link.spec.ts b/apps/client/src/services/link.spec.tsindex 3f7a1072fd..3a0effad99 100644--- a/apps/client/src/services/link.spec.ts+++ b/apps/client/src/services/link.spec.ts@@ -807,6 +807,24 @@ describe("getReferenceLinkTitle / getReferenceLinkTitleSync", () => {expect(linkService.getReferenceLinkTitleSync(`#root/${note2.noteId}?viewMode=attachments&attachmentId=a1`)).toBe("Matched");});+ it("names the card a board reference points at, rather than the board", async () => {+ const board = buildNote({ title: "Board" });+ const card = buildNote({ title: "Card" });+ const href = `#root/${board.noteId}?card=${card.noteId}`;++ expect(await linkService.getReferenceLinkTitle(href)).toBe("Card");+ expect(linkService.getReferenceLinkTitleSync(href)).toBe("Card");+ });++ it("names the board a column reference points at, and the column after it", async () => {+ const board = buildNote({ title: "Board" });+ const href = `#root/${board.noteId}?column=colTodo00001&columnTitle=To%20Do`;++ // The link body is the board, so the column shows only where a suffix can be drawn.+ expect(await linkService.getReferenceLinkTitle(href)).toBe("Board");+ expect(linkService.getReferenceLinkTitleSync(href)).toBe("Board: To Do");+ });+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;@@ -867,6 +885,44 @@ describe("loadReferenceLinkTitle", () => {expect($iconSpan.hasClass("bx-star")).toBe(true);});+ it("draws a card reference from the card's own icon and colour", async () => {+ const board = buildNote({ title: "Board" });+ const card = buildNote({ title: "Card", "#color": "green", "#iconClass": "bx bx-task" });+ const href = `#root/${board.noteId}?card=${card.noteId}`;+ const $el = $("<span>");++ await linkService.loadReferenceLinkTitle($el, href);++ expect($el.text()).toBe("Card");+ expect($el.hasClass(card.getColorClass())).toBe(true);+ expect($el.children("span").first().hasClass("bx-task")).toBe(true);+ });++ it("appends the column a reference names, tinted with its own colour", async () => {+ const board = buildNote({ title: "Board" });+ const href = `#root/${board.noteId}?column=colTodo00001&columnTitle=To%20Do`+ + "&columnIcon=bx%20bx-star&columnColor=%23ff8800";+ const $el = $("<span>");++ await linkService.loadReferenceLinkTitle($el, href);++ expect($el.text()).toContain("Board:");+ const $column = $el.find("small");+ expect($column.text()).toBe(" To Do");+ expect($column.children("span").hasClass("bx-star")).toBe(true);+ expect($column.hasClass("color-FF8800")).toBe(true);+ });++ it("falls back to a column glyph for a reference carrying no icon of its own", async () => {+ const board = buildNote({ title: "Board" });+ const $el = $("<span>");++ await linkService.loadReferenceLinkTitle($el,+ `#root/${board.noteId}?column=colTodo00001&columnTitle=To%20Do`);++ expect($el.find("small span").hasClass("bx-columns")).toBe(true);+ });+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}`);diff --git a/apps/client/src/services/link.ts b/apps/client/src/services/link.tsindex f35ca9d36b..e282b20ab9 100644--- a/apps/client/src/services/link.ts+++ b/apps/client/src/services/link.ts@@ -3,12 +3,16 @@ import { ALLOWED_PROTOCOLS } from "@triliumnext/commons";import appContext, { type NoteCommandData } from "../components/app_context.js";import { openInCurrentNoteContext } from "../components/note_context.js";import linkContextMenuService from "../menus/link_context_menu.js";+import cssClassManager from "./css_class_manager.js";import froca from "./froca.js";import { t } from "./i18n.js";import { showError } from "./toast.js";import treeService from "./tree.js";import utils from "./utils.js";+/** The icon a column reference falls back to when the link carries none of its own. */+const DEFAULT_COLUMN_REFERENCE_ICON = "bx bx-columns";+function getNotePathFromUrl(url: string) {const notePathMatch = /#(root[A-Za-z0-9_/]*)$/.exec(url);@@ -80,6 +84,15 @@ export interface ViewScope {* it. Consumed once, as `bookmark` is.*/column?: string;+ /**+ * How a column reference names its column: the title, icon and colour the board showed when the+ * reference was made. Carried so that a link to a column can be drawn without reading the+ * board's configuration; {@link column} is what the board resolves, so a renamed column is+ * still found and only the label goes stale.+ */+ columnTitle?: string;+ columnIcon?: string;+ columnColor?: string;/*** The note id of the board card a reference points at, revealed the same way {@link column}* is.@@ -107,7 +120,8 @@ const NOTE_PATH_PATTERN = /^[_a-z0-9]{4,}(\/[_a-z0-9]{4,})*$/i;const MAX_SPLIT_PANES_IN_HASH = 8;/** Hash parameters that belong to a pane's view scope rather than to the window as a whole. */-const VIEW_SCOPE_PARAMS = ["viewMode", "attachmentId", "bookmark", "column", "card"];+const VIEW_SCOPE_PARAMS = ["viewMode", "attachmentId", "bookmark", "column", "columnTitle",+ "columnIcon", "columnColor", "card"];interface CreateLinkOptions {title?: string;@@ -245,6 +259,9 @@ export function calculateHash(viewScope.viewMode && viewScope.viewMode !== "default" ? { viewMode: viewScope.viewMode } : null,viewScope.attachmentId ? { attachmentId: viewScope.attachmentId } : null,viewScope.column ? { column: viewScope.column } : null,+ viewScope.columnTitle ? { columnTitle: viewScope.columnTitle } : null,+ viewScope.columnIcon ? { columnIcon: viewScope.columnIcon } : null,+ viewScope.columnColor ? { columnColor: viewScope.columnColor } : null,viewScope.card ? { card: viewScope.card } : null,viewScope.searchTerms?.length? { searchTerms: viewScope.searchTerms.map(encodeURIComponent).join(",") }@@ -630,14 +647,18 @@ async function loadReferenceLinkTitle($el: JQuery<HTMLElement>, href: string | nconsole.warn("Missing note ID.");}- const note = noteId ? await froca.getNote(noteId, true) : null;+ // A card reference names the board in its path and the card in `card`, so the card is what the+ // link is drawn from while the board is what it opens.+ const subjectId = viewScope?.card || noteId;+ const note = subjectId ? await froca.getNote(subjectId, true) : null;if (note) {$el.addClass(note.getColorClass());}const title = await getReferenceLinkTitle(href);- $el.text(title);+ // A column reference reads "<board>: <column>", the column following in a suffix of its own.+ $el.text(viewScope?.columnTitle ? `${title}:` : title);if (viewScope?.bookmark) {$el.append($("<small>").append(@@ -646,8 +667,17 @@ async function loadReferenceLinkTitle($el: JQuery<HTMLElement>, href: string | n));}- if (noteId && note) {- const icon = await getLinkIcon(noteId, viewScope?.viewMode);+ if (viewScope?.columnTitle) {+ $el.append($("<small>")+ .addClass(cssClassManager.createClassForColor(viewScope.columnColor ?? null))+ .append(+ $("<span>").addClass(viewScope.columnIcon || DEFAULT_COLUMN_REFERENCE_ICON),+ document.createTextNode(` ${viewScope.columnTitle}`)+ ));+ }++ if (subjectId && note) {+ const icon = await getLinkIcon(subjectId, viewScope?.viewMode);if (icon) {$el.prepend($("<span>").addClass(icon));@@ -661,7 +691,8 @@ async function getReferenceLinkTitle(href: string) {return "[missing note]";}- const note = await froca.getNote(noteId);+ // A card reference is named by the card, not by the board its path names.+ const note = await froca.getNote(viewScope?.card || noteId);if (!note) {return "[missing note]";}@@ -681,7 +712,7 @@ function getReferenceLinkTitleSync(href: string) {return "[missing note]";}- const note = froca.getNoteFromCache(noteId);+ const note = froca.getNoteFromCache(viewScope?.card || noteId);if (!note) {return "[missing note]";}@@ -696,6 +727,10 @@ function getReferenceLinkTitleSync(href: string) {return attachment ? attachment.title : "[missing attachment]";}+ if (viewScope?.columnTitle) {+ return `${note.title}: ${viewScope.columnTitle}`;+ }+if (viewScope?.bookmark) {return `${note.title} - ${viewScope.bookmark}`;}diff --git a/apps/client/src/stylesheets/style.css b/apps/client/src/stylesheets/style.cssindex 4ab85522db..dc47777cf8 100644--- a/apps/client/src/stylesheets/style.css+++ b/apps/client/src/stylesheets/style.css@@ -2292,6 +2292,12 @@ button.close:hover {margin-inline-end: 3px;}+/* The board column a reference points at. `--custom-color` is set by the theme on+ `.use-note-color`. */+.reference-link small.use-note-color {+ color: var(--custom-color, inherit);+}+.options-section:first-of-type h4 {margin-top: 0;}diff --git a/apps/client/src/widgets/collections/board/api.spec.ts b/apps/client/src/widgets/collections/board/api.spec.tsindex dc1770b3cc..5b85a03b47 100644--- a/apps/client/src/widgets/collections/board/api.spec.ts+++ b/apps/client/src/widgets/collections/board/api.spec.ts@@ -2634,13 +2634,24 @@ describe("references to a board's columns and cards", () => {async () => {const board = buildNote({ title: "Board" });const { api } = createApi(- { columns: [ { value: "To Do", id: "colTodo00001" } ] }, [ "To Do" ], board);+ {+ columns: [+ { value: "To Do", id: "colTodo00001", icon: "bx bx-star",+ color: "#ff8800" },+ { value: "Done", id: "colDone00001" }+ ]+ },+ [ "To Do", "Done" ], board);api.noteContext = { notePath: `root/parent1234/${board.noteId}` } as NoteContext;- await expect(api.getColumnReference("To Do"))- .resolves.toBe(`#root/parent1234/${board.noteId}?column=colTodo00001`);- expect(api.getCardReference("card00000001"))- .toBe(`#root/parent1234/${board.noteId}?card=card00000001`);+ const path = `root/parent1234/${board.noteId}`;+ await expect(api.getColumnReference("To Do")).resolves.toBe(+ `#${path}?column=colTodo00001&columnTitle=To%20Do&columnIcon=bx%20bx-star`+ + "&columnColor=%23ff8800");+ // A column carrying no colour of its own leaves the parameter out.+ await expect(api.getColumnReference("Done")).resolves.toBe(+ `#${path}?column=colDone00001&columnTitle=Done&columnIcon=bx%20bx-circle`);+ expect(api.getCardReference("card00000001")).toBe(`#${path}?card=card00000001`);});/** A board drawn outside a pane, such as in a note preview, still has itself to name. */diff --git a/apps/client/src/widgets/collections/board/api.ts b/apps/client/src/widgets/collections/board/api.tsindex e3cd7af46a..b0469e8336 100644--- a/apps/client/src/widgets/collections/board/api.ts+++ b/apps/client/src/widgets/collections/board/api.ts@@ -31,7 +31,9 @@ import {} from "./columns";import { readColumns, writeColumns } from "./column_storage";import { ColumnItem, ColumnMap } from "./data";-import { cardReference, columnReference, newColumnId, readColumnId } from "./reference";+import {+ cardReference, ColumnReferenceLabel, columnReference, newColumnId, readColumnId+} from "./reference";import { SORT_DESCENDING_LABEL, SORT_LABEL } from "./sort";/** Which end of a column a new card is made at. */@@ -609,18 +611,28 @@ export default class BoardApi {/*** What each column is called, the icon it shows and how many cards it holds, which the right* pane's outline is drawn from.+ */+ getColumnOutline(columns: string[]) {+ return columns.map(column => {+ const { title, icon } = this.getColumnLabel(column);+ return { value: column, title, icon, count: this.byColumn?.get(column)?.length ?? 0 };+ });+ }++ /**+ * What names a column wherever it stands for itself away from the board: its title, its icon+ * and the colour it is tinted with.** A relation board keys its columns by note id, so each one is named from the note's title.*/- getColumnOutline(columns: string[]) {- return columns.map(column => ({- value: column,+ getColumnLabel(column: string): ColumnReferenceLabel {+ return {title: this.isRelationMode && column !== INBOX_COLUMN? froca.getNoteFromCache(column)?.title ?? column: this.getColumnTitle(column),icon: this.getColumnIcon(column) ?? DEFAULT_COLUMN_ICON,- count: this.byColumn?.get(column)?.length ?? 0- }));+ color: this.storedColumns.find(col => col.value === column)?.color+ };}/**@@ -852,7 +864,8 @@ export default class BoardApi {* copying a reference writes to `board.json` where nothing has been stored for the column yet.*/async getColumnReference(column: string) {- return columnReference(this.boardNotePath, await this.ensureColumnId(column));+ return columnReference(this.boardNotePath, await this.ensureColumnId(column),+ this.getColumnLabel(column));}/** The link that opens this board on one of its cards, which is named by its own note id. */diff --git a/apps/client/src/widgets/collections/board/context_menu.spec.ts b/apps/client/src/widgets/collections/board/context_menu.spec.tsindex 96a72e3d3d..15901f28f3 100644--- a/apps/client/src/widgets/collections/board/context_menu.spec.ts+++ b/apps/client/src/widgets/collections/board/context_menu.spec.ts@@ -263,7 +263,7 @@ describe("Board column context menu", () => {/** The id is settled by the server, so the link is awaited before it is copied. */it("copies a link to the column once its id has been assigned", async () => {- const copy = vi.spyOn(clipboard, "copyTextWithToast").mockImplementation(() => {});+ const copy = vi.spyOn(clipboard, "copyReferenceWithToast").mockResolvedValue();const api = {getColumnReference: async (column: string) =>`#root/board1234?column=id-of-${column}`@@ -591,7 +591,7 @@ describe("Board item context menu", () => {});it("copies a link to the card, which the card's own note id names", () => {- const copy = vi.spyOn(clipboard, "copyTextWithToast").mockImplementation(() => {});+ const copy = vi.spyOn(clipboard, "copyReferenceWithToast").mockResolvedValue();const note = buildNote({ title: "Card" }) as FNote;const api = {columns: [],diff --git a/apps/client/src/widgets/collections/board/context_menu.ts b/apps/client/src/widgets/collections/board/context_menu.tsindex cb2ba165e0..8105bccdda 100644--- a/apps/client/src/widgets/collections/board/context_menu.ts+++ b/apps/client/src/widgets/collections/board/context_menu.ts@@ -8,7 +8,7 @@ import NoteColorPicker from "../../../menus/custom-items/NoteColorPicker";import link_context_menu from "../../../menus/link_context_menu";import attributes from "../../../services/attributes";import branches from "../../../services/branches";-import { copyTextWithToast } from "../../../services/clipboard_ext";+import { copyReferenceWithToast } from "../../../services/clipboard_ext";import dialog from "../../../services/dialog";import { t } from "../../../services/i18n";import { shared } from "../../../services/note_set";@@ -77,7 +77,7 @@ export function openColumnContextMenu(api: Api, event: ContextMenuEvent, column:{title: t("board_view.copy-reference"),uiIcon: "bx bx-directions",- handler: async () => copyTextWithToast(await api.getColumnReference(column.value))+ handler: async () => copyReferenceWithToast(await api.getColumnReference(column.value))}];@@ -536,7 +536,7 @@ export function openNoteContextMenu(api: Api, event: ContextMenuEvent, target: N{title: t("board_view.copy-reference"),uiIcon: "bx bx-directions",- handler: () => copyTextWithToast(api.getCardReference(note.noteId))+ handler: () => copyReferenceWithToast(api.getCardReference(note.noteId))},{ kind: "separator" }];diff --git a/apps/client/src/widgets/collections/board/reference.spec.tsx b/apps/client/src/widgets/collections/board/reference.spec.tsxindex ccf9425e2e..47f0a3c730 100644--- a/apps/client/src/widgets/collections/board/reference.spec.tsx+++ b/apps/client/src/widgets/collections/board/reference.spec.tsx@@ -40,13 +40,20 @@ const HIGH_ID = "colHigh00001";describe("board reference links", () => {it("names a column and a card in a note path the app can follow", () => {- expect(columnReference("root/board123", TODO_ID)).toBe(`#root/board123?column=${TODO_ID}`);+ const label = { title: "To Do", icon: "bx bx-star", color: "#ff8800" };+ expect(columnReference("root/board123", TODO_ID, label)).toBe(+ `#root/board123?column=${TODO_ID}&columnTitle=To%20Do&columnIcon=bx%20bx-star`+ + "&columnColor=%23ff8800");+ // A column carrying no colour of its own leaves the parameter out.+ expect(columnReference("root/board123", DONE_ID, { title: "Done", icon: "bx bx-circle" }))+ .toBe(`#root/board123?column=${DONE_ID}&columnTitle=Done&columnIcon=bx%20bx-circle`);expect(cardReference("root/board123", "card00000001")).toBe("#root/board123?card=card00000001");});- it("escapes what a column id could otherwise end the parameter with", () => {- expect(columnReference("root/board123", "a b&c=d")).toBe("#root/board123?column=a%20b%26c%3Dd");+ it("escapes what a column id or title could otherwise end the parameter with", () => {+ expect(columnReference("root/board123", "a b&c=d", { title: "x&y", icon: "bx bx-circle" }))+ .toBe("#root/board123?column=a%20b%26c%3Dd&columnTitle=x%26y&columnIcon=bx%20bx-circle");});it("mints ids of a note id's length, and distinct ones", () => {diff --git a/apps/client/src/widgets/collections/board/reference.ts b/apps/client/src/widgets/collections/board/reference.tsindex 177b86ef96..ea211bb2a7 100644--- a/apps/client/src/widgets/collections/board/reference.ts+++ b/apps/client/src/widgets/collections/board/reference.ts@@ -3,7 +3,8 @@** A reference is a note path plus a `?column=` or `?card=` parameter. `link.ts` carries both in the* pane's view scope, as it carries `?bookmark=`, and {@link useBoardReference} reads the parameter- * once and reveals what it names.+ * once and reveals what it names. A column reference also carries the column's title, icon and+ * colour, which is what `link.ts` draws it from when the reference is pasted into a note.** A card uses its note id. A column uses an id stored in `board.json`, because renaming a column* rewrites the value its cards carry.@@ -95,6 +96,9 @@ export function useBoardReference({: { board: noteId, kind: "card", noteId: viewScope.card ?? "" };switchedTo.current = null;viewScope.column = undefined;+ viewScope.columnTitle = undefined;+ viewScope.columnIcon = undefined;+ viewScope.columnColor = undefined;viewScope.card = undefined;}@@ -268,9 +272,32 @@ export function readColumnId(return columns?.find(column => column.value === value)?.id;}-/** The link that opens a board on one of its columns. */-export function columnReference(notePath: string, columnId: string) {- return `#${notePath}?column=${encodeURIComponent(columnId)}`;+/** How a column reference names its column, which the link carries for display only. */+export interface ColumnReferenceLabel {+ title: string;+ icon: string;+ color?: string;+}++/**+ * The link that opens a board on one of its columns.+ *+ * The label rides along so that a link can be drawn without reading `board.json`, which only the+ * board itself loads. The id is what the board resolves, so renaming a column leaves the link+ * working and only its label behind.+ */+export function columnReference(notePath: string, columnId: string, label: ColumnReferenceLabel) {+ const params: [ string, string ][] = [+ [ "column", columnId ],+ [ "columnTitle", label.title ],+ [ "columnIcon", label.icon ]+ ];+ if (label.color) {+ params.push([ "columnColor", label.color ]);+ }++ const query = params.map(([ name, value ]) => `${name}=${encodeURIComponent(value)}`).join("&");+ return `#${notePath}?${query}`;}/** The link that opens a board on one of its cards. */