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(share): show tabs blocks as tabs on shared pages
Elian Dorand20c14494e95
diff --git a/apps/client/src/widgets/type_widgets/text/ReadOnlyText.tsx b/apps/client/src/widgets/type_widgets/text/ReadOnlyText.tsxindex 82a3ed7b38..98e5c0a8c6 100644--- a/apps/client/src/widgets/type_widgets/text/ReadOnlyText.tsx+++ b/apps/client/src/widgets/type_widgets/text/ReadOnlyText.tsx@@ -4,6 +4,7 @@ import "./ReadOnlyText.css";// (see https://github.com/zadam/trilium/issues/1590 for example of such conflict)import "@triliumnext/ckeditor5";+import { applyTabs } from "@triliumnext/ckeditor5/src/plugins/tabs/tabs_read_only.js";import clsx from "clsx";import { Ref } from "preact";import { useEffect, useLayoutEffect, useMemo, useRef as usePreactRef } from "preact/hooks";@@ -13,6 +14,7 @@ import FNote from "../../../entities/fnote";import { consumeBlockReference } from "../../../services/block_reference";import { consumeBookmark } from "../../../services/bookmark_jump";import { applyInlineMermaid, rewriteMermaidDiagramsInContainer } from "../../../services/content_renderer_text";+import { t } from "../../../services/i18n";import { applyLinkEmbeds } from "../../../services/link_embed";import { renderMathInElement } from "../../../services/math";import { trackPendingRender } from "../../../services/pending_renders";@@ -25,7 +27,7 @@ import {} from "../../react/hooks";import { RawHtmlBlock } from "../../react/RawHtml";import { TypeWidgetProps } from "../type_widget";-import { applyReferenceLinks, applyTabs } from "./read_only_helper";+import { applyReferenceLinks } from "./read_only_helper";import {loadEmbeddedAttachment,loadEmbeddedNote,@@ -144,7 +146,7 @@ export function ReadOnlyTextContent({]));applyMath(container);- applyTabs(container);+ applyTabs(container, { placeholder: t("text-editor.ck.tab-title") });setupImageOpening(container, true);}, [ html, noteId, ntxId, contentRef ]);diff --git a/apps/client/src/widgets/type_widgets/text/read_only_helper.ts b/apps/client/src/widgets/type_widgets/text/read_only_helper.tsindex 19bc14af2f..b83f261021 100644--- a/apps/client/src/widgets/type_widgets/text/read_only_helper.ts+++ b/apps/client/src/widgets/type_widgets/text/read_only_helper.ts@@ -1,6 +1,4 @@-import { t } from "../../../services/i18n";import link from "../../../services/link";-import { randomString } from "../../../services/utils";/** Fills the reference links in `container`, which shows content of `hostNoteId` if given. */export async function applyReferenceLinks(@@ -17,91 +15,3 @@ export async function applyReferenceLinks(referenceLink.replaceChildren(spanEl);}}--/**- * Turns the tabs blocks in `container` into working tabs: the first tab of each block shows, and- * a click on a title, Enter or Space shows that tab. The arrow keys, Home and End move between- * the titles of a block. A title without text shows the editor's placeholder. A block that is- * already set up keeps its listeners and its active tab.- */-export function applyTabs(container: HTMLElement) {- for (const block of container.querySelectorAll<HTMLElement>(".trilium-tabs")) {- if (appliedTabs.has(block)) {- continue;- }- appliedTabs.add(block);-- const titles: HTMLElement[] = [];- for (const tab of block.querySelectorAll<HTMLElement>(":scope > .trilium-tab")) {- const title = tab.querySelector<HTMLElement>(":scope > .trilium-tab-title");- const panel = tab.querySelector<HTMLElement>(":scope > .trilium-tab-panel");- if (!title || !panel) {- continue;- }-- if (!title.textContent?.trim() && !title.querySelector(":not(br)")) {- const placeholder = t("text-editor.ck.tab-title");- title.replaceChildren();- title.dataset.placeholder = placeholder;- title.setAttribute("aria-label", placeholder);- }-- const id = `trilium-tab-${randomString(8)}`;- title.id = `${id}-title`;- title.tabIndex = 0;- title.setAttribute("role", "button");- title.setAttribute("aria-controls", `${id}-panel`);- panel.id = `${id}-panel`;- panel.setAttribute("role", "region");- panel.setAttribute("aria-labelledby", title.id);- titles.push(title);- }- if (!titles.length) {- continue;- }-- const activate = (activeTitle: HTMLElement) => {- for (const title of titles) {- const isActive = title === activeTitle;- title.parentElement?.classList.toggle("trilium-tab--active", isActive);- title.setAttribute("aria-expanded", String(isActive));- }- };- const focusAndActivate = (index: number) => {- const title = titles[(index + titles.length) % titles.length];- title.focus();- activate(title);- };-- for (const [index, title] of titles.entries()) {- title.addEventListener("click", () => activate(title));- title.addEventListener("keydown", (e) => {- const step = getComputedStyle(block).direction === "rtl" ? -1 : 1;- switch (e.key) {- case "Enter":- case " ":- activate(title);- break;- case "ArrowRight":- focusAndActivate(index + step);- break;- case "ArrowLeft":- focusAndActivate(index - step);- break;- case "Home":- focusAndActivate(0);- break;- case "End":- focusAndActivate(titles.length - 1);- break;- default:- return;- }- e.preventDefault();- });- }- activate(titles[0]);- }-}--const appliedTabs = new WeakSet<HTMLElement>();diff --git a/apps/server/src/assets/translations/en/server.json b/apps/server/src/assets/translations/en/server.jsonindex 77977ba5dd..25ebf20687 100644--- a/apps/server/src/assets/translations/en/server.json+++ b/apps/server/src/assets/translations/en/server.json@@ -456,7 +456,8 @@"toggle-navigation": "Toggle Navigation","toggle-toc": "Toggle Table of Contents","logo-alt": "Logo",- "login": "Login"+ "login": "Login",+ "tab-title": "Tab title"},"hidden_subtree_templates": {"text-snippet": "Text Snippet",diff --git a/apps/client/src/widgets/type_widgets/text/read_only_helper.spec.ts b/packages/ckeditor5/src/plugins/tabs/tabs_read_only.spec.tssimilarity index 95%rename from apps/client/src/widgets/type_widgets/text/read_only_helper.spec.tsrename to packages/ckeditor5/src/plugins/tabs/tabs_read_only.spec.tsindex cc99eea717..6aeae640af 100644--- a/apps/client/src/widgets/type_widgets/text/read_only_helper.spec.ts+++ b/packages/ckeditor5/src/plugins/tabs/tabs_read_only.spec.ts@@ -1,13 +1,13 @@-import { describe, expect, it, vi } from "vitest";+import { describe, expect, it } from "vitest";-import { applyTabs } from "./read_only_helper";+import { applyTabs } from "./tabs_read_only.js";-vi.mock("../../../services/i18n", () => ({ t: (key: string) => key }));+const PLACEHOLDER = "Tab title";function renderTabs(html: string) {const container = document.createElement("div");container.innerHTML = html;- applyTabs(container);+ applyTabs(container, { placeholder: PLACEHOLDER });return container;}@@ -95,7 +95,7 @@ describe("applyTabs", () => {expect(document.activeElement).toBe(titleOf(container, "A"));titleOf(container, "B").click();- applyTabs(container);+ applyTabs(container, { placeholder: PLACEHOLDER });expect(activeTitles(container)).toEqual(["B"]);press(titleOf(container, "B"), "ArrowRight");expect(activeTitles(container)).toEqual(["C"]);@@ -107,7 +107,7 @@ describe("applyTabs", () => {const container = renderTabs(`<div class="trilium-tabs">${tab(" ", "")}${tab("", "")}${tab("Named", "")}</div>`);- const label = "text-editor.ck.tab-title";+ const label = PLACEHOLDER;const titles = [...container.querySelectorAll<HTMLElement>(".trilium-tab-title")];expect(titles).toHaveLength(3);diff --git a/packages/ckeditor5/src/plugins/tabs/tabs_read_only.ts b/packages/ckeditor5/src/plugins/tabs/tabs_read_only.tsnew file mode 100644index 0000000000..605e086b27--- /dev/null+++ b/packages/ckeditor5/src/plugins/tabs/tabs_read_only.ts@@ -0,0 +1,97 @@+import { CLASSES } from "./constants.js";++export interface ApplyTabsOptions {+ /** The text a title without text shows, the editor's "Tab title" placeholder. */+ placeholder: string;+}++/**+ * Turns the saved tabs blocks in `container` into working tabs outside the editor: the first tab+ * of each block shows, and a click on a title, Enter or Space shows that tab. The arrow keys, Home+ * and End move between the titles of a block. A block that is already set up keeps its listeners+ * and its active tab.+ *+ * The module imports nothing from CKEditor, so pages that only display content can load it.+ */+export function applyTabs(container: ParentNode, { placeholder }: ApplyTabsOptions) {+ for (const block of container.querySelectorAll<HTMLElement>(`.${CLASSES.tabs}`)) {+ if (appliedTabs.has(block)) {+ continue;+ }+ appliedTabs.add(block);++ const titles: HTMLElement[] = [];+ for (const tab of block.querySelectorAll<HTMLElement>(`:scope > .${CLASSES.tab}`)) {+ const title = tab.querySelector<HTMLElement>(`:scope > .${CLASSES.tabTitle}`);+ const panel = tab.querySelector<HTMLElement>(`:scope > .${CLASSES.tabPanel}`);+ if (!title || !panel) {+ continue;+ }++ // CKEditor saves an empty title as ` `.+ if (!title.textContent?.trim() && !title.querySelector(":not(br)")) {+ title.replaceChildren();+ title.dataset.placeholder = placeholder;+ title.setAttribute("aria-label", placeholder);+ }++ const id = `trilium-tab-view-${++lastTabId}`;+ title.id = `${id}-title`;+ title.tabIndex = 0;+ title.setAttribute("role", "button");+ title.setAttribute("aria-controls", `${id}-panel`);+ panel.id = `${id}-panel`;+ panel.setAttribute("role", "region");+ panel.setAttribute("aria-labelledby", title.id);+ titles.push(title);+ }+ if (!titles.length) {+ continue;+ }++ const activate = (activeTitle: HTMLElement) => {+ for (const title of titles) {+ const isActive = title === activeTitle;+ title.parentElement?.classList.toggle(CLASSES.activeTab, isActive);+ title.setAttribute("aria-expanded", String(isActive));+ }+ };+ const focusAndActivate = (index: number) => {+ const title = titles[(index + titles.length) % titles.length];+ title.focus();+ activate(title);+ };++ for (const [index, title] of titles.entries()) {+ title.addEventListener("click", () => activate(title));+ title.addEventListener("keydown", (e) => {+ const step = getComputedStyle(block).direction === "rtl" ? -1 : 1;+ switch (e.key) {+ case "Enter":+ case " ":+ activate(title);+ break;+ case "ArrowRight":+ focusAndActivate(index + step);+ break;+ case "ArrowLeft":+ focusAndActivate(index - step);+ break;+ case "Home":+ focusAndActivate(0);+ break;+ case "End":+ focusAndActivate(titles.length - 1);+ break;+ default:+ return;+ }+ e.preventDefault();+ });+ }+ activate(titles[0]);+ }+}++const appliedTabs = new WeakSet<HTMLElement>();+let lastTabId = 0;diff --git a/packages/ckeditor5/src/theme/tabs.css b/packages/ckeditor5/src/theme/tabs.cssindex 37799bca06..2c8cedf404 100644--- a/packages/ckeditor5/src/theme/tabs.css+++ b/packages/ckeditor5/src/theme/tabs.css@@ -84,12 +84,12 @@.ck-content:not(.ck-editor__editable) .trilium-tabs > .trilium-tab > .trilium-tab-title {&:focus-visible {- outline: 2px solid var(--input-focus-outline-color, var(--ck-color-focus-border));+ outline: 2px solid var(--input-focus-outline-color, var(--ck-color-focus-border, currentColor));outline-offset: -2px;}&[data-placeholder]::before {content: attr(data-placeholder);- color: var(--ck-color-engine-placeholder-text);+ color: var(--ck-color-engine-placeholder-text, var(--_tabs-title-color));}}diff --git a/packages/share-theme/src/scripts/index.ts b/packages/share-theme/src/scripts/index.tsindex aee26fc793..2bdcfb577c 100644--- a/packages/share-theme/src/scripts/index.ts+++ b/packages/share-theme/src/scripts/index.ts@@ -11,6 +11,9 @@ import setupFaviconContrast from "./modules/favicon_contrast.js";import api from "./modules/api.js";import "highlight.js/styles/default.css";import "@triliumnext/ckeditor5/src/theme/ck-content.css";+import "@triliumnext/ckeditor5/src/theme/tabs.css";++import { applyTabs } from "@triliumnext/ckeditor5/src/plugins/tabs/tabs_read_only.js";function $try<T extends (...a: unknown[]) => unknown>(func: T, ...args: Parameters<T>) {try {@@ -34,6 +37,7 @@ function setupTextNote() {$try(setupMath);$try(setupVideoFacades);$try(setupFaviconContrast);+ $try(setupTabs);}document.addEventListener(@@ -63,6 +67,13 @@ document.addEventListener(false);+function setupTabs() {+ const content = document.getElementById("content");+ if (content) {+ applyTabs(content, { placeholder: content.dataset.tabTitlePlaceholder ?? "" });+ }+}+function determineNoteType() {const bodyClass = document.body.className;const match = bodyClass.match(/type-([^\s]+)/);diff --git a/packages/share-theme/src/styles/content.css b/packages/share-theme/src/styles/content.cssindex a781074022..6a29b6751f 100644--- a/packages/share-theme/src/styles/content.css+++ b/packages/share-theme/src/styles/content.css@@ -186,3 +186,8 @@ body.type-webView {font-size: .9em;text-align: center;}++.ck-content .trilium-tabs {+ --card-background-color: var(--background-secondary);+ --main-text-color: var(--text-primary);+}diff --git a/packages/share-theme/src/templates/page.ejs b/packages/share-theme/src/templates/page.ejsindex 6e1e019b86..b31326f9f4 100644--- a/packages/share-theme/src/templates/page.ejs+++ b/packages/share-theme/src/templates/page.ejs@@ -160,7 +160,7 @@ content = content.replaceAll(headingRe, (...match) => {</div><div id="right-pane"><div id="main">- <div id="content" class="type-<%= note.type %><% if (note.type === "text" || (note.type === "code" && note.mime === "text/x-markdown")) { %> ck-content<% } %><% if (isEmpty) { %> no-content<% } %>">+ <div id="content" class="type-<%= note.type %><% if (note.type === "text" || (note.type === "code" && note.mime === "text/x-markdown")) { %> ck-content<% } %><% if (isEmpty) { %> no-content<% } %>" data-tab-title-placeholder="<%= t("share_theme.tab-title") %>"><%- renderSnippets("content:start") %><h1 id="title"><%= note.title %></h1><% if (isEmpty && (!note.hasVisibleChildren() && note.type !== "book")) { %>