Skip to content

Build your personal knowledge base with Trilium Notes

client/text editor/tabs: implement a single-row scrollable tab bar

Adorian Doran08157872e201
diff --git a/apps/client/src/services/bookmark_jump.spec.ts b/apps/client/src/services/bookmark_jump.spec.ts
index 3152bd852e..5718a9e1a8 100644
--- a/apps/client/src/services/bookmark_jump.spec.ts
+++ b/apps/client/src/services/bookmark_jump.spec.ts
@@ -42,11 +42,11 @@ describe("consumeBookmark", () => {
`<section class="trilium-tab"><p class="trilium-tab-title">B</p><div class="trilium-tab-panel"><p><a id="in-tab"></a>target</p></div></section>` +
`</div>`
);
- applyTabs(container, { placeholder: "" });
+ applyTabs(container, { placeholder: "", scrollLabels: { start: "", end: "" } });
consumeBookmark(container, { bookmark: "in-tab" });
- expect(container.querySelector(".trilium-tab--active > .trilium-tab-title")?.textContent).toBe("B");
+ expect(container.querySelector(".trilium-tab-title--active")?.textContent).toBe("B");
});
it("leaves the bookmark unconsumed when the content container is not rendered yet", () => {
diff --git a/apps/client/src/services/collapsible.spec.ts b/apps/client/src/services/collapsible.spec.ts
index b8abaf1a99..01a1463615 100644
--- a/apps/client/src/services/collapsible.spec.ts
+++ b/apps/client/src/services/collapsible.spec.ts
@@ -78,13 +78,13 @@ describe("revealElement", () => {
`<details><summary>s</summary><span class="m">hit</span></details>` +
`</div></section>` +
`</div>`;
- applyTabs(container, { placeholder: "" });
+ applyTabs(container, { placeholder: "", scrollLabels: { start: "", end: "" } });
const match = container.querySelector(".m");
expect(match).not.toBeNull();
revealElement(match as Element);
expect(container.querySelector("details")?.open).toBe(true);
- expect(container.querySelector(".trilium-tab--active > .trilium-tab-title")?.textContent).toBe("B");
+ expect(container.querySelector(".trilium-tab-title--active")?.textContent).toBe("B");
});
});
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.json
index 97b09bfa3b..89f4229456 100644
--- a/apps/client/src/translations/en/translation.json
+++ b/apps/client/src/translations/en/translation.json
@@ -4547,7 +4547,9 @@
"make-the-tab-the-first-one": "Make the tab the first one",
"make-the-tab-the-last-one": "Make the tab the last one",
"add-a-tab-after-the-current-one": "Add a tab after the current one",
- "add-a-tab-before-the-current-one": "Add a tab before the current one"
+ "add-a-tab-before-the-current-one": "Add a tab before the current one",
+ "scroll-to-the-previous-tabs": "Scroll to the previous tabs",
+ "scroll-to-the-next-tabs": "Scroll to the next tabs"
},
"task-state-dropped-title": "Invalid task states",
"task-state-dropped-message_one": "A custom task state definition is invalid and was ignored.",
diff --git a/apps/client/src/widgets/find_in_html.spec.ts b/apps/client/src/widgets/find_in_html.spec.ts
index 01fc4425cd..4a9d2f5990 100644
--- a/apps/client/src/widgets/find_in_html.spec.ts
+++ b/apps/client/src/widgets/find_in_html.spec.ts
@@ -100,8 +100,8 @@ describe("FindInHtml", () => {
"<div class=\"trilium-tab-panel\"><p>needle</p></div></section>" +
"</div>"
);
- applyTabs(container, { placeholder: "" });
- const activeTitle = () => container.querySelector(".trilium-tab--active > .trilium-tab-title")?.textContent;
+ applyTabs(container, { placeholder: "", scrollLabels: { start: "", end: "" } });
+ const activeTitle = () => container.querySelector(".trilium-tab-title--active")?.textContent;
expect(activeTitle()).toBe("A");
const result = await finder.performFind("needle", false, false);
diff --git a/apps/client/src/widgets/type_widgets/markdown/Markdown.spec.ts b/apps/client/src/widgets/type_widgets/markdown/Markdown.spec.ts
index c3eed681a2..6a4e1c7e9c 100644
--- a/apps/client/src/widgets/type_widgets/markdown/Markdown.spec.ts
+++ b/apps/client/src/widgets/type_widgets/markdown/Markdown.spec.ts
@@ -5,7 +5,7 @@
import { applyTabs } from "@triliumnext/ckeditor5/src/plugins/tabs/tabs_read_only.js";
import type VanillaCodeMirror from "@triliumnext/codemirror";
import { HIGHLIGHT_STYLE } from "@triliumnext/commons";
-import { describe, expect, it, vi } from "vitest";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { findActiveBlock, renderWithSourceLines, revealTabAtLine, scrollToSourceLine } from "./Markdown.js";
@@ -395,6 +395,17 @@ describe("scrollToSourceLine", () => {
});
describe("revealTabAtLine", () => {
+ // `applyTabs()` watches the title bars it builds, and jsdom has no `ResizeObserver`.
+ beforeEach(() => {
+ vi.stubGlobal("ResizeObserver", class {
+ observe() {}
+ disconnect() {}
+ });
+ });
+ afterEach(() => {
+ vi.unstubAllGlobals();
+ });
+
const src = [
"=== \"A\"", // 1
"", // 2
@@ -416,12 +427,12 @@ describe("revealTabAtLine", () => {
function preview() {
const el = document.createElement("div");
el.innerHTML = renderWithSourceLines(src).html;
- applyTabs(el, { placeholder: "" });
+ applyTabs(el, { placeholder: "", scrollLabels: { start: "", end: "" } });
return el;
}
function activeTitles(el: HTMLElement) {
- return [ ...el.querySelectorAll(".trilium-tab--active > .trilium-tab-title") ].map((title) => title.textContent);
+ return [ ...el.querySelectorAll(".trilium-tab-title--active") ].map((title) => title.textContent);
}
it("tags each tab with the line of its header", () => {
diff --git a/apps/client/src/widgets/type_widgets/text/ReadOnlyText.spec.tsx b/apps/client/src/widgets/type_widgets/text/ReadOnlyText.spec.tsx
index 9a3d07697e..27cdd4e932 100644
--- a/apps/client/src/widgets/type_widgets/text/ReadOnlyText.spec.tsx
+++ b/apps/client/src/widgets/type_widgets/text/ReadOnlyText.spec.tsx
@@ -485,8 +485,8 @@ describe("ReadOnlyText tabs", () => {
second.click();
label?.querySelector("b")?.click();
- expect(first.parentElement?.classList.contains("trilium-tab--active")).toBe(true);
- expect(second.parentElement?.classList.contains("trilium-tab--active")).toBe(false);
+ expect(first.classList.contains("trilium-tab-title--active")).toBe(true);
+ expect(second.classList.contains("trilium-tab-title--active")).toBe(false);
await act(async () => render(null, harness.container));
harness.container.remove();
diff --git a/apps/client/src/widgets/type_widgets/text/ReadOnlyText.tsx b/apps/client/src/widgets/type_widgets/text/ReadOnlyText.tsx
index 5eb24e7b8f..5fea17eab2 100644
--- a/apps/client/src/widgets/type_widgets/text/ReadOnlyText.tsx
+++ b/apps/client/src/widgets/type_widgets/text/ReadOnlyText.tsx
@@ -156,7 +156,13 @@ export function ReadOnlyTextContent({
const disposeTableScroll = applyTableScroll(container);
const disposeStickyTableHeaders = applyStickyTableHeaders(container);
applyMath(container);
- applyTabs(container, { placeholder: t("text-editor.ck.tab-title") });
+ const disposeTabs = applyTabs(container, {
+ placeholder: t("text-editor.ck.tab-title"),
+ scrollLabels: {
+ start: t("text-editor.ck.scroll-to-the-previous-tabs"),
+ end: t("text-editor.ck.scroll-to-the-next-tabs")
+ }
+ });
const tabTitles = container.querySelectorAll<HTMLElement>(`.${TAB_CLASSES.tabTitle}`);
const disposeTabTitles = [ ...tabTitles ]
.filter((title) => title.hasChildNodes())
@@ -166,6 +172,7 @@ export function ReadOnlyTextContent({
return () => {
disposeTableScroll();
disposeStickyTableHeaders();
+ disposeTabs();
for (const dispose of disposeTabTitles) {
dispose();
}
diff --git a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/AI.html b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/AI.html
index 0f6021225b..a62d42a39d 100644
--- a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/AI.html
+++ b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/AI.html
@@ -66,13 +66,14 @@
class="trilium-tab-panel">
<p>Reuses an existing subscription instead of paying per use.</p>
<ul>
- <li><span class="tn-icon tn-brand tn-brand-claude"></span><a href="#root/_help_eFhxp9laTW1S?block=V6c5Z5HsjXbJ">&nbsp;Claude Code</a>
+ <li><span class="tn-icon tn-brand tn-brand-claude"></span>&nbsp;<a href="#root/_help_eFhxp9laTW1S">Claude Code</a>
</li>
- <li><span class="tn-icon tn-brand tn-brand-github-copilot"></span><a href="#root/_help_eFhxp9laTW1S?block=4RpEMVIcoT0B">&nbsp;GitHub Copilot</a>
+ <li><span class="tn-icon tn-brand tn-brand-github-copilot"></span>&nbsp;<a
+ href="#root/_help_eFhxp9laTW1S">GitHub Copilot</a>
</li>
- <li><span class="tn-icon tn-brand tn-brand-antigravity"></span><a href="#root/_help_eFhxp9laTW1S?block=QLvuXcOTVnsI">&nbsp;Google Antigravity</a>
+ <li><span class="tn-icon tn-brand tn-brand-antigravity"></span>&nbsp;<a href="#root/_help_eFhxp9laTW1S">Google Antigravity</a>
</li>
- <li><span class="tn-icon tn-brand tn-brand-codex"></span><a href="#root/_help_eFhxp9laTW1S?block=DG1hFjD2ztD3">&nbsp;OpenAI Codex</a>
+ <li><span class="tn-icon tn-brand tn-brand-codex"></span>&nbsp;<a href="#root/_help_eFhxp9laTW1S">OpenAI Codex</a>
</li>
</ul>
</div>
diff --git a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/AI/Privacy.html b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/AI/Privacy.html
index 8f05de5592..edf6fd08dc 100644
--- a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/AI/Privacy.html
+++ b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/AI/Privacy.html
@@ -45,14 +45,14 @@
</aside>
<h2>What is actually sent</h2>
<ul>
- <li class="ck-list-marker-bold"><strong>Always, with every message</strong>
+ <li><strong>Always, with every message</strong>
<ul>
<li>The conversation itself: your messages and the assistant's replies, including
earlier turns</li>
<li>Trilium's system prompt describing how to format answers and use tools.</li>
</ul>
</li>
- <li class="ck-list-marker-bold"><strong>The current note, only when note context is enabled.</strong>
+ <li><strong>The current note, only when note context is enabled.</strong>
<ul>
<li>In the sidebar chat this is the file icon at the bottom; the dedicated
chat note type never sends a current note.</li>
@@ -63,7 +63,7 @@
the model must call a tool to read further.</li>
</ul>
</li>
- <li class="ck-list-marker-bold"><strong>Any note the model asks for, when note access is enabled.</strong>
+ <li><strong>Any note the model asks for, when note access is enabled.</strong>
<ul>
<li>Tools let the model search your tree and read notes, attributes and attachments
beyond the current one.</li>
diff --git a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/AI/Providers/Subscription-based providers.html b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/AI/Providers/Subscription-based providers.html
index d7ca18aef7..a5ebb5911d 100644
--- a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/AI/Providers/Subscription-based providers.html
+++ b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/AI/Providers/Subscription-based providers.html
@@ -8,8 +8,7 @@
mode.</p>
<p>See also the dedicated&nbsp;<a class="reference-link" href="#root/_help_cRRrdZjgyhNc">Privacy</a>&nbsp;section
to better understand what data is being sent to a cloud provider.</p>
-<h2
-data-trilium-block-id="V6c5Z5HsjXbJ"><span class="tn-icon tn-brand tn-brand-claude"></span>&nbsp;Claude Code</h2>
+<h2><span class="tn-icon tn-brand tn-brand-claude"></span>&nbsp;Claude Code</h2>
<p>To use a subscription:</p>
<ol>
<li>First, Claude Code needs to be installed on the machine that runs Trilium.
@@ -45,7 +44,7 @@ data-trilium-block-id="V6c5Z5HsjXbJ"><span class="tn-icon tn-brand tn-brand-clau
doesn't match the one expected by Trilium. Generally it's best to keep
both Claude Code and Trilium updated to the latest version.</p>
</aside>
-<h2 data-trilium-block-id="4RpEMVIcoT0B"><span class="tn-icon tn-brand tn-brand-github-copilot"></span>&nbsp;GitHub Copilot</h2>
+<h2><span class="tn-icon tn-brand tn-brand-github-copilot"></span>&nbsp;GitHub Copilot</h2>
<aside class="admonition note">
<p>This subscription-based provider is still in beta. It is safe to use (won't
use additional funds and respects the terms of use), but you might experience
@@ -85,7 +84,7 @@ data-trilium-block-id="V6c5Z5HsjXbJ"><span class="tn-icon tn-brand tn-brand-clau
href="#root/_help_TiQbQDgP8L5t">Text Extraction (OCR)</a>&nbsp;when the
note tools are enabled.</li>
</ul>
-<h2 data-trilium-block-id="QLvuXcOTVnsI"><span class="tn-icon tn-brand tn-brand-antigravity"></span>&nbsp;Google Antigravity</h2>
+<h2><span class="tn-icon tn-brand tn-brand-antigravity"></span>&nbsp;Google Antigravity</h2>
<aside class="admonition note">
<p>This subscription-based provider is still in beta. It is safe to use (won't
use additional funds and respects the terms of use), but you might experience
@@ -154,11 +153,13 @@ data-trilium-block-id="V6c5Z5HsjXbJ"><span class="tn-icon tn-brand tn-brand-clau
to test it out is to use the <code>nix shell</code> with flakes:</p><pre><code class="language-text-x-trilium-auto">NIXPKGS_ALLOW_UNFREE=1 nix shell --impure github:nixos/nixpkgs/nixos-unstable#antigravity-acp
trilium</code></pre>
</li>
- <li>Go to&nbsp;<a class="reference-link" href="#root/_help_4TIF1oA4VQRO">Options</a>&nbsp;→
- AI / LLM and add the&nbsp;<span class="tn-icon tn-brand tn-brand-antigravity"></span> <em>Google Antigravity</em> provider.
- When the list of models is loaded for the first time, the Google sign-in
- page opens in a browser on the machine running Trilium; finish signing
- in there.</li>
+ <li>
+ <p>Go to&nbsp;<a class="reference-link" href="#root/_help_4TIF1oA4VQRO">Options</a>&nbsp;→
+ AI / LLM and add the&nbsp;<span class="tn-icon tn-brand tn-brand-antigravity"></span> <em>Google Antigravity</em> provider.
+ When the list of models is loaded for the first time, the Google sign-in
+ page opens in a browser on the machine running Trilium; finish signing
+ in there.</p>
+ </li>
</ol>
</div>
</section>
@@ -183,7 +184,7 @@ trilium</code></pre>
<li>The results of tool calls (e.g. reading a note, writing attributes) are
not properly displayed because they are not exposed by the ACP server.</li>
</ul>
-<h2 data-trilium-block-id="DG1hFjD2ztD3"><span class="tn-icon tn-brand tn-brand-codex"></span>&nbsp;OpenAI Codex</h2>
+<h2><span class="tn-icon tn-brand tn-brand-codex"></span>&nbsp;OpenAI Codex</h2>
<aside class="admonition note">
<p>This subscription-based provider is still in beta. It is safe to use (won't
use additional funds and respects the terms of use), but you might experience
@@ -221,11 +222,13 @@ trilium</code></pre>
can be taken from <code>nixos-unstable</code>:</p><pre><code class="language-text-x-sh">nix shell github:nixos/nixpkgs/nixos-unstable#codex
trilium</code></pre>
</li>
- <li>Go to&nbsp;<a class="reference-link" href="#root/_help_4TIF1oA4VQRO">Options</a>&nbsp;→ <em>AI / LLM</em> and
- add the&nbsp;<span class="tn-icon tn-brand tn-brand-codex"></span> <em>OpenAI Codex</em> provider.
- When the list of models is loaded for the first time, the ChatGPT sign-in
- page opens in a browser on the machine running Trilium; finish signing
- in there.</li>
+ <li>
+ <p>Go to&nbsp;<a class="reference-link" href="#root/_help_4TIF1oA4VQRO">Options</a>&nbsp;→ <em>AI / LLM</em> and
+ add the&nbsp;<span class="tn-icon tn-brand tn-brand-codex"></span> <em>OpenAI Codex</em> provider.
+ When the list of models is loaded for the first time, the ChatGPT sign-in
+ page opens in a browser on the machine running Trilium; finish signing
+ in there.</p>
+ </li>
</ol>
</div>
</section>
diff --git a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Text/Content tabs.html b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Text/Content tabs.html
index 812c856a93..c46a432cc9 100644
--- a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Text/Content tabs.html
+++ b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Text/Content tabs.html
@@ -4,9 +4,9 @@
in several programming languages).</p>
<p>A tabs block consists of:</p>
<ul>
- <li><strong>A row of tab titles</strong>, above the panel or, when the tabs
- are aligned at the bottom, below it. The title of the panel that is showing
- is highlighted.</li>
+ <li><strong>A single row of tab titles</strong>, above the panel or, when
+ the tabs are aligned at the bottom, below it. The title of the panel that
+ is showing is highlighted.</li>
<li><strong>The panel of the active tab.</strong> A panel can hold any kind
of content (including nested tabs blocks).</li>
</ul>
@@ -19,6 +19,19 @@
<p>A new block contains two tabs, named “Tab 1” and “Tab 2”. Any content
that was selected prior to inserting the tabs will be moved into the first
tab. The title of the first tab is selected, so typing replaces it.</p>
+<h2>Scrolling through the titles</h2>
+<p>When the titles of a block do not fit on their row, a <span class="tn-icon bx bx-chevron-left"></span> button
+ and a <span class="tn-icon bx bx-chevron-right"></span> button appear at
+ its ends:</p>
+<ul>
+ <li>To scroll the titles, click one of the buttons. Holding a button down
+ scrolls the titles continuously until it is released.</li>
+ <li>On a touch screen, the titles can also be swiped sideways.</li>
+</ul>
+<p>Whenever another tab is shown (for example by clicking its title, by moving
+ the cursor into it or by following a link to it), the row scrolls so that
+ its whole title is visible. This works the same while editing, in read-only
+ notes and on shared pages.</p>
<h2>Editing tabs</h2>
<ul>
<li>To show a tab, click its title or move the cursor into it.</li>
diff --git a/apps/server/src/assets/translations/en/server.json b/apps/server/src/assets/translations/en/server.json
index 2d492735e7..b6a5292e1e 100644
--- a/apps/server/src/assets/translations/en/server.json
+++ b/apps/server/src/assets/translations/en/server.json
@@ -473,7 +473,9 @@
"heading-link": "Link to This Section",
"previous": "Previous",
"next": "Next",
- "page-navigation": "Previous and next pages"
+ "page-navigation": "Previous and next pages",
+ "previous-tabs": "Scroll to the previous tabs",
+ "next-tabs": "Scroll to the next tabs"
},
"hidden_subtree_templates": {
"text-snippet": "Text Snippet",
diff --git a/docs/User Guide/User Guide/Note Types/Text/Content tabs.md b/docs/User Guide/User Guide/Note Types/Text/Content tabs.md
index 74c7aa5d01..340660d916 100644
--- a/docs/User Guide/User Guide/Note Types/Text/Content tabs.md
+++ b/docs/User Guide/User Guide/Note Types/Text/Content tabs.md
@@ -3,7 +3,7 @@ Content tabs group several titled panels of content into one block that shows a
A tabs block consists of:
-* **A row of tab titles**, above the panel or, when the tabs are aligned at the bottom, below it. The title of the panel that is showing is highlighted.
+* **A single row of tab titles**, above the panel or, when the tabs are aligned at the bottom, below it. The title of the panel that is showing is highlighted.
* **The panel of the active tab.** A panel can hold any kind of content (including nested tabs blocks).
## Inserting a tabs block
@@ -13,6 +13,15 @@ A tabs block consists of:
A new block contains two tabs, named “Tab 1” and “Tab 2”. Any content that was selected prior to inserting the tabs will be moved into the first tab. The title of the first tab is selected, so typing replaces it.
+## Scrolling through the titles
+
+When the titles of a block do not fit on their row, a <span class="tn-icon bx bx-chevron-left"></span> button and a <span class="tn-icon bx bx-chevron-right"></span> button appear at its ends:
+
+* To scroll the titles, click one of the buttons. Holding a button down scrolls the titles continuously until it is released.
+* On a touch screen, the titles can also be swiped sideways.
+
+Whenever another tab is shown (for example by clicking its title, by moving the cursor into it or by following a link to it), the row scrolls so that its whole title is visible. This works the same while editing, in read-only notes and on shared pages.
+
## Editing tabs
* To show a tab, click its title or move the cursor into it.
diff --git a/packages/ckeditor5/src/plugins/block_reference/block_reference_read_only.spec.ts b/packages/ckeditor5/src/plugins/block_reference/block_reference_read_only.spec.ts
index acca9d73da..e0edf33ec4 100644
--- a/packages/ckeditor5/src/plugins/block_reference/block_reference_read_only.spec.ts
+++ b/packages/ckeditor5/src/plugins/block_reference/block_reference_read_only.spec.ts
@@ -1,6 +1,6 @@
import { afterEach, beforeEach, describe, expect, it, type MockInstance, vi } from "vitest";
-import { applyTabs } from "../tabs/tabs_read_only.js";
+import { applyTabs, getTabTitle } from "../tabs/tabs_read_only.js";
import { getBlockRangeElements, showBlockReference } from "./block_reference_read_only.js";
const SPACER = "<div style=\"height: 1000px\"></div>";
@@ -109,20 +109,22 @@ describe("showBlockReference", () => {
+ "<section class=\"trilium-tab\" data-trilium-block-id=\"bare\"><p>c</p></section>"
+ "</div>" + SPACER
);
- applyTabs(scroller, { placeholder: "" });
+ applyTabs(scroller, { placeholder: "", scrollLabels: { start: "", end: "" } });
const activeTitle = () =>
- scroller.querySelector(".trilium-tab--active > .trilium-tab-title");
+ scroller.querySelector(".trilium-tab-title--active");
expect(activeTitle()?.textContent).toBe("A");
showBlockReference(scroller, "a");
expect(activeTitle()?.textContent).toBe("B");
showBlockReference(scroller, "t");
- const title = getBlock(scroller, "t").querySelector(".trilium-tab-title");
+ const title = getTabTitle(getBlock(scroller, "t"));
const panel = getBlock(scroller, "t").querySelector(".trilium-tab-panel");
const titleTop = title?.getBoundingClientRect().top ?? NaN;
const height = (panel?.getBoundingClientRect().bottom ?? NaN) - titleTop;
- expect(titleTop - scroller.getBoundingClientRect().top).toBeCloseTo((400 - height) / 2);
+ // The scroll offset is a whole number of pixels.
+ const offset = titleTop - scroller.getBoundingClientRect().top;
+ expect(Math.abs(offset - (400 - height) / 2)).toBeLessThanOrEqual(0.5);
showBlockReference(scroller, "bare");
expect(getOffset(scroller, "bare"))
diff --git a/packages/ckeditor5/src/plugins/block_reference/block_reference_read_only.ts b/packages/ckeditor5/src/plugins/block_reference/block_reference_read_only.ts
index 6ab52f1fc8..b6ffee9140 100644
--- a/packages/ckeditor5/src/plugins/block_reference/block_reference_read_only.ts
+++ b/packages/ckeditor5/src/plugins/block_reference/block_reference_read_only.ts
@@ -2,7 +2,7 @@ import { resolveBlockReference } from "@triliumnext/commons/src/lib/block_refere
import "../../theme/block_reference.css";
import { CLASSES as TAB_CLASSES } from "../tabs/constants.js";
-import { revealTab } from "../tabs/tabs_read_only.js";
+import { getTabTitle, revealTab } from "../tabs/tabs_read_only.js";
const FLASH_CLASS = "block-reference-flash";
/** The duration of the `block-reference-flash` animation in `block_reference.css`. */
@@ -46,7 +46,7 @@ export function flashBlocks(elements: Element[]) {
*/
export function getBlockBoxes(block: Element): { top: Element; bottom: Element } {
if (block.classList.contains(TAB_CLASSES.tab)) {
- const title = block.querySelector(`:scope > .${TAB_CLASSES.tabTitle}`);
+ const title = getTabTitle(block);
const panel = block.querySelector(`:scope > .${TAB_CLASSES.tabPanel}`);
if (title && panel) {
return { top: title, bottom: panel };
diff --git a/packages/ckeditor5/src/plugins/scrollable_bar.spec.ts b/packages/ckeditor5/src/plugins/scrollable_bar.spec.ts
new file mode 100644
index 0000000000..7d3c0043b5
--- /dev/null
+++ b/packages/ckeditor5/src/plugins/scrollable_bar.spec.ts
@@ -0,0 +1,277 @@
+import "../theme/scrollable_bar.css";
+
+import { afterEach, describe, expect, it, onTestFinished, vi } from "vitest";
+
+import { attachScrollableBar, createScrollableBar } from "./scrollable_bar.js";
+
+const LABELS = { start: "Back", end: "Next" };
+
+/** A bar 300px wide with `count` items 100px wide, attached to the document. */
+function renderBar(count: number, dir: "ltr" | "rtl" = "ltr") {
+ const { bar, viewport } = createScrollableBar(document, LABELS);
+ bar.dir = dir;
+ bar.style.width = "300px";
+ for (let index = 0; index < count; index++) {
+ viewport.append(createItem(`Item ${index}`, 100));
+ }
+ document.body.append(bar);
+ const scrollableBar = attachScrollableBar(bar, viewport);
+ onTestFinished(() => {
+ scrollableBar.disconnect();
+ bar.remove();
+ });
+
+ const [ start, end ] = bar.querySelectorAll("button");
+ const items = [ ...viewport.children ] as HTMLElement[];
+ return { bar, viewport, start, end, items, scrollableBar };
+}
+
+function createItem(text: string, width: number) {
+ const item = document.createElement("span");
+ item.textContent = text;
+ item.style.flex = "none";
+ item.style.width = `${width}px`;
+ return item;
+}
+
+/** Presses `target` with the mouse button `button` and keeps it down. */
+function hold(target: Element, button = 0) {
+ const press = new PointerEvent("pointerdown", { bubbles: true, cancelable: true, button });
+ target.dispatchEvent(press);
+ onTestFinished(() => document.dispatchEvent(new PointerEvent("pointerup")));
+ return press;
+}
+
+function wait(milliseconds: number) {
+ return new Promise(resolve => setTimeout(resolve, milliseconds));
+}
+
+function edgeOf(button: HTMLElement) {
+ return button.parentElement as HTMLElement;
+}
+
+function isOverflowing(bar: HTMLElement) {
+ return bar.classList.contains("scrollable-bar--overflowing");
+}
+
+/** How far `item` lies past the left and the right edge of `viewport`, rounded. */
+function edgesOf(item: Element, viewport: Element) {
+ const rect = item.getBoundingClientRect();
+ const box = viewport.getBoundingClientRect();
+ return [ Math.round(rect.left - box.left), Math.round(rect.right - box.right) ];
+}
+
+describe("scrollable bar", () => {
+ afterEach(() => {
+ document.body.classList.remove("motion-disabled");
+ vi.restoreAllMocks();
+ });
+
+ it("builds a viewport between two edges, each with a button out of the tab order", () => {
+ const { bar } = createScrollableBar(document, LABELS);
+
+ expect([ ...bar.children ].map(child => child.className)).toEqual([
+ "scrollable-bar-edge scrollable-bar-edge--start",
+ "scrollable-bar-viewport",
+ "scrollable-bar-edge scrollable-bar-edge--end"
+ ]);
+ const buttons = [ ...bar.querySelectorAll(":scope > .scrollable-bar-edge > button") ];
+ expect(buttons).toHaveLength(2);
+ for (const [ index, button ] of buttons.entries()) {
+ const label = [ "Back", "Next" ][index];
+ const icon = [ "bx-chevron-left", "bx-chevron-right" ][index];
+ expect(button.className).toBe(`icon-action bx ${icon} scrollable-bar-button`);
+ expect(button.type).toBe("button");
+ expect(button.tabIndex).toBe(-1);
+ expect(button.title).toBe(label);
+ expect(button.getAttribute("aria-label")).toBe(label);
+ }
+ });
+
+ it("shows the buttons while the items overflow, disabling one at a reached edge", async () => {
+ const { bar, viewport, start, end } = renderBar(2);
+ expect(isOverflowing(bar)).toBe(false);
+ expect(getComputedStyle(edgeOf(start)).display).toBe("none");
+
+ viewport.append(createItem("Item 2", 100), createItem("Item 3", 100));
+ await expect.poll(() => isOverflowing(bar)).toBe(true);
+ expect(getComputedStyle(edgeOf(start)).display).toBe("flex");
+ for (const button of [ start, end ]) {
+ const edge = edgeOf(button).getBoundingClientRect();
+ const rect = button.getBoundingClientRect();
+ expect([ edge.width, rect.width, rect.height ]).toEqual([ 36, 28, 28 ]);
+ expect(rect.left - edge.left).toBe(edge.right - rect.right);
+ }
+ expect([ start.disabled, end.disabled ]).toEqual([ true, false ]);
+ expect([ start, end ].map(button => button.classList.contains("disabled")))
+ .toEqual([ true, false ]);
+
+ viewport.scrollLeft = viewport.scrollWidth;
+ await expect.poll(() => [ start.disabled, end.disabled ]).toEqual([ false, true ]);
+
+ viewport.lastElementChild?.remove();
+ viewport.lastElementChild?.remove();
+ await expect.poll(() => isOverflowing(bar)).toBe(false);
+ });
+
+ it("scrolls by most of its width toward the edge clicked, in either direction", async () => {
+ document.body.classList.add("motion-disabled");
+ for (const [ dir, sign ] of [ [ "ltr", 1 ], [ "rtl", -1 ] ] as const) {
+ const { viewport, start, end, items } = renderBar(10, dir);
+ const page = viewport.clientWidth * 0.8;
+
+ items[0].click();
+ edgeOf(start).click();
+ expect(viewport.scrollLeft, dir).toBe(0);
+
+ edgeOf(end).click();
+ expect(viewport.scrollLeft, dir).toBeCloseTo(sign * page, 0);
+
+ await expect.poll(() => start.disabled, dir).toBe(false);
+ start.click();
+ expect(viewport.scrollLeft, dir).toBeCloseTo(0, 0);
+ }
+ });
+
+ it("scrolls while a button is held down, and skips the click that ends the hold", async () => {
+ document.body.classList.add("motion-disabled");
+ const { viewport, end } = renderBar(20);
+ hold(end);
+ await wait(200);
+ expect(viewport.scrollLeft).toBe(0);
+
+ await expect.poll(() => viewport.scrollLeft).toBeGreaterThan(0);
+ const start = { time: performance.now(), position: viewport.scrollLeft };
+ await wait(300);
+ const elapsed = performance.now() - start.time;
+ const speed = (viewport.scrollLeft - start.position) / elapsed * 1000;
+ expect(speed).toBeGreaterThan(700);
+ expect(speed).toBeLessThan(1100);
+
+ document.dispatchEvent(new PointerEvent("pointerup"));
+ const position = viewport.scrollLeft;
+ end.click();
+ await wait(100);
+ expect(viewport.scrollLeft).toBe(position);
+
+ end.click();
+ expect(viewport.scrollLeft).toBeCloseTo(position + viewport.clientWidth * 0.8, 0);
+ });
+
+ it("stops a hold at the edge or a canceled pointer, and holds the main button", async () => {
+ const { viewport, start, end } = renderBar(4);
+ hold(end);
+ await expect.poll(() => end.disabled).toBe(true);
+ const position = viewport.scrollLeft;
+ expect(position).toBe(viewport.scrollWidth - viewport.clientWidth);
+
+ hold(start);
+ await expect.poll(() => viewport.scrollLeft).toBeLessThan(position);
+ document.dispatchEvent(new PointerEvent("pointercancel"));
+ const stopped = viewport.scrollLeft;
+ await wait(100);
+ expect(viewport.scrollLeft).toBe(stopped);
+
+ hold(start, 2);
+ await wait(400);
+ expect(viewport.scrollLeft).toBe(stopped);
+ });
+
+ it("scrolls smoothly, unless Trilium's animations or the system's motion are off", async () => {
+ const { viewport, end } = renderBar(10);
+ end.click();
+ expect(viewport.scrollLeft).toBe(0);
+ await expect.poll(() => Math.round(viewport.scrollLeft))
+ .toBe(Math.round(viewport.clientWidth * 0.8));
+
+ vi.spyOn(window, "matchMedia").mockReturnValue({ matches: true } as MediaQueryList);
+ viewport.scrollLeft = 0;
+ end.click();
+ expect(window.matchMedia).toHaveBeenCalledWith("(prefers-reduced-motion: reduce)");
+ expect(viewport.scrollLeft).toBeCloseTo(viewport.clientWidth * 0.8, 0);
+ });
+
+ it("reveals an item by the least distance, or its start when it is wider", async () => {
+ document.body.classList.add("motion-disabled");
+ const { viewport, items, scrollableBar } = renderBar(10);
+ const wide = createItem("Wide", 400);
+ viewport.append(wide);
+
+ scrollableBar.reveal(items[5]);
+ expect(edgesOf(items[5], viewport)[1]).toBe(0);
+
+ scrollableBar.reveal(items[4]);
+ expect(edgesOf(items[5], viewport)[1]).toBe(0);
+
+ scrollableBar.reveal(items[1]);
+ expect(edgesOf(items[1], viewport)[0]).toBe(0);
+
+ scrollableBar.reveal(wide);
+ expect(edgesOf(wide, viewport)[0]).toBe(0);
+
+ scrollableBar.reveal(items[0]);
+ scrollableBar.reveal(wide);
+ expect(edgesOf(wide, viewport)[0]).toBe(0);
+
+ document.body.classList.remove("motion-disabled");
+ scrollableBar.reveal(items[0]);
+ expect(edgesOf(wide, viewport)[0]).toBe(0);
+ await expect.poll(() => edgesOf(items[0], viewport)[0]).toBe(0);
+
+ scrollableBar.reveal(items[9], { isAnimated: false });
+ expect(edgesOf(items[9], viewport)[1]).toBe(0);
+ });
+
+ it("reveals an item from its start right to left", () => {
+ document.body.classList.add("motion-disabled");
+ const { viewport, items, scrollableBar } = renderBar(10, "rtl");
+ const wide = createItem("Wide", 400);
+ viewport.append(wide);
+
+ scrollableBar.reveal(items[5]);
+ expect(edgesOf(items[5], viewport)[0]).toBe(0);
+
+ scrollableBar.reveal(items[1]);
+ expect(edgesOf(items[1], viewport)[1]).toBe(0);
+
+ scrollableBar.reveal(items[2]);
+ expect(edgesOf(items[1], viewport)[1]).toBe(0);
+
+ for (const item of [ wide, items[0], wide ]) {
+ scrollableBar.reveal(item);
+ expect(edgesOf(item, viewport)[1]).toBe(0);
+ }
+ });
+
+ it("keeps a press beside the viewport from taking the focus or reaching ancestors", () => {
+ const { bar, end, items } = renderBar(10);
+ const outside = vi.fn();
+ document.body.addEventListener("pointerdown", outside);
+ onTestFinished(() => document.body.removeEventListener("pointerdown", outside));
+
+ for (const target of [ end, edgeOf(end), bar ]) {
+ expect(hold(target).defaultPrevented).toBe(true);
+ document.dispatchEvent(new PointerEvent("pointerup"));
+ }
+ expect(outside).not.toHaveBeenCalled();
+
+ const itemPress = new PointerEvent("pointerdown", { bubbles: true, cancelable: true });
+ items[0].dispatchEvent(itemPress);
+ expect(itemPress.defaultPrevented).toBe(false);
+ expect(outside).toHaveBeenCalledOnce();
+ expect(bar.contains(document.activeElement)).toBe(false);
+ });
+
+ it("stops scrolling and watching once disconnected", async () => {
+ const { bar, viewport, end, scrollableBar } = renderBar(10);
+ expect(isOverflowing(bar)).toBe(true);
+
+ scrollableBar.disconnect();
+ expect(isOverflowing(bar)).toBe(false);
+ end.click();
+ expect(viewport.scrollLeft).toBe(0);
+ viewport.append(createItem("Item 10", 100));
+ await new Promise(resolve => requestAnimationFrame(resolve));
+ expect(isOverflowing(bar)).toBe(false);
+ });
+});
diff --git a/packages/ckeditor5/src/plugins/scrollable_bar.ts b/packages/ckeditor5/src/plugins/scrollable_bar.ts
new file mode 100644
index 0000000000..ae9aa430af
--- /dev/null
+++ b/packages/ckeditor5/src/plugins/scrollable_bar.ts
@@ -0,0 +1,235 @@
+import {
+ type ScrollFadeState, watchScrollFade
+} from "@triliumnext/commons/src/lib/scroll_fade.js";
+
+/** The classes of a scrollable bar, styled by `scrollable_bar.css`. */
+export const SCROLLABLE_BAR_CLASSES = {
+ bar: "scrollable-bar",
+ overflowing: "scrollable-bar--overflowing",
+ viewport: "scrollable-bar-viewport",
+ edge: "scrollable-bar-edge",
+ startEdge: "scrollable-bar-edge--start",
+ endEdge: "scrollable-bar-edge--end",
+ button: "scrollable-bar-button"
+} as const;
+
+/** The edge of the bar that a button scrolls toward: left or right, depending on the direction. */
+export type ScrollableBarEdge = "start" | "end";
+
+export interface ScrollableBarLabels {
+ /** The label of the button that scrolls toward the start. */
+ start: string;
+ /** The label of the button that scrolls toward the end. */
+ end: string;
+}
+
+export interface ScrollableBar {
+ /**
+ * Scrolls the viewport the least distance that shows all of `item`, or its start when it is
+ * wider than the viewport. The scroll is animated unless motion is turned off.
+ */
+ reveal(item: Element, options?: { isAnimated?: boolean }): void;
+ /** Stops watching the bar and removes its listeners. */
+ disconnect(): void;
+}
+
+/**
+ * Builds an empty scrollable bar: a single-row viewport for the items, between the two edges with
+ * the buttons that scroll it. Add the items to `viewport`, then call {@link attachScrollableBar}.
+ *
+ * The module imports nothing from CKEditor, so pages that only display content can load it.
+ */
+export function createScrollableBar(document: Document, labels: ScrollableBarLabels) {
+ const bar = document.createElement("div");
+ bar.className = SCROLLABLE_BAR_CLASSES.bar;
+ const viewport = document.createElement("div");
+ viewport.className = SCROLLABLE_BAR_CLASSES.viewport;
+ bar.append(
+ createScrollableBarEdge(document, "start", labels.start),
+ viewport,
+ createScrollableBarEdge(document, "end", labels.end)
+ );
+ return { bar, viewport };
+}
+
+/**
+ * Builds the space at one edge of a bar, with the button that scrolls toward that edge in its
+ * center: an `icon-action` button with a Boxicons chevron, out of the tab order. A press anywhere
+ * in the space counts as a press on the button.
+ */
+export function createScrollableBarEdge(
+ document: Document,
+ edge: ScrollableBarEdge,
+ label: string
+) {
+ const isStart = edge === "start";
+ const edgeClass = isStart ? SCROLLABLE_BAR_CLASSES.startEdge : SCROLLABLE_BAR_CLASSES.endEdge;
+ const element = document.createElement("div");
+ element.className = `${SCROLLABLE_BAR_CLASSES.edge} ${edgeClass}`;
+
+ const button = document.createElement("button");
+ button.type = "button";
+ const icon = isStart ? "bx-chevron-left" : "bx-chevron-right";
+ button.className = `icon-action bx ${icon} ${SCROLLABLE_BAR_CLASSES.button}`;
+ button.tabIndex = -1;
+ button.title = label;
+ button.setAttribute("aria-label", label);
+ element.append(button);
+ return element;
+}
+
+/**
+ * Makes `bar` scroll: its buttons show while the items overflow `viewport`, and the button of an
+ * edge that is reached is disabled. A click on a button scrolls by most of the viewport's width;
+ * holding the button down scrolls continuously until it is released. A press on the bar outside
+ * the viewport does not move the focus and does not reach the listeners of the bar's ancestors,
+ * such as an editor's.
+ */
+export function attachScrollableBar(bar: HTMLElement, viewport: HTMLElement): ScrollableBar {
+ const document = bar.ownerDocument;
+ let isRtl = false;
+ let holdTimer: ReturnType<typeof setTimeout> | undefined;
+ let holdFrame: number | undefined;
+ /** Whether the press that ends with the next click scrolled while it was held. */
+ let isClickHandled = false;
+
+ const getDirection = (button: HTMLElement) => {
+ const isTowardStart = !!button.closest(`.${SCROLLABLE_BAR_CLASSES.startEdge}`);
+ return (isTowardStart ? -1 : 1) * (isRtl ? -1 : 1);
+ };
+ const stopHolding = () => {
+ clearTimeout(holdTimer);
+ if (holdFrame !== undefined) {
+ cancelAnimationFrame(holdFrame);
+ }
+ holdTimer = undefined;
+ holdFrame = undefined;
+ document.removeEventListener("pointerup", stopHolding);
+ document.removeEventListener("pointercancel", stopHolding);
+ };
+ const scrollWhileHeld = (button: HTMLButtonElement) => {
+ isClickHandled = true;
+ // `position` keeps the fraction of a pixel that `scrollLeft` can round away each step.
+ let position = viewport.scrollLeft;
+ let lastTime: number | null = null;
+ const step = (time: number) => {
+ if (button.disabled) {
+ stopHolding();
+ return;
+ }
+ const elapsed = lastTime === null ? 0 : time - lastTime;
+ lastTime = time;
+ position += getDirection(button) * HOLD_SPEED * elapsed / 1000;
+ viewport.scrollLeft = position;
+ holdFrame = requestAnimationFrame(step);
+ };
+ holdFrame = requestAnimationFrame(step);
+ };
+
+ const onPointerDown = (event: PointerEvent) => {
+ if (viewport.contains(event.target as Node)) {
+ return;
+ }
+ event.preventDefault();
+ event.stopPropagation();
+ stopHolding();
+ isClickHandled = false;
+ const button = findButton(event);
+ if (button && !button.disabled && event.button === 0) {
+ holdTimer = setTimeout(() => scrollWhileHeld(button), HOLD_DELAY);
+ document.addEventListener("pointerup", stopHolding);
+ document.addEventListener("pointercancel", stopHolding);
+ }
+ };
+ const onClick = (event: MouseEvent) => {
+ const button = findButton(event);
+ if (!button || button.disabled || isClickHandled) {
+ isClickHandled = false;
+ return;
+ }
+ viewport.scrollBy({
+ left: getDirection(button) * viewport.clientWidth * PAGE_SHARE,
+ behavior: getScrollBehavior(viewport)
+ });
+ };
+ const showState = (state: ScrollFadeState) => {
+ isRtl = state.isRtl;
+ bar.classList.toggle(SCROLLABLE_BAR_CLASSES.overflowing, state.overflow > MIN_OVERFLOW);
+ const buttons = bar.querySelectorAll<HTMLButtonElement>(
+ `:scope > .${SCROLLABLE_BAR_CLASSES.edge} > .${SCROLLABLE_BAR_CLASSES.button}`);
+ for (const button of buttons) {
+ const isStart = !!button.closest(`.${SCROLLABLE_BAR_CLASSES.startEdge}`);
+ button.disabled = !(isStart ? state.isStartFaded : state.isEndFaded);
+ // `icon-action` buttons look disabled through the class.
+ button.classList.toggle("disabled", button.disabled);
+ }
+ };
+
+ const watch = watchScrollFade(viewport, showState, {
+ direction: "horizontal",
+ minOverflow: MIN_OVERFLOW
+ });
+ bar.addEventListener("pointerdown", onPointerDown);
+ bar.addEventListener("click", onClick);
+
+ return {
+ reveal(item, { isAnimated = true } = {}) {
+ const distance = getRevealDistance(
+ viewport.getBoundingClientRect(), item.getBoundingClientRect(), isRtl);
+ if (distance) {
+ viewport.scrollBy({
+ left: distance,
+ behavior: isAnimated ? getScrollBehavior(viewport) : "instant"
+ });
+ }
+ },
+ disconnect() {
+ stopHolding();
+ watch.disconnect();
+ bar.removeEventListener("pointerdown", onPointerDown);
+ bar.removeEventListener("click", onClick);
+ bar.classList.remove(SCROLLABLE_BAR_CLASSES.overflowing);
+ }
+ };
+}
+
+/** The share of the viewport's width that a button scrolls by. */
+const PAGE_SHARE = 0.8;
+
+/** Overflow up to this many pixels is rounding and shows no buttons. */
+const MIN_OVERFLOW = 1;
+
+/** How long a button is held down before it scrolls continuously, in milliseconds. */
+const HOLD_DELAY = 300;
+
+/** The speed of the continuous scroll while a button is held down, in pixels per second. */
+const HOLD_SPEED = 900;
+
+/** The button of the edge that `event` happened in. */
+function findButton(event: Event) {
+ const edge = (event.target as Element).closest(`.${SCROLLABLE_BAR_CLASSES.edge}`);
+ return edge?.querySelector<HTMLButtonElement>(`.${SCROLLABLE_BAR_CLASSES.button}`);
+}
+
+/** The horizontal distance to scroll `box` by so that it shows `rect`, from its start edge. */
+function getRevealDistance(box: DOMRect, rect: DOMRect, isRtl: boolean) {
+ const pastLeft = rect.left - box.left;
+ const pastRight = rect.right - box.right;
+ if (isRtl) {
+ if (pastRight > 0) {
+ return pastRight;
+ }
+ return pastLeft < 0 ? Math.max(pastLeft, pastRight) : 0;
+ }
+ if (pastLeft < 0) {
+ return pastLeft;
+ }
+ return pastRight > 0 ? Math.min(pastRight, pastLeft) : 0;
+}
+
+/** Smooth scrolling, unless Trilium's animations or the system's motion are turned off. */
+function getScrollBehavior(element: Element): ScrollBehavior {
+ const isReduced = element.ownerDocument.body.classList.contains("motion-disabled")
+ || matchMedia("(prefers-reduced-motion: reduce)").matches;
+ return isReduced ? "instant" : "smooth";
+}
diff --git a/packages/ckeditor5/src/plugins/tabs/constants.ts b/packages/ckeditor5/src/plugins/tabs/constants.ts
index 9da117b74c..467ec67889 100644
--- a/packages/ckeditor5/src/plugins/tabs/constants.ts
+++ b/packages/ckeditor5/src/plugins/tabs/constants.ts
@@ -6,13 +6,15 @@ export const ELEMENTS = {
tabPanel: "tabPanel"
} as const;
-/** CSS classes of the saved HTML and the editing view. */
+/** CSS classes of the saved HTML and of the editing and read-only views. */
export const CLASSES = {
tabs: "trilium-tabs",
tab: "trilium-tab",
tabTitle: "trilium-tab-title",
tabPanel: "trilium-tab-panel",
- activeTab: "trilium-tab--active"
+ activeTab: "trilium-tab--active",
+ activeTitle: "trilium-tab-title--active",
+ titleBar: "trilium-tabs-bar"
} as const;
/** Custom property that marks the editing-view widget element of a tabs block. */
diff --git a/packages/ckeditor5/src/plugins/tabs/tabs.spec.ts b/packages/ckeditor5/src/plugins/tabs/tabs.spec.ts
index bb9c1a3609..ef31032edf 100644
--- a/packages/ckeditor5/src/plugins/tabs/tabs.spec.ts
+++ b/packages/ckeditor5/src/plugins/tabs/tabs.spec.ts
@@ -6,7 +6,9 @@ import {
Essentials,
FindAndReplaceEditing,
type ModelElement,
- Paragraph
+ Paragraph,
+ type ViewElement,
+ type ViewNode
} from "ckeditor5";
import { afterEach, beforeEach, describe, expect, it } from "vitest";
@@ -46,7 +48,7 @@ describe("Tabs", () => {
function activeTitles() {
const root = editor.editing.view.getDomRoot();
- return [...root?.querySelectorAll(".trilium-tab--active > .trilium-tab-title") ?? []]
+ return [...root?.querySelectorAll(".trilium-tab-title--active") ?? []]
.map(title => title.textContent);
}
@@ -301,6 +303,90 @@ describe("Tabs", () => {
expect(model()).toBe("<paragraph></paragraph>");
});
+ it("keeps the titles in the title bar in tab order, and each panel in its section", () => {
+ editor.setData(TWO_TABS);
+ const root = editor.editing.view.getDomRoot();
+ const barTitles = () =>
+ [...root?.querySelectorAll(".trilium-tabs-bar .trilium-tab-title") ?? []]
+ .map(title => title.textContent);
+ const windows = tabsElement().getChild(0) as ModelElement;
+ editor.model.change(writer => writer.setSelection(windows.getChild(0) as ModelElement, 0));
+
+ editor.execute("insertTab");
+ editor.model.change(writer => editor.model.insertContent(writer.createText("macOS")));
+ expect(barTitles()).toEqual(["Windows", "macOS", "Linux"]);
+
+ editor.execute("moveTabRight");
+ expect(barTitles()).toEqual(["Windows", "Linux", "macOS"]);
+ editor.execute("undo");
+ expect(barTitles()).toEqual(["Windows", "macOS", "Linux"]);
+ editor.execute("removeTab");
+ expect(barTitles()).toEqual(["Windows", "Linux"]);
+
+ const linux = tabsElement().getChild(1) as ModelElement;
+ editor.model.change(writer => writer.remove(linux.getChild(0) as ModelElement));
+ expect(barTitles()).toEqual(["Windows", ""]);
+ editor.execute("undo");
+ expect(barTitles()).toEqual(["Windows", "Linux"]);
+
+ const sections = [...root?.querySelectorAll("section.trilium-tab") ?? []];
+ const panels = [...root?.querySelectorAll(".trilium-tab-panel") ?? []];
+ expect(sections.map(section => [...section.children].map(child => child.id)))
+ .toEqual(panels.map(panel => [panel.id]));
+ expect(editor.getData()).toBe(TWO_TABS);
+ });
+
+ it("maps positions in the title bar and the sections to the model and back", () => {
+ editor.setData(TWO_TABS);
+ const { mapper, view } = editor.editing;
+ const model = editor.model;
+ const tabs = tabsElement();
+ const [windows, linux] = tabs.getChildren() as IterableIterator<ModelElement>;
+ const tabsView = mapper.toViewElement(tabs) as ViewElement;
+ const section = mapper.toViewElement(linux) as ViewElement;
+ const windowsTitle = mapper.toViewElement(windows.getChild(0) as ModelElement);
+ const viewport = windowsTitle?.parent as ViewElement;
+ const toModelPath = (parent: ViewNode, offset: number) =>
+ mapper.toModelPosition(view.createPositionAt(parent, offset)).path;
+
+ const linuxTitle = mapper.toViewElement(linux.getChild(0) as ModelElement) as ViewElement;
+ expect(toModelPath(linuxTitle.getChild(0) as ViewNode, 2)).toEqual([0, 1, 0, 2]);
+ expect(toModelPath(section, 0)).toEqual([0, 1, 1]);
+ expect(toModelPath(section, 1)).toEqual([0, 1, 2]);
+ expect(toModelPath(viewport, 1)).toEqual([0, 1]);
+ expect(toModelPath(tabsView, tabsView.getChildIndex(section))).toEqual([0, 1]);
+ expect(toModelPath(tabsView, tabsView.childCount)).toEqual([0, 2]);
+
+ const toView = (parent: ModelElement, offset: number) => {
+ const position = mapper.toViewPosition(model.createPositionAt(parent, offset));
+ return [position.parent, position.offset];
+ };
+ expect(toView(linux, 0)).toEqual([viewport, 1]);
+ expect(toView(linux, 1)).toEqual([section, 0]);
+ expect(toView(tabs, 1)).toEqual([tabsView, tabsView.getChildIndex(section)]);
+ expect(toView(tabs, 2)).toEqual([tabsView, tabsView.getChildIndex(section) + 1]);
+ });
+
+ it("keeps a press on a scroll button from selecting the tabs block", () => {
+ editor.setData(TWO_TABS);
+ const windows = tabsElement().getChild(0) as ModelElement;
+ editor.model.change(writer => writer.setSelection(windows.getChild(0) as ModelElement, 0));
+ const caret = getModelData(editor.model);
+ const root = editor.editing.view.getDomRoot();
+ const press = (target: Element | null | undefined) => {
+ expect(target).toBeTruthy();
+ target?.dispatchEvent(new PointerEvent("pointerdown", {
+ bubbles: true, cancelable: true, isPrimary: true
+ }));
+ };
+
+ press(root?.querySelector(".scrollable-bar-edge--end > .scrollable-bar-button"));
+ expect(getModelData(editor.model)).toBe(caret);
+
+ press(root?.querySelector(".scrollable-bar-viewport"));
+ expect(editor.model.document.selection.getSelectedElement()).toBe(tabsElement());
+ });
+
it("moves the caret from a title into its panel on Enter", () => {
editor.setData(TWO_TABS);
const windows = tabsElement().getChild(0) as ModelElement;
diff --git a/packages/ckeditor5/src/plugins/tabs/tabs.ts b/packages/ckeditor5/src/plugins/tabs/tabs.ts
index 81cd728954..3ac3de165d 100644
--- a/packages/ckeditor5/src/plugins/tabs/tabs.ts
+++ b/packages/ckeditor5/src/plugins/tabs/tabs.ts
@@ -1,5 +1,6 @@
import { Plugin } from "ckeditor5";
+import "../../theme/scrollable_bar.css";
import "../../theme/tabs.css";
import type {
AssignTabReferenceCommand, InsertTabCommand, InsertTabsCommand, MoveTabCommand,
@@ -7,6 +8,7 @@ import type {
} from "./tabs_commands.js";
import TabsEditing from "./tabs_editing.js";
import TabsKeyboard from "./tabs_keyboard.js";
+import TabsTitleBar from "./tabs_title_bar.js";
import TabsUI from "./tabs_ui.js";
/**
@@ -32,6 +34,7 @@ declare module "ckeditor5" {
[Tabs.pluginName]: Tabs;
[TabsEditing.pluginName]: TabsEditing;
[TabsKeyboard.pluginName]: TabsKeyboard;
+ [TabsTitleBar.pluginName]: TabsTitleBar;
[TabsUI.pluginName]: TabsUI;
}
diff --git a/packages/ckeditor5/src/plugins/tabs/tabs_commands.spec.ts b/packages/ckeditor5/src/plugins/tabs/tabs_commands.spec.ts
index 1f1e5df1aa..23e57901e3 100644
--- a/packages/ckeditor5/src/plugins/tabs/tabs_commands.spec.ts
+++ b/packages/ckeditor5/src/plugins/tabs/tabs_commands.spec.ts
@@ -47,7 +47,7 @@ describe("tabs commands", () => {
function activeTitles() {
const root = editor.editing.view.getDomRoot();
- return [...root?.querySelectorAll(".trilium-tab--active > .trilium-tab-title") ?? []]
+ return [...root?.querySelectorAll(".trilium-tab-title--active") ?? []]
.map(title => title.textContent);
}
diff --git a/packages/ckeditor5/src/plugins/tabs/tabs_editing.spec.ts b/packages/ckeditor5/src/plugins/tabs/tabs_editing.spec.ts
index 63e81ef1e0..67b6aff637 100644
--- a/packages/ckeditor5/src/plugins/tabs/tabs_editing.spec.ts
+++ b/packages/ckeditor5/src/plugins/tabs/tabs_editing.spec.ts
@@ -40,7 +40,7 @@ describe("TabsEditing", () => {
function activeTitles() {
const root = editor.editing.view.getDomRoot();
- return [...root?.querySelectorAll(".trilium-tab--active > .trilium-tab-title") ?? []]
+ return [...root?.querySelectorAll(".trilium-tab-title--active") ?? []]
.map(title => title.textContent);
}
diff --git a/packages/ckeditor5/src/plugins/tabs/tabs_editing.ts b/packages/ckeditor5/src/plugins/tabs/tabs_editing.ts
index 7022594f9e..9b56d641ad 100644
--- a/packages/ckeditor5/src/plugins/tabs/tabs_editing.ts
+++ b/packages/ckeditor5/src/plugins/tabs/tabs_editing.ts
@@ -24,6 +24,7 @@ import {
AssignTabReferenceCommand, InsertTabCommand, InsertTabsCommand, MoveTabCommand,
MoveToTabCommand, RemoveTabCommand, TabAlignmentCommand
} from "./tabs_commands.js";
+import TabsTitleBar from "./tabs_title_bar.js";
/**
* Schema, conversion, commands and key handling for tabs blocks. The active tab is editing-view
@@ -36,7 +37,7 @@ export default class TabsEditing extends Plugin {
}
public static get requires() {
- return [Widget] as const;
+ return [TabsTitleBar, Widget] as const;
}
/** The tab each tabs block shows, keyed by the `tabs` model element. */
@@ -45,6 +46,9 @@ export default class TabsEditing extends Plugin {
/** The editing-view ID prefix of each tab's title and panel, keyed by the `tab` model element. */
private readonly tabIds = new WeakMap<ModelElement, string>();
+ /** The tab whose title each tabs block last scrolled into view, keyed by the `tabs` element. */
+ private readonly revealedTabs = new WeakMap<ModelElement, RevealedTab>();
+
public init(): void {
const editor = this.editor;
editor.commands.add("tabs", new InsertTabsCommand(editor));
@@ -200,7 +204,9 @@ export default class TabsEditing extends Plugin {
view: (_model, { writer }) => {
const div = writer.createContainerElement("div", { class: CLASSES.tabs });
writer.setCustomProperty(TABS_WIDGET_PROPERTY, true, div);
- return toWidget(div, writer, { label: t("Tabs"), hasSelectionHandle: true });
+ toWidget(div, writer, { label: t("Tabs"), hasSelectionHandle: true });
+ editor.plugins.get(TabsTitleBar).addBar(writer, div);
+ return div;
}
});
conversion.for("editingDowncast").elementToElement({
@@ -217,12 +223,14 @@ export default class TabsEditing extends Plugin {
// global `aria-current` and `aria-controls` attributes carry the tab semantics.
const tab = model.parent as ModelElement;
const id = this.getTabId(tab);
+ const isActive = this.isActiveTab(tab);
+ const classes = isActive ? [CLASSES.tabTitle, CLASSES.activeTitle] : [CLASSES.tabTitle];
const title: ViewEditableElement & PlaceholderableViewElement =
writer.createEditableElement("div", {
- class: CLASSES.tabTitle,
+ class: classes.join(" "),
id: `${id}-title`,
"aria-controls": `${id}-panel`,
- ...(this.isActiveTab(tab) ? { "aria-current": "true" } : {})
+ ...(isActive ? { "aria-current": "true" } : {})
});
title.placeholder = t("Tab title");
enableViewPlaceholder({
@@ -341,8 +349,13 @@ export default class TabsEditing extends Plugin {
}
}
+ /**
+ * Marks the active tab of each of `blocks`. Scrolls its title into view when another tab
+ * became active or the active tab moved.
+ */
private updateActiveClasses(blocks: Set<ModelElement>) {
const editing = this.editor.editing;
+ const titleBar = this.editor.plugins.get(TabsTitleBar);
editing.view.change(writer => {
for (const tabs of blocks) {
const active = this.getActiveTab(tabs);
@@ -353,12 +366,22 @@ export default class TabsEditing extends Plugin {
if (!view || !title) {
continue;
}
- if (tab === active) {
- writer.addClass(CLASSES.activeTab, view);
- writer.setAttribute("aria-current", "true", title);
- } else {
+ if (tab !== active) {
writer.removeClass(CLASSES.activeTab, view);
+ writer.removeClass(CLASSES.activeTitle, title);
writer.removeAttribute("aria-current", title);
+ continue;
+ }
+
+ writer.addClass(CLASSES.activeTab, view);
+ writer.addClass(CLASSES.activeTitle, title);
+ writer.setAttribute("aria-current", "true", title);
+ // A block shows its first tab until a tab is activated.
+ const shown = this.revealedTabs.get(tabs)
+ ?? { tab: tabs.getChild(0), index: 0 };
+ if (tab !== shown.tab || tab.index !== shown.index) {
+ titleBar.revealTitleAfterRender(title);
+ this.revealedTabs.set(tabs, { tab, index: tab.index });
}
}
}
@@ -387,6 +410,11 @@ export default class TabsEditing extends Plugin {
}
}
+interface RevealedTab {
+ tab: ModelNode | null;
+ index: number | null;
+}
+
/** Adds every tabs block that encloses `position`. */
function collectTabsAround(position: ModelPosition, blocks: Set<ModelElement>) {
for (const ancestor of position.getAncestors()) {
diff --git a/packages/ckeditor5/src/plugins/tabs/tabs_keyboard.spec.ts b/packages/ckeditor5/src/plugins/tabs/tabs_keyboard.spec.ts
index eb4a05c0a3..a546ffeaab 100644
--- a/packages/ckeditor5/src/plugins/tabs/tabs_keyboard.spec.ts
+++ b/packages/ckeditor5/src/plugins/tabs/tabs_keyboard.spec.ts
@@ -99,7 +99,7 @@ function model(editor: ClassicEditor) {
function activeTitles(editor: ClassicEditor) {
const root = editor.editing.view.getDomRoot();
- return [...root?.querySelectorAll(".trilium-tab--active > .trilium-tab-title") ?? []]
+ return [...root?.querySelectorAll(".trilium-tab-title--active") ?? []]
.map(title => title.textContent);
}
diff --git a/packages/ckeditor5/src/plugins/tabs/tabs_layout.spec.ts b/packages/ckeditor5/src/plugins/tabs/tabs_layout.spec.ts
index 8d534d4648..40e7d78e2c 100644
--- a/packages/ckeditor5/src/plugins/tabs/tabs_layout.spec.ts
+++ b/packages/ckeditor5/src/plugins/tabs/tabs_layout.spec.ts
@@ -1,4 +1,4 @@
-import { Essentials, Paragraph } from "ckeditor5";
+import { Essentials, type ModelElement, Paragraph } from "ckeditor5";
import editorStylesheetUrl from "ckeditor5/ckeditor5.css?url";
import { beforeAll, describe, expect, it, onTestFinished } from "vitest";
@@ -7,6 +7,8 @@ import type { TabAlignment } from "./constants.js";
import Tabs from "./tabs.js";
import { applyTabs } from "./tabs_read_only.js";
+const OPTIONS = { placeholder: "Tab title", scrollLabels: { start: "Back", end: "Next" } };
+
function tab(title: string, body: string) {
return `<section class="trilium-tab"><p class="trilium-tab-title">${title}</p>` +
`<div class="trilium-tab-panel">${body}</div></section>`;
@@ -22,6 +24,50 @@ function tabsHtml(alignment: TabAlignment | null) {
"</div>";
}
+/** Ten tabs, more than the titles of a 400px block can fit. */
+function manyTabsHtml(alignment: TabAlignment | null = null) {
+ const attribute = alignment ? ` data-trilium-tab-alignment="${alignment}"` : "";
+ const tabs = Array.from({ length: 10 }, (_, index) =>
+ tab(`Step ${index + 1} of the guide`, `<p>Body ${index + 1}</p>`));
+ return `<div class="trilium-tabs"${attribute}>${tabs.join("")}</div>`;
+}
+
+/** Saved `html` that `applyTabs()` set up, in a 400px container. */
+function renderSaved(html: string) {
+ const container = document.createElement("div");
+ container.className = "ck-content";
+ container.style.width = "400px";
+ container.innerHTML = html;
+ document.body.appendChild(container);
+ const dispose = applyTabs(container, OPTIONS);
+ onTestFinished(() => {
+ dispose();
+ container.remove();
+ });
+ return { container, dispose };
+}
+
+/** The first tabs block in `root` and the parts of its title bar. */
+function barOf(root: Element) {
+ const block = root.querySelector(".trilium-tabs") as HTMLElement;
+ const bar = block.querySelector(":scope > .trilium-tabs-bar") as HTMLElement;
+ const viewport = bar.querySelector(":scope > .scrollable-bar-viewport") as HTMLElement;
+ const titles = [...viewport.children] as HTMLElement[];
+ const end = bar.querySelector(".scrollable-bar-edge--end > button") as HTMLButtonElement;
+ return { block, bar, viewport, titles, end };
+}
+
+function isOverflowing(bar: Element) {
+ return bar.classList.contains("scrollable-bar--overflowing");
+}
+
+/** Whether all of `title` shows in `viewport`. */
+function isShown(title: Element, viewport: Element) {
+ const rect = title.getBoundingClientRect();
+ const box = viewport.getBoundingClientRect();
+ return rect.left >= box.left - 0.5 && rect.right <= box.right + 0.5;
+}
+
/** The radii of the top-left, top-right, bottom-right and bottom-left corners. */
function cornersOf(element: Element | null | undefined) {
if (!element) {
@@ -53,7 +99,7 @@ function textHeightOf(element: Element) {
/** Where the titles of a tabs block sit around the panel of its first tab, and their corners. */
function measure(block: Element | null, alignment: TabAlignment) {
expect(block).not.toBeNull();
- const titles = [...block?.querySelectorAll(":scope > .trilium-tab > .trilium-tab-title") ?? []];
+ const titles = [...block?.querySelectorAll(".trilium-tabs-bar .trilium-tab-title") ?? []];
const panel = block?.querySelector(".trilium-tab--active > .trilium-tab-panel");
const panelRect = panel?.getBoundingClientRect();
expect(titles).toHaveLength(3);
@@ -107,7 +153,7 @@ describe("tabs layout styles", () => {
container.innerHTML = tabsHtml(attribute);
document.body.appendChild(container);
onTestFinished(() => container.remove());
- applyTabs(container, { placeholder: "Tab title" });
+ applyTabs(container, OPTIONS);
const block = container.querySelector(".trilium-tabs");
expect(measure(block, alignment), alignment).toEqual(EXPECTED[alignment]);
@@ -135,7 +181,7 @@ describe("tabs layout styles", () => {
container.innerHTML = html;
document.body.appendChild(container);
onTestFinished(() => container.remove());
- applyTabs(container, { placeholder: "Tab title" });
+ applyTabs(container, OPTIONS);
const editor = await createTestEditor([Essentials, Paragraph, Tabs]);
const editable = editor.ui.view.editable.element as HTMLElement;
@@ -220,4 +266,78 @@ describe("tabs layout styles", () => {
.toEqual(["rgb(12, 34, 56)", "0s"]);
await expect.poll(outlines).toEqual(["rgb(65, 43, 21)", "rgba(0, 0, 0, 0)"]);
});
+
+ it("keeps overflowing titles on one scrolling row and rounds the panel corners", async () => {
+ const editor = await createTestEditor([Essentials, Paragraph, Tabs]);
+ const editable = editor.ui.view.editable.element as HTMLElement;
+ editable.style.width = "400px";
+
+ for (const alignment of ["top", "bottom"] as const) {
+ const html = manyTabsHtml(alignment);
+ editor.setData(html);
+ for (const root of [renderSaved(html).container, editable]) {
+ const { block, bar, viewport, titles } = barOf(root);
+ await expect.poll(() => isOverflowing(bar), alignment).toBe(true);
+ const rects = titles.map(title => title.getBoundingClientRect());
+ const lowestTop = Math.max(...rects.map(rect => rect.top));
+ const highestBottom = Math.min(...rects.map(rect => rect.bottom));
+ expect(lowestTop, alignment).toBeLessThan(highestBottom);
+ expect(viewport.scrollWidth).toBeGreaterThan(viewport.clientWidth);
+ const panel = block.querySelector(".trilium-tab--active > .trilium-tab-panel");
+ expect(cornersOf(panel), alignment).toBe("8px 8px 8px 8px");
+ }
+ }
+ });
+
+ it("scrolls the titles with the buttons, and reveals the title of the shown tab", async () => {
+ document.body.classList.add("motion-disabled");
+ onTestFinished(() => document.body.classList.remove("motion-disabled"));
+
+ const saved = barOf(renderSaved(manyTabsHtml()).container);
+ saved.end.click();
+ expect(saved.viewport.scrollLeft).toBeGreaterThan(0);
+ saved.titles[9].click();
+ expect(isShown(saved.titles[9], saved.viewport)).toBe(true);
+ saved.titles[9].dispatchEvent(new KeyboardEvent("keydown", { key: "Home", bubbles: true }));
+ expect(document.activeElement).toBe(saved.titles[0]);
+ expect(saved.viewport.scrollLeft).toBe(0);
+
+ const editor = await createTestEditor([Essentials, Paragraph, Tabs]);
+ const editable = editor.ui.view.editable.element as HTMLElement;
+ editable.style.width = "400px";
+ editor.setData(manyTabsHtml());
+ const edited = barOf(editable);
+ const tabs = editor.model.document.getRoot()?.getChild(0) as ModelElement;
+ const selectPanel = (index: number) => editor.model.change(writer => {
+ const tab = tabs.getChild(index) as ModelElement;
+ writer.setSelection(tab.getChild(1) as ModelElement, 0);
+ });
+ await expect.poll(() => isOverflowing(edited.bar)).toBe(true);
+ edited.end.click();
+ expect(edited.viewport.scrollLeft).toBeGreaterThan(0);
+
+ selectPanel(9);
+ expect(isShown(edited.titles[9], edited.viewport)).toBe(true);
+ selectPanel(0);
+ expect(edited.viewport.scrollLeft).toBe(0);
+ selectPanel(9);
+
+ editor.execute("moveTab", { target: "first" });
+ expect(edited.viewport.scrollLeft).toBe(0);
+ expect(edited.viewport.firstElementChild?.textContent).toBe("Step 10 of the guide");
+ });
+
+ it("stops the title bars of saved content on dispose, and starts them on the next call", () => {
+ const { container, dispose } = renderSaved(manyTabsHtml());
+ const { bar } = barOf(container);
+ expect(isOverflowing(bar)).toBe(true);
+
+ dispose();
+ expect(isOverflowing(bar)).toBe(false);
+
+ const disposeAgain = applyTabs(container, OPTIONS);
+ onTestFinished(disposeAgain);
+ expect(isOverflowing(bar)).toBe(true);
+ expect(container.querySelectorAll(".trilium-tabs-bar")).toHaveLength(1);
+ });
});
diff --git a/packages/ckeditor5/src/plugins/tabs/tabs_read_only.spec.ts b/packages/ckeditor5/src/plugins/tabs/tabs_read_only.spec.ts
index 5c23e15a5f..f75c9ea8d4 100644
--- a/packages/ckeditor5/src/plugins/tabs/tabs_read_only.spec.ts
+++ b/packages/ckeditor5/src/plugins/tabs/tabs_read_only.spec.ts
@@ -1,14 +1,15 @@
import { ClassicEditor, Essentials, Paragraph } from "ckeditor5";
import { describe, expect, it } from "vitest";
-import { applyTabs, revealFragment, revealTab } from "./tabs_read_only.js";
+import { applyTabs, getTabTitle, revealFragment, revealTab } from "./tabs_read_only.js";
const PLACEHOLDER = "Tab title";
+const OPTIONS = { placeholder: PLACEHOLDER, scrollLabels: { start: "Back", end: "Next" } };
function renderTabs(html: string) {
const container = document.createElement("div");
container.innerHTML = html;
- applyTabs(container, { placeholder: PLACEHOLDER });
+ applyTabs(container, OPTIONS);
return container;
}
@@ -25,7 +26,7 @@ function titleOf(container: HTMLElement, text: string) {
}
function activeTitles(container: HTMLElement) {
- return [...container.querySelectorAll(".trilium-tab--active > .trilium-tab-title")]
+ return [...container.querySelectorAll(".trilium-tab-title--active")]
.map(title => title.textContent);
}
@@ -55,6 +56,31 @@ describe("applyTabs", () => {
expect(new Set([...titles, ...panels].map(element => element.id)).size).toBe(4);
});
+ it("moves the titles into a title bar at the start of the block, in order", () => {
+ const container = renderTabs(
+ `<div class="trilium-tabs">${tab("A", "<p>a</p>")}${tab("B", "<p>b</p>")}</div>`
+ );
+ const block = container.querySelector(".trilium-tabs");
+ const bar = block?.firstElementChild;
+ expect(bar?.className).toBe("scrollable-bar trilium-tabs-bar");
+ expect([...bar?.querySelectorAll(":scope > .scrollable-bar-edge > button") ?? []]
+ .map(button => button.getAttribute("aria-label"))).toEqual(["Back", "Next"]);
+ expect([...bar?.querySelector(".scrollable-bar-viewport")?.children ?? []]
+ .map(title => title.textContent)).toEqual(["A", "B"]);
+
+ const sections = [...block?.querySelectorAll(":scope > .trilium-tab") ?? []];
+ expect(sections).toHaveLength(2);
+ for (const [index, section] of sections.entries()) {
+ const panel = section.firstElementChild as HTMLElement | null;
+ const title = getTabTitle(section);
+ expect([...section.children]).toEqual([panel]);
+ expect(title?.textContent).toBe(["A", "B"][index]);
+ for (const element of [title, panel]) {
+ expect(element?.style.getPropertyValue("--trilium-tab-index")).toBe(String(index));
+ }
+ }
+ });
+
it("switches tabs on click, Enter and Space", () => {
const container = renderTabs(
`<div class="trilium-tabs">${tab("A", "")}${tab("B", "")}${tab("C", "")}</div>`
@@ -96,7 +122,7 @@ describe("applyTabs", () => {
expect(document.activeElement).toBe(titleOf(container, "A"));
titleOf(container, "B").click();
- applyTabs(container, { placeholder: PLACEHOLDER });
+ applyTabs(container, OPTIONS);
expect(activeTitles(container)).toEqual(["B"]);
press(titleOf(container, "B"), "ArrowRight");
expect(activeTitles(container)).toEqual(["C"]);
diff --git a/packages/ckeditor5/src/plugins/tabs/tabs_read_only.ts b/packages/ckeditor5/src/plugins/tabs/tabs_read_only.ts
index aa1432de7e..b3fff58805 100644
--- a/packages/ckeditor5/src/plugins/tabs/tabs_read_only.ts
+++ b/packages/ckeditor5/src/plugins/tabs/tabs_read_only.ts
@@ -1,99 +1,51 @@
import type { Editor } from "ckeditor5";
+import {
+ attachScrollableBar, createScrollableBar, type ScrollableBar, type ScrollableBarLabels
+} from "../scrollable_bar.js";
import { CLASSES } from "./constants.js";
import type TabsEditing from "./tabs_editing.js";
export interface ApplyTabsOptions {
/** The text a title without text shows, the editor's "Tab title" placeholder. */
placeholder: string;
+ /** The labels of the buttons that scroll the titles, the editor's. */
+ scrollLabels: ScrollableBarLabels;
}
/**
- * 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.
+ * Turns the saved tabs blocks in `container` into working tabs outside the editor: the titles of
+ * each block move into a scrollable title bar and the first tab shows. A click on a title, Enter or
+ * Space shows that tab and scrolls its title into view. 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 only types from CKEditor, so pages that only display content can load it.
+ * Returns a function that stops the title bars that this call started. The module imports only
+ * types 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 (activators.has(block)) {
- continue;
+export function applyTabs(container: ParentNode, { placeholder, scrollLabels }: ApplyTabsOptions) {
+ const blocks = [...container.querySelectorAll<HTMLElement>(`.${CLASSES.tabs}`)];
+ for (const block of blocks) {
+ if (!tabsBlocks.has(block)) {
+ setUpBlock(block, placeholder, scrollLabels);
}
+ }
- 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 `&nbsp;`.
- 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;
+ // After every block is built, so that only the first measurement lays out the page.
+ const started: TabsBlock[] = [];
+ for (const block of blocks) {
+ const tabsBlock = tabsBlocks.get(block);
+ if (tabsBlock && !tabsBlock.scrollableBar) {
+ tabsBlock.scrollableBar = attachScrollableBar(tabsBlock.bar, tabsBlock.viewport);
+ started.push(tabsBlock);
}
+ }
- 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));
- }
- };
- activators.set(block, activate);
- 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();
- });
+ return () => {
+ for (const tabsBlock of started.splice(0)) {
+ tabsBlock.scrollableBar?.disconnect();
+ tabsBlock.scrollableBar = undefined;
}
- activate(titles[0]);
- }
+ };
}
/**
@@ -113,14 +65,23 @@ export function revealTab(element: Element) {
let tab = element.closest(`.${CLASSES.tab}`);
while (tab) {
const block = tab.parentElement;
- const title = tab.querySelector<HTMLElement>(`:scope > .${CLASSES.tabTitle}`);
+ const title = sectionTitles.get(tab);
if (block && title) {
- activators.get(block)?.(title);
+ tabsBlocks.get(block)?.activate(title);
}
tab = block?.closest(`.${CLASSES.tab}`) ?? null;
}
}
+/**
+ * Returns the title of `section`, a saved tab, from the title bar where {@link applyTabs} moved it
+ * or from the section itself.
+ */
+export function getTabTitle(section: Element): HTMLElement | null {
+ return sectionTitles.get(section)
+ ?? section.querySelector<HTMLElement>(`:scope > .${CLASSES.tabTitle}`);
+}
+
/**
* Returns the element that the URL fragment `hash` (`#id`, percent-encoded) names, after showing
* every tab that encloses it, or `null` when no element has that ID.
@@ -152,6 +113,116 @@ function getEditor(element: Element): Editor | null {
return null;
}
-/** Shows the tab of the given title, keyed by the tabs block that {@link applyTabs} set up. */
-const activators = new WeakMap<HTMLElement, (title: HTMLElement) => void>();
+interface TabsBlock {
+ /** Shows the tab of `title` and scrolls the title into view. */
+ activate(title: HTMLElement): void;
+ bar: HTMLElement;
+ viewport: HTMLElement;
+ /** The title bar while it scrolls, between {@link applyTabs} and its returned function. */
+ scrollableBar?: ScrollableBar;
+}
+
+/**
+ * Moves the titles of `block` into a title bar at its start, links each title to its panel and
+ * shows the first tab.
+ */
+function setUpBlock(block: HTMLElement, placeholder: string, scrollLabels: ScrollableBarLabels) {
+ const tabs: { section: HTMLElement; title: HTMLElement; panel: HTMLElement }[] = [];
+ for (const section of block.querySelectorAll<HTMLElement>(`:scope > .${CLASSES.tab}`)) {
+ const title = section.querySelector<HTMLElement>(`:scope > .${CLASSES.tabTitle}`);
+ const panel = section.querySelector<HTMLElement>(`:scope > .${CLASSES.tabPanel}`);
+ if (title && panel) {
+ tabs.push({ section, title, panel });
+ }
+ }
+ if (!tabs.length) {
+ return;
+ }
+
+ const { bar, viewport } = createScrollableBar(block.ownerDocument, scrollLabels);
+ bar.classList.add(CLASSES.titleBar);
+ for (const [index, { section, title, panel }] of tabs.entries()) {
+ // CKEditor saves an empty title as `&nbsp;`.
+ 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);
+
+ // A printout puts each title back above its panel.
+ title.style.setProperty(TAB_INDEX_PROPERTY, String(index));
+ panel.style.setProperty(TAB_INDEX_PROPERTY, String(index));
+ viewport.append(title);
+ sectionTitles.set(section, title);
+ }
+ block.prepend(bar);
+
+ const titles = tabs.map(({ title }) => title);
+ const tabsBlock: TabsBlock = {
+ bar,
+ viewport,
+ activate(activeTitle) {
+ for (const { section, title } of tabs) {
+ const isActive = title === activeTitle;
+ section.classList.toggle(CLASSES.activeTab, isActive);
+ title.classList.toggle(CLASSES.activeTitle, isActive);
+ title.setAttribute("aria-expanded", String(isActive));
+ }
+ tabsBlock.scrollableBar?.reveal(activeTitle);
+ }
+ };
+ tabsBlocks.set(block, tabsBlock);
+
+ const focusAndActivate = (index: number) => {
+ const title = titles[(index + titles.length) % titles.length];
+ title.focus({ preventScroll: true });
+ tabsBlock.activate(title);
+ };
+ for (const [index, title] of titles.entries()) {
+ title.addEventListener("click", () => tabsBlock.activate(title));
+ title.addEventListener("keydown", (e) => {
+ const step = getComputedStyle(block).direction === "rtl" ? -1 : 1;
+ switch (e.key) {
+ case "Enter":
+ case " ":
+ tabsBlock.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();
+ });
+ }
+ tabsBlock.activate(titles[0]);
+}
+
+/** The CSS property with the position of a title and its panel in their block. */
+const TAB_INDEX_PROPERTY = "--trilium-tab-index";
+
+/** The blocks that {@link applyTabs} set up. */
+const tabsBlocks = new WeakMap<HTMLElement, TabsBlock>();
+
+/** The title of each tab that {@link applyTabs} moved into a title bar, keyed by its section. */
+const sectionTitles = new WeakMap<Element, HTMLElement>();
let lastTabId = 0;
diff --git a/packages/ckeditor5/src/plugins/tabs/tabs_title_bar.ts b/packages/ckeditor5/src/plugins/tabs/tabs_title_bar.ts
new file mode 100644
index 0000000000..8f6c6427a0
--- /dev/null
+++ b/packages/ckeditor5/src/plugins/tabs/tabs_title_bar.ts
@@ -0,0 +1,266 @@
+import {
+ type DowncastConversionApi,
+ type DowncastInsertEvent,
+ type DowncastRemoveEvent,
+ type MapperModelToViewPositionEvent,
+ type MapperViewToModelPositionEvent,
+ type ModelElement,
+ Plugin,
+ type ViewDowncastWriter,
+ type ViewElement,
+ type ViewNode,
+ type ViewPosition
+} from "ckeditor5";
+
+import {
+ attachScrollableBar, createScrollableBarEdge, SCROLLABLE_BAR_CLASSES, type ScrollableBar,
+ type ScrollableBarEdge
+} from "../scrollable_bar.js";
+import { CLASSES, ELEMENTS } from "./constants.js";
+
+/**
+ * The title bar of tabs blocks in the editing view: a scrollable bar that holds the title of every
+ * tab, above or below the panels. The model and the saved HTML keep each title inside its tab, so
+ * the plugin maps the positions of a tab between the title in the bar and the panel in the tab's
+ * section.
+ */
+export default class TabsTitleBar extends Plugin {
+
+ public static get pluginName() {
+ return "TabsTitleBar" as const;
+ }
+
+ /** The viewport of the title bar, keyed by the view element of the tabs block. */
+ private readonly viewports = new WeakMap<ViewElement, ViewElement>();
+
+ /** The view title of each tab, keyed by the view section of the tab. */
+ private readonly titles = new WeakMap<ViewElement, ViewElement>();
+
+ /**
+ * The title bars that scroll, keyed by their view element. The renderer can bind a DOM bar to
+ * a new view bar and reset its classes, so a scrolling bar belongs to both elements together.
+ */
+ private readonly bars = new Map<ViewElement, AttachedBar>();
+
+ /** The view title bars to attach to their DOM element after the next render. */
+ private readonly newBars = new Set<ViewElement>();
+
+ /** The view titles to scroll into view after the next render. */
+ private readonly pendingReveals = new Set<ViewElement>();
+
+ public init(): void {
+ this.registerPositionMapping();
+ this.registerTitleConversion();
+ this.listenTo(this.editor.editing.view, "render", () => {
+ this.updateBars();
+ this.revealPendingTitles();
+ }, { priority: "low" });
+ }
+
+ public override destroy(): void {
+ for (const { scrollableBar } of this.bars.values()) {
+ scrollableBar.disconnect();
+ }
+ this.bars.clear();
+ super.destroy();
+ }
+
+ /** Adds an empty title bar to `tabs`, the editing-view element of a tabs block. */
+ public addBar(writer: ViewDowncastWriter, tabs: ViewElement) {
+ const t = this.editor.t;
+ const bar = writer.createContainerElement("div", {
+ class: `${SCROLLABLE_BAR_CLASSES.bar} ${CLASSES.titleBar}`
+ });
+ const viewport = writer.createContainerElement("div", {
+ class: SCROLLABLE_BAR_CLASSES.viewport
+ });
+ writer.insert(writer.createPositionAt(bar, 0), [
+ createEdge(writer, "start", t("Scroll to the previous tabs")),
+ viewport,
+ createEdge(writer, "end", t("Scroll to the next tabs"))
+ ]);
+ writer.insert(writer.createPositionAt(tabs, "end"), bar);
+ this.viewports.set(tabs, viewport);
+ this.newBars.add(bar);
+ }
+
+ /**
+ * Scrolls the title bar of `title`, the editing-view element of a title, to show the whole
+ * title after the next render. Rendering waits for the end of a model change block, so a
+ * title that the change converts has no DOM element before.
+ */
+ public revealTitleAfterRender(title: ViewElement) {
+ this.pendingReveals.add(title);
+ }
+
+ /**
+ * Maps the positions in a tab: offset 0 is in the title bar, before the tab's title, and the
+ * other offsets are in the tab's section. In a tabs block, only the sections count.
+ */
+ private registerPositionMapping() {
+ const editing = this.editor.editing;
+ const view = editing.view;
+ const model = this.editor.model;
+
+ // A tabs block and a tab convert before the positions inside them are mapped.
+ editing.mapper.on<MapperModelToViewPositionEvent>("modelToViewPosition", (_evt, data) => {
+ const { parent, offset } = data.modelPosition;
+ if (parent.is("element", ELEMENTS.tabs)) {
+ const tabs = data.mapper.toViewElement(parent) as ViewElement;
+ data.viewPosition = this.getSectionPosition(tabs, offset);
+ } else if (parent.is("element", ELEMENTS.tab)) {
+ const section = data.mapper.toViewElement(parent) as ViewElement;
+ data.viewPosition = offset === 0
+ ? this.getTitlePosition(section)
+ : view.createPositionAt(section, offset - 1);
+ }
+ });
+
+ editing.mapper.on<MapperViewToModelPositionEvent>("viewToModelPosition", (_evt, data) => {
+ const { parent, offset } = data.viewPosition;
+ if (!parent.is("element")) {
+ return;
+ }
+ const modelParent = data.mapper.toModelElement(parent);
+ if (modelParent?.is("element", ELEMENTS.tabs)) {
+ const sections = [ ...parent.getChildren() ].slice(0, offset).filter(isSection);
+ data.modelPosition = model.createPositionAt(modelParent, sections.length);
+ } else if (modelParent?.is("element", ELEMENTS.tab)) {
+ const modelOffset = Math.min(offset + 1, modelParent.maxOffset);
+ data.modelPosition = model.createPositionAt(modelParent, modelOffset);
+ }
+ });
+ }
+
+ /**
+ * Keeps the view title of each tab known by its section, and removes it from the title bar
+ * together with the title or the tab.
+ */
+ private registerTitleConversion() {
+ const dispatcher = this.editor.editing.downcastDispatcher;
+
+ // The section of a tab converts before its title, which converts at the normal priority.
+ dispatcher.on<DowncastInsertEvent<ModelElement>>(`insert:${ELEMENTS.tabTitle}`,
+ (_evt, data, { mapper }) => {
+ const tab = data.item.parent as ModelElement;
+ const section = mapper.toViewElement(tab) as ViewElement;
+ this.titles.set(section, mapper.toViewElement(data.item) as ViewElement);
+ }, { priority: "low" });
+
+ dispatcher.on<DowncastRemoveEvent>(`remove:${ELEMENTS.tab}`, (_evt, data, api) => {
+ const { mapper, writer } = api;
+ const start = mapper.toViewPosition(data.position);
+ const end = mapper.toViewPosition(data.position.getShiftedBy(data.length), {
+ isPhantom: true
+ });
+ for (const section of writer.createRange(start, end).getItems({ shallow: true })) {
+ this.removeTitle(section as ViewElement, api);
+ }
+ }, { priority: "high" });
+
+ // A title is outside the section of its tab, so this converter replaces the default one.
+ dispatcher.on<DowncastRemoveEvent>(`remove:${ELEMENTS.tabTitle}`, (evt, data, api) => {
+ const section = api.mapper.toViewElement(data.position.parent as ModelElement);
+ this.removeTitle(section as ViewElement, api);
+ evt.stop();
+ }, { priority: "high" });
+ }
+
+ /**
+ * The position before the section at `offset` among the sections of `tabs`, or after the last
+ * section or the title bar.
+ */
+ private getSectionPosition(tabs: ViewElement, offset: number): ViewPosition {
+ const view = this.editor.editing.view;
+ const sections = [ ...tabs.getChildren() ].filter(isSection);
+ if (offset < sections.length) {
+ return view.createPositionBefore(sections[offset]);
+ }
+ const viewport = this.viewports.get(tabs) as ViewElement;
+ return view.createPositionAfter(sections.at(-1) ?? viewport.parent as ViewElement);
+ }
+
+ /** The position for the title of the tab of `section`: after the title of the previous tab. */
+ private getTitlePosition(section: ViewElement): ViewPosition {
+ const view = this.editor.editing.view;
+ for (let node = section.previousSibling; node; node = node.previousSibling) {
+ const title = this.titles.get(node as ViewElement);
+ if (title) {
+ return view.createPositionAfter(title);
+ }
+ }
+ const viewport = this.viewports.get(section.parent as ViewElement) as ViewElement;
+ return view.createPositionAt(viewport, 0);
+ }
+
+ private removeTitle(section: ViewElement, { mapper, writer }: DowncastConversionApi) {
+ const title = this.titles.get(section);
+ /* v8 ignore next 3 -- every converted tab has its title in the title bar */
+ if (!title) {
+ return;
+ }
+ this.titles.delete(section);
+ const removed = writer.remove(writer.createRangeOn(title));
+ for (const item of writer.createRangeIn(removed).getItems()) {
+ if (item.is("element")) {
+ mapper.unbindViewElement(item, { defer: true });
+ }
+ }
+ }
+
+ /**
+ * Starts scrolling the title bars that rendered, and stops those whose view element left the
+ * view or now renders to another DOM element.
+ */
+ private updateBars() {
+ const domConverter = this.editor.editing.view.domConverter;
+ for (const [ viewBar, { element, scrollableBar } ] of this.bars) {
+ if (domConverter.mapViewToDom(viewBar) !== element) {
+ scrollableBar.disconnect();
+ this.bars.delete(viewBar);
+ this.newBars.add(viewBar);
+ }
+ }
+
+ for (const viewBar of this.newBars) {
+ const element = domConverter.mapViewToDom(viewBar);
+ if (element) {
+ const viewport = element.querySelector(
+ `:scope > .${SCROLLABLE_BAR_CLASSES.viewport}`) as HTMLElement;
+ const scrollableBar = attachScrollableBar(element, viewport);
+ this.bars.set(viewBar, { element, scrollableBar });
+ }
+ }
+ this.newBars.clear();
+ }
+
+ private revealPendingTitles() {
+ const domConverter = this.editor.editing.view.domConverter;
+ for (const title of this.pendingReveals) {
+ const domTitle = domConverter.mapViewToDom(title);
+ const bar = this.bars.get(title.parent?.parent as ViewElement);
+ /* v8 ignore next 3 -- only a title that left the view before the render has neither */
+ if (domTitle && bar) {
+ bar.scrollableBar.reveal(domTitle);
+ }
+ }
+ this.pendingReveals.clear();
+ }
+
+}
+
+interface AttachedBar {
+ /** The DOM element that the view bar rendered to when it started scrolling. */
+ element: HTMLElement;
+ scrollableBar: ScrollableBar;
+}
+
+/** An edge of the title bar with its scroll button, drawn by the scrollable bar module. */
+function createEdge(writer: ViewDowncastWriter, edge: ScrollableBarEdge, label: string) {
+ return writer.createUIElement("div", undefined, domDocument =>
+ createScrollableBarEdge(domDocument, edge, label));
+}
+
+function isSection(node: ViewNode): node is ViewElement {
+ return node.is("element", "section") && node.hasClass(CLASSES.tab);
+}
diff --git a/packages/ckeditor5/src/theme/scrollable_bar.css b/packages/ckeditor5/src/theme/scrollable_bar.css
new file mode 100644
index 0000000000..f646873456
--- /dev/null
+++ b/packages/ckeditor5/src/theme/scrollable_bar.css
@@ -0,0 +1,73 @@
+:where(:root) {
+ --scrollable-bar-button-color: currentColor;
+ --scrollable-bar-edge-width: 36px;
+}
+
+@media (pointer: coarse) {
+ :where(:root) {
+ --scrollable-bar-edge-width: 48px;
+ }
+}
+
+.scrollable-bar {
+ display: flex;
+ min-width: 0;
+
+ & > .scrollable-bar-viewport {
+ display: flex;
+ flex: 1 1 auto;
+ min-width: 0;
+ overflow-x: auto;
+ overflow-y: hidden;
+ overscroll-behavior-x: contain;
+ scrollbar-width: none;
+ }
+
+ & > .scrollable-bar-edge {
+ display: none;
+ flex: none;
+ align-items: center;
+ justify-content: center;
+ min-width: var(--scrollable-bar-edge-width);
+ cursor: pointer;
+ touch-action: manipulation;
+ user-select: none;
+
+ &:has(> .scrollable-bar-button:disabled) {
+ cursor: default;
+ }
+ }
+
+ &.scrollable-bar--overflowing > .scrollable-bar-edge {
+ display: flex;
+ }
+
+ & > .scrollable-bar-edge > .scrollable-bar-button {
+ --icon-button-size: 28px;
+ --icon-button-icon-ratio: .75;
+
+ flex: none;
+ }
+
+ &:dir(rtl) > .scrollable-bar-edge > .scrollable-bar-button::before {
+ scale: -1 1;
+ }
+}
+
+/* Shared pages draw the buttons without the application's `icon-action` rules. */
+:where(.scrollable-bar-edge > .scrollable-bar-button) {
+ margin: 0;
+ border: 0;
+ padding: 0;
+ width: 28px;
+ height: 28px;
+ background: none;
+ color: var(--scrollable-bar-button-color);
+ font-size: 20px;
+ cursor: pointer;
+
+ &:disabled {
+ opacity: .35;
+ cursor: default;
+ }
+}
diff --git a/packages/ckeditor5/src/theme/tabs.css b/packages/ckeditor5/src/theme/tabs.css
index 9e86fa4e48..6f2f3c90a2 100644
--- a/packages/ckeditor5/src/theme/tabs.css
+++ b/packages/ckeditor5/src/theme/tabs.css
@@ -13,20 +13,20 @@
--_tabs-border-radius: 8px;
--_tabs-active-title-color: var(--main-text-color, currentColor);
--_tabs-title-color: color-mix(in srgb, var(--_tabs-active-title-color), transparent 50%);
+ --scrollable-bar-button-color: var(--_tabs-title-color);
display: flex;
- flex-wrap: wrap;
- align-items: flex-end;
- gap: 0 var(--_tabs-delimiter-width);
+ flex-direction: column;
margin: 1em 0;
border-radius: var(--_tabs-border-radius);
- & > .trilium-tab {
- display: contents;
+ & > .trilium-tabs-bar > .scrollable-bar-viewport {
+ align-items: flex-end;
+ gap: 0 var(--_tabs-delimiter-width);
}
- & > .trilium-tab > .trilium-tab-title {
- order: 0;
+ & > .trilium-tabs-bar > .scrollable-bar-viewport > .trilium-tab-title {
+ flex: none;
box-sizing: border-box;
min-width: 4em;
max-width: 30%;
@@ -44,15 +44,25 @@
color: var(--_tabs-active-title-color);
}
+ &.trilium-tab-title--active {
+ margin-bottom: 0;
+ padding-bottom: calc(6px + var(--_tabs-delimiter-width));
+ background: var(--_tabs-background);
+ color: var(--_tabs-active-title-color);
+ cursor: text;
+ }
+
body.mobile & {
max-width: 45%;
}
}
+ & > .trilium-tab {
+ display: contents;
+ }
+
& > .trilium-tab > .trilium-tab-panel {
display: none;
- order: 1;
- flex: 1 0 100%;
min-width: 0;
padding: .75rem 1rem;
border-radius: 0 var(--_tabs-border-radius) var(--_tabs-border-radius);
@@ -67,45 +77,69 @@
}
}
- & > .trilium-tab.trilium-tab--active {
- & > .trilium-tab-title {
- margin-bottom: 0;
- padding-bottom: calc(6px + var(--_tabs-delimiter-width));
- background: var(--_tabs-background);
- color: var(--_tabs-active-title-color);
- cursor: text;
- }
+ & > .trilium-tab.trilium-tab--active > .trilium-tab-panel {
+ display: block;
+ }
- & > .trilium-tab-panel {
- display: block;
- }
+ &:has(> .trilium-tabs-bar.scrollable-bar--overflowing) > .trilium-tab > .trilium-tab-panel {
+ border-radius: var(--_tabs-border-radius);
}
&[data-trilium-tab-alignment="bottom"] {
- align-items: flex-start;
-
- & > .trilium-tab > .trilium-tab-title {
+ & > .trilium-tabs-bar {
order: 1;
- margin: var(--_tabs-delimiter-width) 0 0;
- border-radius: 0 0 var(--_tabs-border-radius) var(--_tabs-border-radius);
+ }
+
+ & > .trilium-tabs-bar > .scrollable-bar-viewport {
+ align-items: flex-start;
+
+ & > .trilium-tab-title {
+ margin: var(--_tabs-delimiter-width) 0 0;
+ border-radius: 0 0 var(--_tabs-border-radius) var(--_tabs-border-radius);
+ }
+
+ & > .trilium-tab-title.trilium-tab-title--active {
+ margin-top: 0;
+ padding-top: calc(6px + var(--_tabs-delimiter-width));
+ padding-bottom: 6px;
+ }
}
& > .trilium-tab > .trilium-tab-panel {
- order: 0;
border-radius: var(--_tabs-border-radius);
border-bottom-left-radius: 0;
}
- & > .trilium-tab.trilium-tab--active > .trilium-tab-title {
- margin-top: 0;
- padding-top: calc(6px + var(--_tabs-delimiter-width));
- padding-bottom: 6px;
+ &:has(> .trilium-tabs-bar.scrollable-bar--overflowing)
+ > .trilium-tab > .trilium-tab-panel {
+ border-bottom-left-radius: var(--_tabs-border-radius);
}
+ }
+ }
+}
- /* The editor's widget UI elements stay at the end of the title row. */
- & > :not(.trilium-tab) {
- order: 1;
- }
+@media print {
+ .trilium-tabs:has(> .trilium-tabs-bar) {
+ display: flex;
+ flex-direction: column;
+
+ & > .trilium-tabs-bar,
+ & > .trilium-tabs-bar > .scrollable-bar-viewport,
+ & > .trilium-tab {
+ display: contents;
+ }
+
+ & > .trilium-tabs-bar > .scrollable-bar-edge {
+ display: none;
+ }
+
+ /* `applyTabs()` sets `--trilium-tab-index` on each title and panel. */
+ & > .trilium-tabs-bar > .scrollable-bar-viewport > .trilium-tab-title {
+ order: calc(var(--trilium-tab-index) * 2);
+ }
+
+ & > .trilium-tab > .trilium-tab-panel {
+ order: calc(var(--trilium-tab-index) * 2 + 1);
}
}
}
@@ -123,7 +157,7 @@
}
}
-.ck-editor__editable .trilium-tabs > .trilium-tab > .trilium-tab-title {
+.ck-editor__editable .trilium-tab-title {
/* CKEditor positions the placeholder absolutely, so it does not size the title. */
&.ck-placeholder::after {
content: attr(data-placeholder);
@@ -135,7 +169,7 @@
}
}
-.ck-content:not(.ck-editor__editable) .trilium-tabs > .trilium-tab > .trilium-tab-title {
+.ck-content:not(.ck-editor__editable) .trilium-tabs-bar .trilium-tab-title {
&:focus-visible {
outline: 2px solid var(--input-focus-outline-color, var(--ck-color-focus-border, currentColor));
outline-offset: -2px;
diff --git a/packages/share-theme/src/index.spec.ts b/packages/share-theme/src/index.spec.ts
index afe5c1ad5d..42117b3b94 100644
--- a/packages/share-theme/src/index.spec.ts
+++ b/packages/share-theme/src/index.spec.ts
@@ -103,7 +103,8 @@ describe("share theme entry", () => {
it("enhances a text note's content and reveals the tab panel the address points to", () => {
document.body.className = "type-text";
- document.body.innerHTML = `<div id="content" data-tab-title-placeholder="Tab">`
+ document.body.innerHTML = `<div id="content" data-tab-title-placeholder="Tab"`
+ + ` data-tab-previous-label="Back" data-tab-next-label="On">`
+ `<blockquote><figure class="include-note"></figure></blockquote></div>`;
const panel = { scrollIntoView: vi.fn() };
mocks.revealFragment.mockReturnValue(panel);
@@ -117,7 +118,10 @@ describe("share theme entry", () => {
expect(mocks.applyTableScroll.mock.calls)
.toEqual([ [ content ], [ content?.querySelector(".include-note") ] ]);
expect(mocks.applyStickyTableHeaders.mock.calls).toEqual([ [ content ] ]);
- expect(mocks.applyTabs).toHaveBeenCalledWith(content, { placeholder: "Tab" });
+ expect(mocks.applyTabs).toHaveBeenCalledWith(content, {
+ placeholder: "Tab",
+ scrollLabels: { start: "Back", end: "On" }
+ });
expect(panel.scrollIntoView).toHaveBeenCalledOnce();
window.dispatchEvent(new Event("hashchange"));
@@ -160,7 +164,10 @@ describe("share theme entry", () => {
document.dispatchEvent(new Event("DOMContentLoaded"));
expect(mocks.applyTabs)
- .toHaveBeenCalledWith(document.getElementById("content"), { placeholder: "" });
+ .toHaveBeenCalledWith(document.getElementById("content"), {
+ placeholder: "",
+ scrollLabels: { start: "", end: "" }
+ });
mocks.applyTabs.mockClear();
document.body.className = "type-text";
diff --git a/packages/share-theme/src/index.ts b/packages/share-theme/src/index.ts
index ae7405b1c1..02f2a83034 100644
--- a/packages/share-theme/src/index.ts
+++ b/packages/share-theme/src/index.ts
@@ -23,6 +23,7 @@ import setupAppView from "./content/app_view.js";
import setupMermaid from "./content/mermaid.js";
import "virtual:code-themes.css";
import "@triliumnext/ckeditor5/src/theme/ck-content.css";
+import "@triliumnext/ckeditor5/src/theme/scrollable_bar.css";
import "@triliumnext/ckeditor5/src/theme/tabs.css";
import "@triliumnext/ckeditor5/src/theme/multicolumn.css";
import "@triliumnext/ckeditor5/src/theme/collapsible_blocks.css";
@@ -120,7 +121,11 @@ function setupStickyTableHeaders() {
function setupTabs() {
const content = document.getElementById("content");
if (content) {
- applyTabs(content, { placeholder: content.dataset.tabTitlePlaceholder ?? "" });
+ const { tabTitlePlaceholder, tabPreviousLabel, tabNextLabel } = content.dataset;
+ applyTabs(content, {
+ placeholder: tabTitlePlaceholder ?? "",
+ scrollLabels: { start: tabPreviousLabel ?? "", end: tabNextLabel ?? "" }
+ });
}
// The browser does not scroll to a fragment inside a hidden panel.
diff --git a/packages/share-theme/src/templates/page.ejs b/packages/share-theme/src/templates/page.ejs
index 472b49d1fd..3713c2e09a 100644
--- a/packages/share-theme/src/templates/page.ejs
+++ b/packages/share-theme/src/templates/page.ejs
@@ -71,7 +71,7 @@
</div>
<div id="right-pane">
<div id="main">
- <div id="content" class="<%= contentClasses %>"<% if (language.content) { %> lang="<%= language.content.lang %>" dir="<%= language.content.dir %>"<% } %> data-tab-title-placeholder="<%= t("share_theme.tab-title") %>">
+ <div id="content" class="<%= contentClasses %>"<% if (language.content) { %> lang="<%= language.content.lang %>" dir="<%= language.content.dir %>"<% } %> data-tab-title-placeholder="<%= t("share_theme.tab-title") %>" data-tab-previous-label="<%= t("share_theme.previous-tabs") %>" data-tab-next-label="<%= t("share_theme.next-tabs") %>">
<%- snippets["content:start"] %>
<% if (showTitle && titleIcon) { %>
<div id="title-row">