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/text editor: add "copy public link" for blocks
Adorian Doran214f7472625f
diff --git a/apps/client/src/services/block_reference.spec.ts b/apps/client/src/services/block_reference.spec.tsindex 18c7b7187f..d21c81aa78 100644--- a/apps/client/src/services/block_reference.spec.ts+++ b/apps/client/src/services/block_reference.spec.ts@@ -5,19 +5,21 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import type { CommandNames } from "../components/app_context.js";import type { MenuCommandItem, MenuItem } from "../menus/context_menu.js";import {- buildBlockReferenceMenuItems, consumeBlockReference, copyBlockReference, copyTabReference,- getBlockRangeElements, getClipboardBlockReference, highlightBlockReference,+ buildBlockReferenceMenuItems, consumeBlockReference, copyBlockReference, copyBlockShareLink,+ copyTabReference, getBlockRangeElements, getClipboardBlockReference, highlightBlockReference,openBlockHandleMenu, revealHighlightedBlocks} from "./block_reference.js";import type { ViewScope } from "./link.js";const {- showError, showMessage, showMenu, copyHtmlWithToast, getTextEditorContaining, getNote+ showError, showMessage, showMenu, copyHtmlWithToast, copyTextWithToast, getTextEditorContaining,+ getNote} = vi.hoisted(() => ({showError: vi.fn(),showMessage: vi.fn(),showMenu: vi.fn(),copyHtmlWithToast: vi.fn(),+ copyTextWithToast: vi.fn(),getTextEditorContaining: vi.fn(),getNote: vi.fn()}));@@ -27,7 +29,7 @@ vi.mock("./i18n.js", () => ({vi.mock("./toast.js", () => ({ default: { showError, showMessage } }));vi.mock("../menus/context_menu.js", () => ({ default: { show: showMenu } }));vi.mock("../menus/text_editor_context_menu.js", () => ({ getTextEditorContaining }));-vi.mock("./clipboard_ext.js", () => ({ copyHtmlWithToast }));+vi.mock("./clipboard_ext.js", () => ({ copyHtmlWithToast, copyTextWithToast }));vi.mock("./froca.js", () => ({ default: { getNote } }));vi.mock("./content_renderer.js", () => ({EXCERPT_BOX_SIZE: "full",@@ -285,19 +287,56 @@ describe("copyTabReference", () => {});});+describe("copyBlockShareLink", () => {+ it("copies a link to the selected blocks on the shared page and flashes them", () => {+ const root = buildContainer(+ "<p data-trilium-block-id=\"s1\">Start</p><p data-trilium-block-id=\"e1\">End</p>"+ );+ const editor = buildEditor(root, { startId: "s1", endId: "e1", count: 2 });++ copyBlockShareLink(editor, "https://notes.example.com/share/page");++ expect(editor.execute).toHaveBeenCalledWith("assignBlockReference");+ expect(copyTextWithToast).toHaveBeenCalledWith(+ "https://notes.example.com/share/page?block=s1:e1"+ );+ expect(getFlashed(root)).toEqual([ "Start", "End" ]);+ });++ it("copies nothing when no block is referenced", () => {+ const root = buildContainer("<p>one</p>");+ const shareLink = "https://notes.example.com/share/page";++ copyBlockShareLink(buildEditor(root, undefined), shareLink);+ const missingTarget = { startId: "x", endId: "x", count: 1 };+ copyBlockShareLink(buildEditor(root, missingTarget), shareLink);++ expect(copyTextWithToast).not.toHaveBeenCalled();+ });+});+describe("openBlockHandleMenu", () => {- it("offers to copy a reference to the selected blocks", () => {+ it("offers to copy a reference to the selected blocks, and a public link if shared", () => {const event = new MouseEvent("contextmenu", { clientX: 10, clientY: 20 });const copyReference = vi.fn();+ const copyShareLink = vi.fn();+ const copyItem = expect.objectContaining({+ title: "block_reference.copy:3",+ handler: copyReference+ });- openBlockHandleMenu(event, 3, copyReference);+ openBlockHandleMenu(event, 3, { copyReference });+ openBlockHandleMenu(event, 3, { copyReference, copyShareLink });- expect(showMenu).toHaveBeenCalledWith(expect.objectContaining({+ expect(showMenu).toHaveBeenNthCalledWith(1, expect.objectContaining({x: event.pageX,y: event.pageY,- items: [ expect.objectContaining({- title: "block_reference.copy:3",- handler: copyReference+ items: [ copyItem ]+ }));+ expect(showMenu).toHaveBeenNthCalledWith(2, expect.objectContaining({+ items: [ copyItem, expect.objectContaining({+ title: "block_reference.copy_share_link:3",+ handler: copyShareLink}) ]}));});diff --git a/apps/client/src/services/block_reference.ts b/apps/client/src/services/block_reference.tsindex e6582eaf28..86ac33d8db 100644--- a/apps/client/src/services/block_reference.ts+++ b/apps/client/src/services/block_reference.ts@@ -1,7 +1,8 @@import type { CKTextEditor } from "@triliumnext/ckeditor5";import { CLASSES as TAB_CLASSES } from "@triliumnext/ckeditor5/src/plugins/tabs/constants.js";import {- type BlockRange, formatBlockRange, parseBlockRange, resolveBlockRange, resolveBlockReference+ type BlockRange, encodeBlockParameter, formatBlockRange, parseBlockRange, resolveBlockRange,+ resolveBlockReference} from "@triliumnext/commons";import type { CommandNames } from "../components/app_context.js";@@ -9,7 +10,7 @@ import contextMenu, { type MenuItem } from "../menus/context_menu.js";import type { ClipboardAccess } from "../menus/table_context_menu.js";import { getTextEditorContaining } from "../menus/text_editor_context_menu.js";import { getBlockExcerpt } from "./block_excerpts.js";-import { copyHtmlWithToast } from "./clipboard_ext.js";+import { copyHtmlWithToast, copyTextWithToast } from "./clipboard_ext.js";import { revealElement } from "./collapsible.js";import froca from "./froca.js";import { t } from "./i18n.js";@@ -40,18 +41,39 @@ export interface BlockReferenceMenuItems {paste: MenuItem<CommandNames>[];}+/** The actions of the block handle menu. */+export interface BlockHandleMenuActions {+ /** Copies a reference to the selected blocks. */+ copyReference: () => void;+ /** Copies a link to the selected blocks on the shared page of the note, if it is shared. */+ copyShareLink?: () => void;+}+/** The component of a text editor that copies references to the blocks of its note. */interface BlockReferenceHost {copyBlockReference?(): Promise<void>;copyTabReference?(): void;}-/** Opens the menu of the block handle at `event`, which copies a reference to `count` blocks. */-export function openBlockHandleMenu(event: MouseEvent, count: number, copyReference: () => void) {+/** Opens the menu of the block handle at `event`, for `count` selected blocks. */+export function openBlockHandleMenu(+ event: MouseEvent,+ count: number,+ { copyReference, copyShareLink }: BlockHandleMenuActions+) {+ const items = [ getCopyItem(count, copyReference) ];+ if (copyShareLink) {+ items.push({+ title: t("block_reference.copy_share_link", { count }),+ uiIcon: "bx bx-world",+ handler: copyShareLink+ });+ }+void contextMenu.show({x: event.pageX,y: event.pageY,- items: [ getCopyItem(count, copyReference) ],+ items,selectMenuItemHandler: () => {}});}@@ -122,6 +144,19 @@ export async function copyTabReference(await copyReference(editor, editor.execute("assignTabReference"), notePath, noteTitle);}+/**+ * Gives ids to the selected blocks of `editor`, flashes the blocks and copies a link to them on+ * the shared page of the note, whose URL is `shareLink`.+ */+export function copyBlockShareLink(editor: CKTextEditor, shareLink: string) {+ const target = editor.execute("assignBlockReference");+ if (!target || !flashBlockRange(editor, target)) {+ return;+ }++ copyTextWithToast(`${shareLink}?block=${encodeBlockParameter(formatBlockRange(target))}`);+}+/** Flashes the blocks of `target` and copies a reference link to them. */async function copyReference(editor: CKTextEditor,@@ -129,23 +164,36 @@ async function copyReference(notePath: string,noteTitle: string) {- const root = editor.editing.view.getDomRoot();- const { start, end } = target && root- ? resolveBlockRange<HTMLElement>(root, target)- : { start: null, end: null };- if (!target || !start || !end) {+ const blocks = target && flashBlockRange(editor, target);+ if (!target || !blocks) {return;}- flashBlocks(getBlockRangeElements(start, end));const href = calculateHash({ notePath, viewScope: { block: formatBlockRange(target) } });const $link = $("<a>").addClass("reference-link").attr("href", href)- .text(`${noteTitle} - ${getBlockExcerpt(start, end)}`);+ .text(`${noteTitle} - ${getBlockExcerpt(blocks.start, blocks.end)}`);await copyHtmlWithToast($link[0].outerHTML, href);}+/**+ * Flashes the blocks of `target` in `editor`. Returns the first and the last block, or `null` when+ * one of them is not found.+ */+function flashBlockRange(editor: CKTextEditor, target: BlockRange) {+ const root = editor.editing.view.getDomRoot();+ const { start, end } = root+ ? resolveBlockRange<HTMLElement>(root, target)+ : { start: null, end: null };+ if (!start || !end) {+ return null;+ }++ flashBlocks(getBlockRangeElements(start, end));+ return { start, end };+}+/*** Reads and clears `viewScope.block`, then scrolls to the blocks it points at in `container` and* flashes them. When a block is missing, the blocks found are shown, with an error toast.diff --git a/apps/client/src/services/share_link.spec.ts b/apps/client/src/services/share_link.spec.tsindex 8567673c24..810b0504c7 100644--- a/apps/client/src/services/share_link.spec.ts+++ b/apps/client/src/services/share_link.spec.ts@@ -1,6 +1,9 @@-import { afterEach, describe, expect, it } from "vitest";+import { afterEach, describe, expect, it, vi } from "vitest";-import { buildShareLink } from "./share_link";+import { buildNote } from "../test/easy-froca";+import froca from "./froca";+import options from "./options";+import { buildShareLink, getNoteShareLink, getShareScope } from "./share_link";describe("buildShareLink", () => {const originalGlob = window.glob;@@ -82,3 +85,59 @@ describe("buildShareLink", () => {expect(buildShareLink(shareId, null)).toBe(`http://localhost:3000/share/${encoded}`);});});++describe("getNoteShareLink", () => {+ afterEach(() => {+ vi.unstubAllGlobals();+ });++ it("links a shared note to its shared page, by its alias or its id", () => {+ const host = "https://notes.example.com";+ options.load({ syncServerHost: host });+ const shareRoot = buildNote({+ id: "_share",+ title: "Shared notes",+ children: [+ { id: "sharedAlias", title: "Aliased", "#shareAlias": "my-page" },+ { id: "sharedPlain", title: "Plain" }+ ]+ });+ const unshared = buildNote({ title: "Private" });++ expect(getNoteShareLink(froca.notes.sharedAlias)).toBe(`${host}/share/my-page`);+ expect(getNoteShareLink(froca.notes.sharedPlain)).toBe(`${host}/share/sharedPlain`);+ expect(getNoteShareLink(shareRoot)).toBeNull();+ expect(getNoteShareLink(unshared)).toBeNull();+ });++ it("gives no link in the mobile app without a sync server", () => {+ vi.stubGlobal("Capacitor", { isNativePlatform: () => true });+ const shareRoot = buildNote({+ id: "_share",+ title: "Shared notes",+ children: [ { title: "Shared" } ]+ });+ const shared = froca.notes[shareRoot.children[0]];++ options.load({ syncServerHost: "" });+ expect(getNoteShareLink(shared)).toBeNull();++ options.load({ syncServerHost: "https://notes.example.com" });+ expect(getNoteShareLink(shared)).toBe(`https://notes.example.com/share/${shared.noteId}`);+ });+});++describe("getShareScope", () => {+ it("tells a public share from a local one, a standalone preview and one only an export publishes", () => {+ const syncServerHost = "https://sync.example.com";+ const platform = { isElectron: false, isStandalone: false, isMobileApp: false };++ expect(getShareScope({ ...platform, syncServerHost: "" })).toBe("public");+ expect(getShareScope({ ...platform, isElectron: true, syncServerHost: "" })).toBe("local");+ expect(getShareScope({ ...platform, isElectron: true, syncServerHost })).toBe("public");+ expect(getShareScope({ ...platform, isStandalone: true, syncServerHost: "" })).toBe("preview");+ expect(getShareScope({ ...platform, isStandalone: true, syncServerHost })).toBe("public");+ expect(getShareScope({ ...platform, isStandalone: true, isMobileApp: true, syncServerHost: "" })).toBe("export-only");+ expect(getShareScope({ ...platform, isStandalone: true, isMobileApp: true, syncServerHost })).toBe("public");+ });+});diff --git a/apps/client/src/services/share_link.ts b/apps/client/src/services/share_link.tsindex fe60a8e1ef..63abd0923e 100644--- a/apps/client/src/services/share_link.ts+++ b/apps/client/src/services/share_link.ts@@ -1,3 +1,10 @@+import type FNote from "../entities/fnote.js";+import options from "./options.js";+import { isElectron, isMobileApp, isStandalone } from "./utils.js";++/** Where a shared note can be opened from, see `getShareScope()`. */+export type ShareScope = "public" | "local" | "preview" | "export-only";+/*** Builds the browser-openable URL for a shared note.*@@ -23,6 +30,63 @@ export function buildShareLink(shareId: string, syncServerHost: string | null |return appendSharePath(location.href, encodedShareId);}+/**+ * The URL of the shared page of `note`, or `null` when the note is not shared or its shared page+ * cannot be opened (`export-only` scope).+ */+export function getNoteShareLink(note: FNote): string | null {+ const syncServerHost = options.get("syncServerHost");+ const scope = getShareScope({+ isElectron: isElectron(),+ isStandalone: !!isStandalone,+ isMobileApp: isMobileApp(),+ syncServerHost+ });+ if (!note.isShared() || scope === "export-only") {+ return null;+ }++ return buildShareLink(getShareId(note), syncServerHost);+}++/**+ * Where a shared note can be opened from. `local` is the desktop app without a sync server, which+ * serves the page on the loopback address. `preview` is the standalone build without a sync server,+ * which renders the page in its own service worker, so only this browser can open it. `export-only`+ * is the mobile app without a sync server: its link opens nowhere, so the static export is the only+ * way to publish the note. A server cannot tell whether it is reachable from outside, so it always+ * reports `public`.+ */+export function getShareScope({ isElectron, isStandalone, isMobileApp, syncServerHost }: {+ isElectron: boolean;+ isStandalone: boolean;+ isMobileApp: boolean;+ syncServerHost: string | null | undefined;+}): ShareScope {+ if (syncServerHost) {+ return "public";+ }++ if (isMobileApp) {+ return "export-only";+ }++ if (isStandalone) {+ return "preview";+ }++ return isElectron ? "local" : "public";+}++/** The id in the URL of the shared page of `note`: empty for the share root. */+export function getShareId(note: FNote) {+ if (note.hasOwnedLabel("shareRoot")) {+ return "";+ }++ return note.getOwnedLabelValue("shareAlias") || note.noteId;+}+// `new URL("/share/x", base)` cannot stand in here: the leading slash makes the path absolute// and drops the base's own path, which an instance reverse-proxied under a subpath needs.function appendSharePath(base: string, encodedShareId: string): string {diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex 3553e52691..4d01c7f72c 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -4572,6 +4572,8 @@"block_reference": {"copy_one": "Copy reference to this block","copy_other": "Copy reference to these {{count}} blocks",+ "copy_share_link_one": "Copy public link to this block",+ "copy_share_link_other": "Copy public link to these {{count}} blocks","copy_tab": "Copy link to this tab","paste_as_link": "Paste reference as a link","paste_as_excerpt": "Paste reference as an excerpt",diff --git a/apps/client/src/widgets/layout/NoteBadges.spec.tsx b/apps/client/src/widgets/layout/NoteBadges.spec.tsxindex f949a96dd3..8fb871c20b 100644--- a/apps/client/src/widgets/layout/NoteBadges.spec.tsx+++ b/apps/client/src/widgets/layout/NoteBadges.spec.tsx@@ -23,7 +23,7 @@ vi.mock("../../services/i18n", () => ({import { buildNote } from "../../test/easy-froca";import { renderInto } from "../../test/render";-import { ClippedNoteBadge, ExecuteBadge, getShareScope, OfficePreviewBadge } from "./NoteBadges";+import { ClippedNoteBadge, ExecuteBadge, OfficePreviewBadge } from "./NoteBadges";const DOCX_MIME = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";@@ -142,18 +142,3 @@ describe("ClippedNoteBadge", () => {]);}});--describe("getShareScope", () => {- it("tells a public share from a local one, a standalone preview and one only an export publishes", () => {- const syncServerHost = "https://sync.example.com";- const platform = { isElectron: false, isStandalone: false, isMobileApp: false };-- expect(getShareScope({ ...platform, syncServerHost: "" })).toBe("public");- expect(getShareScope({ ...platform, isElectron: true, syncServerHost: "" })).toBe("local");- expect(getShareScope({ ...platform, isElectron: true, syncServerHost })).toBe("public");- expect(getShareScope({ ...platform, isStandalone: true, syncServerHost: "" })).toBe("preview");- expect(getShareScope({ ...platform, isStandalone: true, syncServerHost })).toBe("public");- expect(getShareScope({ ...platform, isStandalone: true, isMobileApp: true, syncServerHost: "" })).toBe("export-only");- expect(getShareScope({ ...platform, isStandalone: true, isMobileApp: true, syncServerHost })).toBe("public");- });-});diff --git a/apps/client/src/widgets/layout/NoteBadges.tsx b/apps/client/src/widgets/layout/NoteBadges.tsxindex 605d6e7411..f2e9783b22 100644--- a/apps/client/src/widgets/layout/NoteBadges.tsx+++ b/apps/client/src/widgets/layout/NoteBadges.tsx@@ -13,7 +13,9 @@ import dialog from "../../services/dialog";import { t } from "../../services/i18n";import { goToLinkExt } from "../../services/link";import server from "../../services/server";-import { buildShareLink } from "../../services/share_link";+import {+ buildShareLink, getShareId, getShareScope, type ShareScope+} from "../../services/share_link";import sync from "../../services/sync";import { isElectron, isMobileApp, isStandalone } from "../../services/utils";import { Badge, BadgeWithDropdown } from "../react/Badge";@@ -355,42 +357,3 @@ function useShareInfo(note: FNote | null | undefined) {})};}--/**- * Where a shared note can be opened from. `local` is the desktop app without a sync server, which- * serves the page on the loopback address. `preview` is the standalone build without a sync server,- * which renders the page in its own service worker, so only this browser can open it. `export-only`- * is the mobile app without a sync server: its link opens nowhere, so the static export is the only- * way to publish the note. A server cannot tell whether it is reachable from outside, so it always- * reports `public`.- */-export function getShareScope({ isElectron, isStandalone, isMobileApp, syncServerHost }: {- isElectron: boolean;- isStandalone: boolean;- isMobileApp: boolean;- syncServerHost: string | null | undefined;-}): ShareScope {- if (syncServerHost) {- return "public";- }-- if (isMobileApp) {- return "export-only";- }-- if (isStandalone) {- return "preview";- }-- return isElectron ? "local" : "public";-}--type ShareScope = "public" | "local" | "preview" | "export-only";--function getShareId(note: FNote) {- if (note.hasOwnedLabel("shareRoot")) {- return "";- }-- return note.getOwnedLabelValue("shareAlias") || note.noteId;-}diff --git a/apps/client/src/widgets/type_widgets/text/EditableText.tsx b/apps/client/src/widgets/type_widgets/text/EditableText.tsxindex 34c72fd658..d07b9a2dd0 100644--- a/apps/client/src/widgets/type_widgets/text/EditableText.tsx+++ b/apps/client/src/widgets/type_widgets/text/EditableText.tsx@@ -15,7 +15,8 @@ import { useEffect, useRef, useState } from "preact/hooks";import appContext from "../../../components/app_context";import {- consumeBlockReference, copyBlockReference, copyTabReference, openBlockHandleMenu+ consumeBlockReference, copyBlockReference, copyBlockShareLink, copyTabReference,+ openBlockHandleMenu} from "../../../services/block_reference";import { consumeBookmark } from "../../../services/bookmark_jump";import { getUploadBoxSize } from "../../../services/content_renderer";@@ -26,6 +27,7 @@ import type LoadResults from "../../../services/load_results";import note_create from "../../../services/note_create";import options from "../../../services/options";import { consumeSearchTerms } from "../../../services/search_jump";+import { getNoteShareLink } from "../../../services/share_link";import toast from "../../../services/toast";import utils, { isMobile } from "../../../services/utils";import type { IconPickerOpts } from "../../dialogs/icon_picker";@@ -180,13 +182,16 @@ export default function EditableText({consumeBlockReference(root, noteContext?.viewScope);}- async function copyReference(copy = copyBlockReference) {+ async function copyReference(+ copy: (editor: CKTextEditor, notePath: string, noteTitle: string) => void | Promise<void>+ = copyBlockReference+ ) {const editor = editorRef.current;if (!editor) return;const notePath = noteContext?.notePath ?? `root/${note.noteId}`;await copy(editor, notePath, note.title);- // Saved now, so that the link resolves in other notes at once.+ // Saved now, so that the link resolves at once.spacedUpdate.updateNowIfNecessary();}@@ -303,7 +308,13 @@ export default function EditableText({getEmbedBoxSize: getUploadBoxSize,openContentEmbedMenu,openBlockHandleMenu(event: MouseEvent, count: number) {- openBlockHandleMenu(event, count, () => void copyReference());+ const shareLink = getNoteShareLink(note);+ openBlockHandleMenu(event, count, {+ copyReference: () => void copyReference(),+ copyShareLink: shareLink+ ? () => void copyReference((editor) => copyBlockShareLink(editor, shareLink))+ : undefined+ });},copyBlockReference: () => copyReference(),copyTabReference: () => void copyReference(copyTabReference),diff --git a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Text/Block references.html b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Text/Block references.htmlindex b73d4fa808..f3541295e6 100644--- a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Text/Block references.html+++ b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Text/Block references.html@@ -22,6 +22,10 @@<p>The link shows the title of the note, followed by the beginning of thereferenced text. A link to blocks of the same note shows only the beginningof the referenced text.</p>+<p>If the note is <a href="#root/_help_R9pX4DGra2Vt">shared</a>, the menu+ of the block handle also offers <em>Copy public link to this block</em>.+ It copies the web address of the shared page with the reference added,+ to send to people who read the note outside Trilium.</p><p>The <em>Paste</em> submenu of the context menu offers two more ways to inserta copied reference:</p><ul>diff --git a/docs/User Guide/User Guide/Note Types/Text/Block references.md b/docs/User Guide/User Guide/Note Types/Text/Block references.mdindex 5c620fa77a..93266af284 100644--- a/docs/User Guide/User Guide/Note Types/Text/Block references.md+++ b/docs/User Guide/User Guide/Note Types/Text/Block references.md@@ -12,6 +12,8 @@ Inside a <a class="reference-link" href="Content%20tabs.md">Content tabs</a> bloThe link shows the title of the note, followed by the beginning of the referenced text. A link to blocks of the same note shows only the beginning of the referenced text.+If the note is [shared](../../Advanced%20Usage/Sharing.md), the menu of the block handle also offers _Copy public link to this block_. It copies the web address of the shared page with the reference added, to send to people who read the note outside Trilium.+The _Paste_ submenu of the context menu offers two more ways to insert a copied reference:* _Paste reference as a link_ inserts only the link, even when the reference was copied as plain text or along with other content.