Skip to content

Build your personal knowledge base with Trilium Notes

feat(share): show a heading's link on hover and copy the section's address

Elian Doran019865767720
diff --git a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Advanced Usage/Sharing.html b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Advanced Usage/Sharing.html
index bf2e361874..c96a67b8ef 100644
--- a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Advanced Usage/Sharing.html
+++ b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Advanced Usage/Sharing.html
@@ -43,6 +43,9 @@ class="image">
<td>
<ul>
<li>Table of contents.</li>
+ <li>A link next to each heading, shown while the pointer is over the heading.
+ Clicking it goes to the section and copies the address of the section,
+ to share a link to it.</li>
<li>Syntax highlight of code blocks, in the language selected for each block
and in the colors of the VS Code light or dark theme, following the page's
mode. For “Auto-detected” blocks, the language is guessed among the ones
diff --git a/apps/server/src/assets/translations/en/server.json b/apps/server/src/assets/translations/en/server.json
index 5a74dde5e4..4767bd1b89 100644
--- a/apps/server/src/assets/translations/en/server.json
+++ b/apps/server/src/assets/translations/en/server.json
@@ -458,7 +458,8 @@
"toggle-toc": "Toggle Table of Contents",
"logo-alt": "Logo",
"login": "Login",
- "tab-title": "Tab title"
+ "tab-title": "Tab title",
+ "heading-link": "Link to This Section"
},
"hidden_subtree_templates": {
"text-snippet": "Text Snippet",
diff --git a/docs/User Guide/User Guide/Advanced Usage/Sharing.md b/docs/User Guide/User Guide/Advanced Usage/Sharing.md
index 8c2739a5fe..58aab17640 100644
--- a/docs/User Guide/User Guide/Advanced Usage/Sharing.md
+++ b/docs/User Guide/User Guide/Advanced Usage/Sharing.md
@@ -33,7 +33,7 @@ Trilium allows you to share selected notes as **publicly accessible** read-only
<tbody>
<tr>
<th><a class="reference-link" href="../Note%20Types/Text.md">Text</a></th>
- <td><ul><li>Table of contents.</li><li>Syntax highlight of code blocks, in the language selected for each block and in the colors of the VS Code light or dark theme, following the page's mode. For “Auto-detected” blocks, the language is guessed among the ones enabled in <a class="reference-link" href="../Basic%20Concepts%20and%20Features/UI%20Elements/Options.md">Options</a> → <em>Code Notes</em>; a language not enabled there is not highlighted.</li><li>Rendering for math equations.</li><li><a href="../Note%20Types/Text/Include%20Note.md">Including notes</a> (only if the included notes are also shared).</li><li>Mermaid diagrams in code blocks, drawn in the page's light or dark mode and redrawn when the visitor switches it.</li></ul></td>
+ <td><ul><li>Table of contents.</li><li>A link next to each heading, shown while the pointer is over the heading. Clicking it goes to the section and copies the address of the section, to share a link to it.</li><li>Syntax highlight of code blocks, in the language selected for each block and in the colors of the VS Code light or dark theme, following the page's mode. For “Auto-detected” blocks, the language is guessed among the ones enabled in <a class="reference-link" href="../Basic%20Concepts%20and%20Features/UI%20Elements/Options.md">Options</a> → <em>Code Notes</em>; a language not enabled there is not highlighted.</li><li>Rendering for math equations.</li><li><a href="../Note%20Types/Text/Include%20Note.md">Including notes</a> (only if the included notes are also shared).</li><li>Mermaid diagrams in code blocks, drawn in the page's light or dark mode and redrawn when the visitor switches it.</li></ul></td>
<td>&nbsp;</td>
</tr>
<tr>
diff --git a/packages/share-theme/src/content/content.css b/packages/share-theme/src/content/content.css
index 8a75cfce60..01a174bc53 100644
--- a/packages/share-theme/src/content/content.css
+++ b/packages/share-theme/src/content/content.css
@@ -64,8 +64,8 @@ iframe.pdf-view {
border-bottom: 1px solid var(--background-highlight);
}
-/* The links of the app's default theme, `theme-next/forms.css`; link previews have their own. */
-.ck-content a:where(:not(.link-embed-mention, .link-embed-card)) {
+/* The links of the app's default theme, `theme-next/forms.css`; link previews and heading links have their own. */
+.ck-content a:where(:not(.link-embed-mention, .link-embed-card, .toc-anchor)) {
--background: transparent;
box-shadow: 0 0 0 0 var(--background);
@@ -80,12 +80,12 @@ iframe.pdf-view {
color 300ms ease-out;
}
-.ck-content a:where(:not(.link-embed-mention, .link-embed-card)):focus-visible {
+.ck-content a:where(:not(.link-embed-mention, .link-embed-card, .toc-anchor)):focus-visible {
outline: 2px solid var(--link-focus-outline-color);
outline-offset: 2px;
}
-.ck-content a:where(:not(.link-embed-mention, .link-embed-card)):hover {
+.ck-content a:where(:not(.link-embed-mention, .link-embed-card, .toc-anchor)):hover {
--background: var(--link-hover-background);
box-shadow: 0 0 0 4px var(--link-hover-background);
diff --git a/packages/share-theme/src/page/toc.css b/packages/share-theme/src/page/toc.css
index 8a99e1ff89..20899d4187 100644
--- a/packages/share-theme/src/page/toc.css
+++ b/packages/share-theme/src/page/toc.css
@@ -92,13 +92,30 @@
background: var(--background-highlight);
}
-#content h1 a.toc-anchor,
-#content h2 a.toc-anchor,
-#content h3 a.toc-anchor,
-#content h4 a.toc-anchor,
-#content h5 a.toc-anchor,
-#content h6 a.toc-anchor {
- margin-left: 10px;
+#content :is(h1, h2, h3, h4, h5, h6) {
+ scroll-margin-top: 16px;
+}
+
+#content .toc-anchor {
+ margin-inline-start: 0.3em;
+ font-size: 0.6em;
+ vertical-align: middle;
+ color: var(--text-menu);
+ text-decoration: none;
+ opacity: 0;
+ transition: opacity 150ms ease;
+}
+
+#content :is(h1, h2, h3, h4, h5, h6):hover > .toc-anchor,
+#content .toc-anchor:focus-visible,
+#content .toc-anchor.copied {
+ opacity: 1;
+}
+
+@media (hover: none) {
+ #content .toc-anchor {
+ opacity: 0.5;
+ }
}
@media (max-width: 48em) {
diff --git a/packages/share-theme/src/page/toc.spec.ts b/packages/share-theme/src/page/toc.spec.ts
index 68d4e507a6..47723d90d3 100644
--- a/packages/share-theme/src/page/toc.spec.ts
+++ b/packages/share-theme/src/page/toc.spec.ts
@@ -7,6 +7,8 @@ describe("setupToC", () => {
afterEach(() => {
document.body.innerHTML = "";
vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+ vi.useRealTimers();
});
it("marks the entry of the last heading scrolled past, whatever the heading levels", () => {
@@ -54,6 +56,59 @@ describe("setupToC", () => {
}
expect(activeEntry()).toBeUndefined();
});
+
+ it("copies the address of a heading's section, showing a check mark for a moment", async () => {
+ vi.useFakeTimers();
+ const writeText = vi.fn().mockResolvedValue(undefined);
+ vi.stubGlobal("navigator", { clipboard: { writeText } });
+ renderPage([ [ 2, "intro", 100 ] ]);
+ const link = headingLink("intro");
+ const icon = () => link.querySelector(".tn-icon")?.className;
+
+ link.click();
+ await vi.waitFor(() => expect(icon()).toBe("tn-icon bx bx-check"));
+ expect(writeText).toHaveBeenCalledWith(new URL("#intro", location.href).href);
+ expect(link.classList.contains("copied")).toBe(true);
+
+ vi.advanceTimersByTime(1000);
+ link.click();
+ await Promise.resolve();
+ vi.advanceTimersByTime(1000);
+ expect(icon()).toBe("tn-icon bx bx-check");
+
+ vi.advanceTimersByTime(500);
+ expect(icon()).toBe("tn-icon bx bx-link");
+ expect(link.classList.contains("copied")).toBe(false);
+ });
+
+ it("only jumps to the section when the address cannot be copied", async () => {
+ const writeText = vi.fn().mockRejectedValue(new Error("denied"));
+ vi.stubGlobal("navigator", { clipboard: { writeText } });
+ renderPage([ [ 2, "intro", 100 ] ]);
+ const link = headingLink("intro");
+
+ const click = new MouseEvent("click", { bubbles: true, cancelable: true });
+ link.dispatchEvent(click);
+ await vi.waitFor(() => expect(writeText).toHaveBeenCalledOnce());
+ await Promise.resolve();
+ expect(click.defaultPrevented).toBe(false);
+ expect(link.classList.contains("copied")).toBe(false);
+
+ vi.stubGlobal("navigator", {});
+ expect(() => link.click()).not.toThrow();
+ });
+
+ it("sets the heading links up on a page without a table of contents", async () => {
+ const writeText = vi.fn().mockResolvedValue(undefined);
+ vi.stubGlobal("navigator", { clipboard: { writeText } });
+ document.body.innerHTML = `<div id="content"><h2 id="only">Only${anchor("only")}</h2></div>`;
+ setupToC();
+
+ const link = headingLink("only");
+ link.querySelector(".tn-icon")?.remove();
+ link.click();
+ await vi.waitFor(() => expect(link.classList.contains("copied")).toBe(true));
+ });
});
/**
@@ -64,8 +119,8 @@ function renderPage(headings: [ level: number, slug: string, offsetTop: number ]
document.body.innerHTML = `
<div id="right-pane">
<div id="content">
- ${headings.map(([ level, slug ]) => `<h${level}>${slug}`
- + `<a id="${slug}" class="toc-anchor" href="#${slug}">#</a></h${level}>`).join("")}
+ ${headings.map(([ level, slug ]) => `<h${level} id="${slug}">${slug}${anchor(slug)}`
+ + `</h${level}>`).join("")}
</div>
<ul id="toc">
${headings.map(([ , slug ]) => `<li><a href="#${slug}">${slug}</a></li>`).join("")}
@@ -73,7 +128,7 @@ function renderPage(headings: [ level: number, slug: string, offsetTop: number ]
</div>
`;
for (const [ , slug, offsetTop ] of headings) {
- const heading = document.getElementById(slug)?.parentElement;
+ const heading = document.getElementById(slug);
if (heading) {
Object.defineProperty(heading, "offsetTop", { value: offsetTop });
}
@@ -90,3 +145,17 @@ function renderPage(headings: [ level: number, slug: string, offsetTop: number ]
function activeEntry() {
return document.querySelector("#toc a.active")?.textContent;
}
+
+/** The link core's `preparePageContent()` gives a heading. */
+function anchor(slug: string) {
+ return `<a class="toc-anchor" href="#${slug}" aria-label="Link to This Section">`
+ + `<span class="tn-icon bx bx-link" aria-hidden="true"></span></a>`;
+}
+
+function headingLink(slug: string) {
+ const link = document.querySelector<HTMLAnchorElement>(`#content a.toc-anchor[href="#${slug}"]`);
+ if (!link) {
+ throw new Error(`The link of ${slug} is missing.`);
+ }
+ return link;
+}
diff --git a/packages/share-theme/src/page/toc.ts b/packages/share-theme/src/page/toc.ts
index c4e6950b73..4f58d4e91f 100644
--- a/packages/share-theme/src/page/toc.ts
+++ b/packages/share-theme/src/page/toc.ts
@@ -14,6 +14,8 @@ import "./toc.css";
* entry as the user scrolls.
*/
export default function setupToC() {
+ setupHeadingLinks();
+
const container = document.getElementById("right-pane");
const toc = document.getElementById("toc");
if (!toc || !container) return;
@@ -51,3 +53,30 @@ export default function setupToC() {
changeLinkState();
container.addEventListener("scroll", changeLinkState);
}
+
+/** How long a heading link shows its check mark after copying, in milliseconds. */
+const COPIED_DURATION = 1500;
+
+/**
+ * Makes the link of each heading copy the address of its section when clicked, besides jumping to
+ * it, and show a check mark for a moment. Without clipboard access, a click only jumps.
+ */
+function setupHeadingLinks() {
+ for (const link of document.querySelectorAll<HTMLAnchorElement>("#content .toc-anchor")) {
+ let resetTimer: ReturnType<typeof setTimeout> | undefined;
+ const setCopied = (copied: boolean) => {
+ link.classList.toggle("copied", copied);
+ const icon = link.querySelector(".tn-icon");
+ icon?.classList.toggle("bx-link", !copied);
+ icon?.classList.toggle("bx-check", copied);
+ };
+
+ link.addEventListener("click", () => {
+ navigator.clipboard?.writeText(link.href).then(() => {
+ setCopied(true);
+ clearTimeout(resetTimer);
+ resetTimer = setTimeout(() => setCopied(false), COPIED_DURATION);
+ }, () => undefined);
+ });
+ }
+}
diff --git a/packages/trilium-core/src/share/content_renderer.spec.ts b/packages/trilium-core/src/share/content_renderer.spec.ts
index 50b24730e9..c9cbb633a0 100644
--- a/packages/trilium-core/src/share/content_renderer.spec.ts
+++ b/packages/trilium-core/src/share/content_renderer.spec.ts
@@ -317,8 +317,8 @@ describe("content_renderer", () => {
const page = renderNoteContent(shareRootNote.getChildNotes()[0]);
- expect(page).toContain(`<h3 data-trilium-block-id="b1">Referenced`
- + `<a id="referenced" class="toc-anchor"`);
+ expect(page).toContain(`<h3 data-trilium-block-id="b1" id="referenced">Referenced`
+ + `<a class="toc-anchor"`);
expect(page).toContain(`href="#referenced"`);
const toc = parse(String(page)).querySelector("#toc");
@@ -358,7 +358,7 @@ describe("content_renderer", () => {
const page = parse(String(renderNoteContent(shareRootNote.getChildNotes()[0])));
- expect(page.querySelector("#content h2:last-of-type .toc-anchor")?.id)
+ expect(page.querySelector("#content h2:last-of-type")?.id)
.toBe("spans-two-lines");
expect(page.querySelectorAll("#toc a").map((link) => [
link.getAttribute("href"), link.text.trim()
@@ -1115,8 +1115,9 @@ describe("content_renderer", () => {
{ level: 2, text: "Intro", slug: "intro-1" }
]);
expect(content).toContain(
- `<h2 class="x">Q&amp;A <strong>now</strong>`
- + `<a id="q-amp-a-now" class="toc-anchor" name="q-amp-a-now" href="#q-amp-a-now">#</a></h2>`);
+ `<h2 class="x" id="q-amp-a-now">Q&amp;A <strong>now</strong>`
+ + `<a class="toc-anchor" href="#q-amp-a-now" aria-label="Link &quot;here&quot;">`
+ + `<span class="tn-icon bx bx-link" aria-hidden="true"></span></a></h2>`);
expect(content).toContain(`<p>Text</p>`);
expect(parse(content).querySelectorAll(".toc-anchor")).toHaveLength(4);
});
@@ -1141,7 +1142,7 @@ describe("content_renderer", () => {
});
function prepare(html: string) {
- return preparePageContent(html, { imageAlt: "Image" });
+ return preparePageContent(html, { imageAlt: "Image", headingLinkLabel: `Link "here"` });
}
});
diff --git a/packages/trilium-core/src/share/content_renderer.ts b/packages/trilium-core/src/share/content_renderer.ts
index 490724f511..0a36adfdd1 100644
--- a/packages/trilium-core/src/share/content_renderer.ts
+++ b/packages/trilium-core/src/share/content_renderer.ts
@@ -275,7 +275,10 @@ function renderNoteContentInternal(note: SNote | BNote, renderArgs: RenderArgs)
// anchors and image attributes, which templates derived from an earlier `page.ejs` add
// themselves.
const { content: pageContent, headings } = typeof content === "string"
- ? preparePageContent(content, { imageAlt: t("share_theme.image_alt") })
+ ? preparePageContent(content, {
+ imageAlt: t("share_theme.image_alt"),
+ headingLinkLabel: t("share_theme.heading-link")
+ })
: { content, headings: [] };
const pageOpts = { ...opts, content: pageContent, headings, toc: getTableOfContents(headings) };
return ejs.render(readShareTemplate("page"), pageOpts, {
@@ -284,12 +287,15 @@ function renderNoteContentInternal(note: SNote | BNote, renderArgs: RenderArgs)
}
/**
- * Prepares the content of a share page for the default template. Every heading gets a `#` link to
- * itself, with an ID made from its text that is unique on the page, and the headings are returned
- * in document order. An image without `alt` gets `imageAlt`, and one without `loading` loads
- * lazily. HTML without headings or images comes back as it is.
+ * Prepares the content of a share page for the default template. Every heading gets an ID made from
+ * its text that is unique on the page, and a link to itself labeled `headingLinkLabel`; the
+ * headings are returned in document order. An image without `alt` gets `imageAlt`, and one without
+ * `loading` loads lazily. HTML without headings or images comes back as it is.
*/
-export function preparePageContent(html: string, options: { imageAlt: string }) {
+export function preparePageContent(
+ html: string,
+ options: { imageAlt: string; headingLinkLabel: string }
+) {
if (!/<(h[1-6]|img)[\s>]/i.test(html)) {
return { content: html, headings: [] as PageHeading[] };
}
@@ -310,8 +316,10 @@ export function preparePageContent(html: string, options: { imageAlt: string })
const slug = slugs[index];
const text = element.text.replace(/\s+/g, " ").trim();
const heading = { level: Number(element.tagName.slice(1)), text, slug };
- element.insertAdjacentHTML("beforeend",
- `<a id="${slug}" class="toc-anchor" name="${slug}" href="#${slug}">#</a>`);
+ element.setAttribute("id", slug);
+ element.insertAdjacentHTML("beforeend", `<a class="toc-anchor" href="#${slug}"`
+ + ` aria-label="${escapeHtml(options.headingLinkLabel)}">`
+ + `<span class="tn-icon bx bx-link" aria-hidden="true"></span></a>`);
return heading;
});
return { content: document.toString(), headings };