Skip to content

Build your personal knowledge base with Trilium Notes

feat(text): draft a tabs block for text notes

Claude0adc8668bb9d
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.json
index 0b06ff9864..5f0526e958 100644
--- a/apps/client/src/translations/en/translation.json
+++ b/apps/client/src/translations/en/translation.json
@@ -4361,7 +4361,16 @@
"more-actions": "More actions",
"drawing-canvas": "Drawing canvas",
"editable": "Editable",
- "insert-a-canvas-to-draw-on": "Insert a canvas to draw on."
+ "insert-a-canvas-to-draw-on": "Insert a canvas to draw on.",
+ "tabs": "Tabs",
+ "tab-title": "Tab title",
+ "tab-content": "Tab content",
+ "add-tab": "Add tab",
+ "remove-tab": "Remove tab",
+ "move-tab-left": "Move tab left",
+ "move-tab-right": "Move tab right",
+ "tabs-toolbar": "Tabs toolbar",
+ "insert-titled-tabs-that-show-one-panel-at-a-time": "Insert titled tabs that show one panel at a time."
},
"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/type_widgets/text/toolbar.ts b/apps/client/src/widgets/type_widgets/text/toolbar.ts
index a7a77b0214..33253d9530 100644
--- a/apps/client/src/widgets/type_widgets/text/toolbar.ts
+++ b/apps/client/src/widgets/type_widgets/text/toolbar.ts
@@ -105,7 +105,7 @@ export function buildClassicToolbar(multilineToolbar: boolean, aiAssistant: bool
"footnote",
{
...buildInsertGroup(),
- items: ["link", "linkEmbed", "bookmark", "internallink", "contentEmbed", "|", "collapsible", "math", "drawingCanvas", "mermaid", "horizontalLine", "pageBreak", "|", "dateTime", "specialCharacters", "emoji", "insertIcon"]
+ items: ["link", "linkEmbed", "bookmark", "internallink", "contentEmbed", "|", "collapsible", "tabs", "math", "drawingCanvas", "mermaid", "horizontalLine", "pageBreak", "|", "dateTime", "specialCharacters", "emoji", "insertIcon"]
},
"|",
buildAlignmentToolbar(),
@@ -176,7 +176,7 @@ export function buildFloatingToolbar(aiAssistant: boolean) {
"footnote",
{
...buildInsertGroup(),
- items: ["link", "linkEmbed", "bookmark", "internallink", "contentEmbed", "|", "collapsible", "math", "drawingCanvas", "mermaid", "horizontalLine", "pageBreak", "dateTime"]
+ items: ["link", "linkEmbed", "bookmark", "internallink", "contentEmbed", "|", "collapsible", "tabs", "math", "drawingCanvas", "mermaid", "horizontalLine", "pageBreak", "dateTime"]
},
"|",
buildAlignmentToolbar(),
diff --git a/packages/ckeditor5/src/icons/tabs.svg b/packages/ckeditor5/src/icons/tabs.svg
new file mode 100644
index 0000000000..3e621727a0
--- /dev/null
+++ b/packages/ckeditor5/src/icons/tabs.svg
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<svg viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg">
+ <path d="M2.6 16.4V5.2c0-.55.45-1 1-1h4.2c.55 0 1 .45 1 1v2.2h7.6c.55 0 1 .45 1 1v8c0 .55-.45 1-1 1H3.6c-.55 0-1-.45-1-1Z" fill="none" stroke="currentColor" stroke-width="1.2" stroke-linejoin="round"/>
+ <path d="M8.8 7.4V5.2c0-.55.45-1 1-1h3.6c.55 0 1 .45 1 1v2.2" fill="none" stroke="currentColor" stroke-width="1.2" stroke-linejoin="round"/>
+</svg>
diff --git a/packages/ckeditor5/src/plugins.ts b/packages/ckeditor5/src/plugins.ts
index 44382a9047..1f9d7aa576 100644
--- a/packages/ckeditor5/src/plugins.ts
+++ b/packages/ckeditor5/src/plugins.ts
@@ -31,6 +31,7 @@ import Kbd from "./plugins/keyboard_marker/keyboard_marker.js";
import Mermaid from "./plugins/mermaid/mermaid.js";
import Admonition from "./plugins/admonition/admonition.js";
import Collapsible from "./plugins/collapsible/collapsible.js";
+import Tabs from "./plugins/tabs/tabs.js";
import Footnotes from "./plugins/footnotes/footnotes.js";
import Math from "./plugins/math/math.js";
import AutoformatMath from "./plugins/math/autoformat_math.js";
@@ -134,6 +135,7 @@ const EXTERNAL_PLUGINS: typeof Plugin[] = [
Mermaid,
Admonition,
Collapsible,
+ Tabs,
Footnotes,
Math,
AutoformatMath
diff --git a/packages/ckeditor5/src/plugins/mention/slash_commands.ts b/packages/ckeditor5/src/plugins/mention/slash_commands.ts
index f1ce8e927b..af74c0a60f 100644
--- a/packages/ckeditor5/src/plugins/mention/slash_commands.ts
+++ b/packages/ckeditor5/src/plugins/mention/slash_commands.ts
@@ -40,6 +40,7 @@ import insertFootnoteIcon from "../../icons/insert-footnote.svg?raw";
import importMarkdownIcon from "../../icons/markdown-mark.svg?raw";
import mathIcon from "../../icons/math.svg?raw";
import noteIcon from "../../icons/note.svg?raw";
+import tabsIcon from "../../icons/tabs.svg?raw";
import internalLinkIcon from "../../icons/trilium.svg?raw";
import { ADMONITION_TYPE_NAMES, type AdmonitionType } from "../admonition/admonition_command.js";
import { getAdmonitionTitle } from "../admonition/admonition_ui.js";
@@ -362,6 +363,14 @@ export function buildTriliumSlashCommands(editor: Editor): SlashCommandDefinitio
icon: collapsibleIcon,
commandName: "collapsible"
},
+ {
+ id: "tabs",
+ title: t("Tabs"),
+ description: t("Insert titled tabs that show one panel at a time."),
+ aliases: [ "tab", "tabbed", "tab group", "panels", "variants" ],
+ icon: tabsIcon,
+ commandName: "tabs"
+ },
{
id: "footnote",
title: t("Footnote"),
diff --git a/packages/ckeditor5/src/plugins/tabs/constants.ts b/packages/ckeditor5/src/plugins/tabs/constants.ts
new file mode 100644
index 0000000000..edef6a74f0
--- /dev/null
+++ b/packages/ckeditor5/src/plugins/tabs/constants.ts
@@ -0,0 +1,19 @@
+/** Model element names of the tabs block. */
+export const ELEMENTS = {
+ tabs: "tabs",
+ tab: "tab",
+ tabTitle: "tabTitle",
+ tabPanel: "tabPanel"
+} as const;
+
+/** CSS classes of the saved HTML and the editing view. */
+export const CLASSES = {
+ tabs: "trilium-tabs",
+ tab: "trilium-tab",
+ tabTitle: "trilium-tab-title",
+ tabPanel: "trilium-tab-panel",
+ activeTab: "trilium-tab--active"
+} as const;
+
+/** Custom property that marks the editing-view widget element of a tabs block. */
+export const TABS_WIDGET_PROPERTY = "tabsWidget";
diff --git a/packages/ckeditor5/src/plugins/tabs/tabs.spec.ts b/packages/ckeditor5/src/plugins/tabs/tabs.spec.ts
new file mode 100644
index 0000000000..f63a30d0a2
--- /dev/null
+++ b/packages/ckeditor5/src/plugins/tabs/tabs.spec.ts
@@ -0,0 +1,146 @@
+import {
+ _getModelData as getModelData,
+ _setModelData as setModelData,
+ ClassicEditor,
+ Essentials,
+ type ModelElement,
+ Paragraph
+} from "ckeditor5";
+import { afterEach, beforeEach, describe, expect, it } from "vitest";
+
+import Tabs from "./tabs.js";
+
+const TWO_TABS =
+ "<div class=\"trilium-tabs\">" +
+ "<section class=\"trilium-tab\"><p class=\"trilium-tab-title\">Windows</p>" +
+ "<div class=\"trilium-tab-panel\"><p>Run the installer.</p></div></section>" +
+ "<section class=\"trilium-tab\"><p class=\"trilium-tab-title\">Linux</p>" +
+ "<div class=\"trilium-tab-panel\"><p>Use the package.</p></div></section>" +
+ "</div>";
+
+describe("Tabs", () => {
+ let domElement: HTMLDivElement;
+ let editor: ClassicEditor;
+
+ beforeEach(async () => {
+ domElement = document.createElement("div");
+ document.body.appendChild(domElement);
+ editor = await ClassicEditor.create(domElement, {
+ licenseKey: "GPL",
+ plugins: [Essentials, Paragraph, Tabs]
+ });
+ });
+
+ afterEach(() => {
+ domElement.remove();
+ return editor.destroy();
+ });
+
+ function model() {
+ return getModelData(editor.model, { withoutSelection: true });
+ }
+
+ function activeTitles() {
+ const root = editor.editing.view.getDomRoot();
+ return [...root?.querySelectorAll(".trilium-tab--active > .trilium-tab-title") ?? []]
+ .map(title => title.textContent);
+ }
+
+ function tabsElement() {
+ const tabs = editor.model.document.getRoot()?.getChild(0);
+ expect(tabs?.is("element", "tabs")).toBe(true);
+ return tabs as ModelElement;
+ }
+
+ it("round-trips the saved HTML through the model", () => {
+ editor.setData(TWO_TABS);
+
+ expect(model()).toBe(
+ "<tabs>" +
+ "<tab><tabTitle>Windows</tabTitle><tabPanel><paragraph>Run the installer.</paragraph></tabPanel></tab>" +
+ "<tab><tabTitle>Linux</tabTitle><tabPanel><paragraph>Use the package.</paragraph></tabPanel></tab>" +
+ "</tabs>"
+ );
+ expect(editor.getData()).toBe(TWO_TABS);
+ });
+
+ it("inserts two empty tabs and places the caret in the first title", () => {
+ setModelData(editor.model, "<paragraph>[]</paragraph>");
+
+ editor.execute("tabs");
+
+ expect(getModelData(editor.model)).toBe(
+ "<tabs>" +
+ "<tab><tabTitle>[]</tabTitle><tabPanel><paragraph></paragraph></tabPanel></tab>" +
+ "<tab><tabTitle></tabTitle><tabPanel><paragraph></paragraph></tabPanel></tab>" +
+ "</tabs>"
+ );
+ });
+
+ it("repairs tabs that lack a title or a panel and drops a block without tabs", () => {
+ editor.setData(
+ "<div class=\"trilium-tabs\">" +
+ "<section class=\"trilium-tab\"><div class=\"trilium-tab-panel\"><p>Body</p></div></section>" +
+ "<section class=\"trilium-tab\"><p class=\"trilium-tab-title\">Title</p></section>" +
+ "</div>" +
+ "<div class=\"trilium-tabs\"></div>"
+ );
+
+ expect(model()).toBe(
+ "<tabs>" +
+ "<tab><tabTitle></tabTitle><tabPanel><paragraph>Body</paragraph></tabPanel></tab>" +
+ "<tab><tabTitle>Title</tabTitle><tabPanel><paragraph></paragraph></tabPanel></tab>" +
+ "</tabs>"
+ );
+ });
+
+ it("shows the first tab, then whichever tab holds the selection", () => {
+ editor.setData(TWO_TABS);
+ expect(activeTitles()).toEqual(["Windows"]);
+
+ const linux = tabsElement().getChild(1) as ModelElement;
+ editor.model.change(writer => writer.setSelection(linux.getChild(1) as ModelElement, 0));
+ expect(activeTitles()).toEqual(["Linux"]);
+
+ editor.model.change(writer => writer.setSelection(editor.model.document.getRoot() as ModelElement, "end"));
+ expect(activeTitles()).toEqual(["Linux"]);
+ });
+
+ it("adds, moves and removes the tab holding the selection", () => {
+ editor.setData(TWO_TABS);
+ 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 => writer.insertText("macOS", editor.model.document.selection.getFirstPosition()));
+ expect(activeTitles()).toEqual(["macOS"]);
+
+ editor.execute("moveTabRight");
+ expect(editor.commands.get("moveTabRight")?.isEnabled).toBe(false);
+ expect(editor.getData()).toContain("Windows</p>");
+ expect(editor.getData().indexOf("Linux")).toBeLessThan(editor.getData().indexOf("macOS"));
+
+ editor.execute("removeTab");
+ expect(model()).not.toContain("macOS");
+ expect(activeTitles()).toEqual(["Linux"]);
+
+ editor.execute("removeTab");
+ editor.execute("removeTab");
+ expect(model()).toBe("<paragraph></paragraph>");
+ });
+
+ it("moves the caret from a title into its panel on Enter", () => {
+ editor.setData(TWO_TABS);
+ const windows = tabsElement().getChild(0) as ModelElement;
+ editor.model.change(writer => writer.setSelection(windows.getChild(0) as ModelElement, "end"));
+
+ editor.editing.view.document.fire("enter", {
+ preventDefault() {},
+ domEvent: new KeyboardEvent("keydown")
+ });
+
+ expect(getModelData(editor.model)).toContain(
+ "<tabTitle>Windows</tabTitle><tabPanel><paragraph>[]Run the installer.</paragraph></tabPanel>"
+ );
+ });
+});
diff --git a/packages/ckeditor5/src/plugins/tabs/tabs.ts b/packages/ckeditor5/src/plugins/tabs/tabs.ts
new file mode 100644
index 0000000000..bb51edd895
--- /dev/null
+++ b/packages/ckeditor5/src/plugins/tabs/tabs.ts
@@ -0,0 +1,39 @@
+import { Plugin } from "ckeditor5";
+
+import "../../theme/tabs.css";
+import TabsEditing from "./tabs_editing.js";
+import type { InsertTabCommand, InsertTabsCommand, MoveTabCommand, RemoveTabCommand } from "./tabs_commands.js";
+import TabsUI from "./tabs_ui.js";
+
+/**
+ * The tabs block: titled panels of block content, one of which shows at a time.
+ *
+ * This is a "glue" plugin which loads {@link TabsEditing} and {@link TabsUI}.
+ */
+export default class Tabs extends Plugin {
+
+ public static get requires() {
+ return [TabsEditing, TabsUI] as const;
+ }
+
+ public static get pluginName() {
+ return "Tabs" as const;
+ }
+
+}
+
+declare module "ckeditor5" {
+ interface PluginsMap {
+ [Tabs.pluginName]: Tabs;
+ [TabsEditing.pluginName]: TabsEditing;
+ [TabsUI.pluginName]: TabsUI;
+ }
+
+ interface CommandsMap {
+ tabs: InsertTabsCommand;
+ insertTab: InsertTabCommand;
+ removeTab: RemoveTabCommand;
+ moveTabLeft: MoveTabCommand;
+ moveTabRight: MoveTabCommand;
+ }
+}
diff --git a/packages/ckeditor5/src/plugins/tabs/tabs_commands.ts b/packages/ckeditor5/src/plugins/tabs/tabs_commands.ts
new file mode 100644
index 0000000000..6f46e65319
--- /dev/null
+++ b/packages/ckeditor5/src/plugins/tabs/tabs_commands.ts
@@ -0,0 +1,176 @@
+import { Command, type Editor, type ModelElement, type ModelWriter } from "ckeditor5";
+
+import { ELEMENTS } from "./constants.js";
+
+/**
+ * Inserts a tabs block with two empty tabs at the selection and places the caret in the first
+ * tab's title.
+ */
+export class InsertTabsCommand extends Command {
+
+ public override refresh(): void {
+ const model = this.editor.model;
+ const position = model.document.selection.getFirstPosition();
+ this.isEnabled = !!position && !!model.schema.findAllowedParent(position, ELEMENTS.tabs);
+ }
+
+ public override execute(): void {
+ const model = this.editor.model;
+
+ model.change(writer => {
+ const tabs = writer.createElement(ELEMENTS.tabs);
+ writer.append(createTab(writer), tabs);
+ writer.append(createTab(writer), tabs);
+ model.insertObject(tabs, null, null, { setSelection: "on" });
+
+ const firstTitle = getTitle(tabs.getChild(0) as ModelElement);
+ if (firstTitle) {
+ writer.setSelection(firstTitle, 0);
+ }
+ });
+ }
+}
+
+/**
+ * Adds a tab next to the one holding the selection and places the caret in its title. With
+ * the whole block selected, the tab goes at the end.
+ */
+export class InsertTabCommand extends Command {
+
+ public override refresh(): void {
+ this.isEnabled = !!getSelectedTabs(this.editor);
+ }
+
+ public override execute({ position = "after" }: { position?: "before" | "after" } = {}): void {
+ const editor = this.editor;
+ const tabs = getSelectedTabs(editor);
+ if (!tabs) {
+ return;
+ }
+ const currentTab = getSelectedTab(editor);
+
+ editor.model.change(writer => {
+ const tab = createTab(writer);
+ if (currentTab) {
+ writer.insert(tab, currentTab, position);
+ } else {
+ writer.insert(tab, tabs, "end");
+ }
+
+ const title = getTitle(tab);
+ if (title) {
+ writer.setSelection(title, 0);
+ }
+ });
+ }
+}
+
+/**
+ * Removes the tab holding the selection and moves the caret to the title of a neighboring tab.
+ * Removing the last tab removes the whole block.
+ */
+export class RemoveTabCommand extends Command {
+
+ public override refresh(): void {
+ this.isEnabled = !!getSelectedTab(this.editor);
+ }
+
+ public override execute(): void {
+ const editor = this.editor;
+ const tab = getSelectedTab(editor);
+ const tabs = tab?.parent;
+ if (!tab || !tabs?.is("element", ELEMENTS.tabs)) {
+ return;
+ }
+
+ editor.model.change(writer => {
+ if (tabs.childCount === 1) {
+ const paragraph = writer.createElement("paragraph");
+ writer.insert(paragraph, tabs, "after");
+ writer.remove(tabs);
+ writer.setSelection(paragraph, 0);
+ return;
+ }
+
+ const neighbor = (tab.nextSibling ?? tab.previousSibling) as ModelElement;
+ writer.remove(tab);
+
+ const title = getTitle(neighbor);
+ if (title) {
+ writer.setSelection(title, "end");
+ }
+ });
+ }
+}
+
+/** Swaps the tab holding the selection with its left or right neighbor. */
+export class MoveTabCommand extends Command {
+
+ private readonly direction: "left" | "right";
+
+ public constructor(editor: Editor, direction: "left" | "right") {
+ super(editor);
+ this.direction = direction;
+ }
+
+ public override refresh(): void {
+ const tab = getSelectedTab(this.editor);
+ this.isEnabled = !!this.getNeighbor(tab);
+ }
+
+ public override execute(): void {
+ const editor = this.editor;
+ const tab = getSelectedTab(editor);
+ const neighbor = this.getNeighbor(tab);
+ if (!tab || !neighbor) {
+ return;
+ }
+
+ editor.model.change(writer => {
+ const target = this.direction === "left"
+ ? writer.createPositionBefore(neighbor)
+ : writer.createPositionAfter(neighbor);
+ writer.move(writer.createRangeOn(tab), target);
+ });
+ }
+
+ private getNeighbor(tab: ModelElement | null) {
+ const neighbor = this.direction === "left" ? tab?.previousSibling : tab?.nextSibling;
+ return neighbor?.is("element", ELEMENTS.tab) ? neighbor : null;
+ }
+}
+
+/** Creates a tab with an empty title and a panel holding one empty paragraph. */
+export function createTab(writer: ModelWriter): ModelElement {
+ const tab = writer.createElement(ELEMENTS.tab);
+ writer.append(writer.createElement(ELEMENTS.tabTitle), tab);
+ const panel = writer.createElement(ELEMENTS.tabPanel);
+ writer.append(writer.createElement("paragraph"), panel);
+ writer.append(panel, tab);
+ return tab;
+}
+
+/** Returns the innermost tab that contains the selection. */
+export function getSelectedTab(editor: Editor): ModelElement | null {
+ const position = editor.model.document.selection.getFirstPosition();
+ return (position?.findAncestor(ELEMENTS.tab) as ModelElement | null) ?? null;
+}
+
+/**
+ * Returns the innermost tabs block that contains the selection, or the block itself when it is
+ * the selected object.
+ */
+export function getSelectedTabs(editor: Editor): ModelElement | null {
+ const selection = editor.model.document.selection;
+ const selected = selection.getSelectedElement();
+ if (selected?.is("element", ELEMENTS.tabs)) {
+ return selected;
+ }
+ const position = selection.getFirstPosition();
+ return (position?.findAncestor(ELEMENTS.tabs) as ModelElement | null) ?? null;
+}
+
+function getTitle(tab: ModelElement): ModelElement | null {
+ const title = tab.getChild(0);
+ return title?.is("element", ELEMENTS.tabTitle) ? title : null;
+}
diff --git a/packages/ckeditor5/src/plugins/tabs/tabs_editing.ts b/packages/ckeditor5/src/plugins/tabs/tabs_editing.ts
new file mode 100644
index 0000000000..8c3f063d35
--- /dev/null
+++ b/packages/ckeditor5/src/plugins/tabs/tabs_editing.ts
@@ -0,0 +1,345 @@
+import {
+ enableViewPlaceholder,
+ type ModelElement,
+ type ModelNode,
+ type ModelPosition,
+ type ModelWriter,
+ type PlaceholderableViewElement,
+ Plugin,
+ toWidget,
+ toWidgetEditable,
+ type ViewDocumentEnterEvent,
+ type ViewEditableElement,
+ Widget
+} from "ckeditor5";
+
+import { CLASSES, ELEMENTS, TABS_WIDGET_PROPERTY } from "./constants.js";
+import { InsertTabCommand, InsertTabsCommand, MoveTabCommand, RemoveTabCommand } from "./tabs_commands.js";
+
+/**
+ * Schema, conversion, commands and key handling for tabs blocks.
+ *
+ * Model: <tabs><tab><tabTitle>…</tabTitle><tabPanel>…blocks…</tabPanel></tab>…</tabs>
+ * Data view: <div class="trilium-tabs">
+ * <section class="trilium-tab">
+ * <p class="trilium-tab-title">…</p>
+ * <div class="trilium-tab-panel">…blocks…</div>
+ * </section>
+ * </div>
+ * Editing view: a widget whose titles form the tab strip and whose active panel shows below it.
+ *
+ * The active tab is editing-view state only: it follows the selection, so clicking a title or
+ * moving the caret into a tab shows that tab. The saved HTML lists every tab in order, which
+ * reads as a sequence of titled sections wherever no script turns it into tabs.
+ */
+export default class TabsEditing extends Plugin {
+
+ public static get pluginName() {
+ return "TabsEditing" as const;
+ }
+
+ public static get requires() {
+ return [Widget] as const;
+ }
+
+ /** The tab each tabs block shows, keyed by the `tabs` model element. */
+ private readonly activeTabs = new WeakMap<ModelElement, ModelElement>();
+
+ public init(): void {
+ const editor = this.editor;
+ editor.commands.add("tabs", new InsertTabsCommand(editor));
+ editor.commands.add("insertTab", new InsertTabCommand(editor));
+ editor.commands.add("removeTab", new RemoveTabCommand(editor));
+ editor.commands.add("moveTabLeft", new MoveTabCommand(editor, "left"));
+ editor.commands.add("moveTabRight", new MoveTabCommand(editor, "right"));
+
+ this.registerSchema();
+ this.registerConversion();
+ this.registerPostFixer();
+ this.registerActiveTabTracking();
+ this.registerEnterInTitle();
+ }
+
+ /**
+ * Returns the tab that `tabs` shows: the one last activated, or the first tab when that one
+ * was removed or none was activated yet.
+ */
+ public getActiveTab(tabs: ModelElement): ModelElement | null {
+ const active = this.activeTabs.get(tabs);
+ if (active?.parent === tabs) {
+ return active;
+ }
+ const first = tabs.getChild(0);
+ return first?.is("element", ELEMENTS.tab) ? first : null;
+ }
+
+ private registerSchema() {
+ const schema = this.editor.model.schema;
+ schema.register(ELEMENTS.tabs, {
+ inheritAllFrom: "$blockObject"
+ });
+ schema.register(ELEMENTS.tab, {
+ allowIn: ELEMENTS.tabs,
+ isLimit: true
+ });
+ schema.register(ELEMENTS.tabTitle, {
+ allowIn: ELEMENTS.tab,
+ allowContentOf: "$block",
+ isLimit: true
+ });
+ schema.register(ELEMENTS.tabPanel, {
+ allowIn: ELEMENTS.tab,
+ allowContentOf: "$root",
+ isLimit: true
+ });
+ }
+
+ private registerConversion() {
+ const editor = this.editor;
+ const conversion = editor.conversion;
+ const t = editor.t;
+
+ // The upcasts match on class and run ahead of the paragraph and General HTML Support
+ // converters, which would otherwise claim the plain `<div>`, `<section>` and `<p>`.
+ conversion.for("upcast").elementToElement({
+ view: { name: "div", classes: CLASSES.tabs },
+ model: ELEMENTS.tabs,
+ converterPriority: "high"
+ });
+ conversion.for("upcast").elementToElement({
+ view: { name: "section", classes: CLASSES.tab },
+ model: ELEMENTS.tab,
+ converterPriority: "high"
+ });
+ conversion.for("upcast").elementToElement({
+ view: { name: "p", classes: CLASSES.tabTitle },
+ model: ELEMENTS.tabTitle,
+ converterPriority: "high"
+ });
+ conversion.for("upcast").elementToElement({
+ view: { name: "div", classes: CLASSES.tabPanel },
+ model: ELEMENTS.tabPanel,
+ converterPriority: "high"
+ });
+
+ conversion.for("dataDowncast").elementToElement({
+ model: ELEMENTS.tabs,
+ view: (_model, { writer }) => writer.createContainerElement("div", { class: CLASSES.tabs })
+ });
+ conversion.for("dataDowncast").elementToElement({
+ model: ELEMENTS.tab,
+ view: (_model, { writer }) => writer.createContainerElement("section", { class: CLASSES.tab })
+ });
+ conversion.for("dataDowncast").elementToElement({
+ model: ELEMENTS.tabTitle,
+ view: (_model, { writer }) => writer.createContainerElement("p", { class: CLASSES.tabTitle })
+ });
+ conversion.for("dataDowncast").elementToElement({
+ model: ELEMENTS.tabPanel,
+ view: (_model, { writer }) => writer.createContainerElement("div", { class: CLASSES.tabPanel })
+ });
+
+ conversion.for("editingDowncast").elementToElement({
+ model: ELEMENTS.tabs,
+ 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 });
+ }
+ });
+ conversion.for("editingDowncast").elementToElement({
+ model: ELEMENTS.tab,
+ view: (model, { writer }) => {
+ const tabs = model.parent;
+ const isActive = !!tabs?.is("element", ELEMENTS.tabs) && this.getActiveTab(tabs) === model;
+ const classes = isActive ? [CLASSES.tab, CLASSES.activeTab] : [CLASSES.tab];
+ return writer.createContainerElement("section", { class: classes.join(" ") });
+ }
+ });
+ conversion.for("editingDowncast").elementToElement({
+ model: ELEMENTS.tabTitle,
+ view: (_model, { writer }) => {
+ const title: ViewEditableElement & PlaceholderableViewElement =
+ writer.createEditableElement("div", { class: CLASSES.tabTitle });
+ title.placeholder = t("Tab title");
+ enableViewPlaceholder({
+ view: editor.editing.view,
+ element: title,
+ keepOnFocus: true
+ });
+ return toWidgetEditable(title, writer, { label: t("Tab title") });
+ }
+ });
+ conversion.for("editingDowncast").elementToElement({
+ model: ELEMENTS.tabPanel,
+ view: (_model, { writer }) => {
+ const panel = writer.createEditableElement("div", { class: CLASSES.tabPanel });
+ return toWidgetEditable(panel, writer, { label: t("Tab content") });
+ }
+ });
+ }
+
+ /**
+ * Keeps every tabs block well formed however it was produced (paste, import, undo): a block
+ * has at least one tab, and every tab starts with a title and holds one non-empty panel.
+ */
+ private registerPostFixer() {
+ const model = this.editor.model;
+
+ model.document.registerPostFixer(writer => {
+ const blocks = new Set<ModelElement>();
+ for (const change of model.document.differ.getChanges()) {
+ if (change.type === "attribute") {
+ continue;
+ }
+ collectTabsAround(change.position, blocks);
+ if (change.type === "insert") {
+ collectTabsWithin(change.position.nodeAfter, blocks);
+ }
+ }
+
+ let changed = false;
+ for (const tabs of blocks) {
+ changed = fixTabs(writer, tabs) || changed;
+ }
+ return changed;
+ });
+ }
+
+ /**
+ * Shows the tab that holds the selection and re-applies the active class wherever a tab was
+ * added, removed or moved. Runs after the editing downcast, so every tab has its view element.
+ */
+ private registerActiveTabTracking() {
+ const editor = this.editor;
+ const model = editor.model;
+
+ this.listenTo(model.document, "change", () => {
+ const blocks = new Set<ModelElement>();
+
+ const position = model.document.selection.getFirstPosition();
+ for (const ancestor of position?.getAncestors() ?? []) {
+ if (ancestor.is("element", ELEMENTS.tab) && ancestor.parent?.is("element", ELEMENTS.tabs)) {
+ this.activeTabs.set(ancestor.parent, ancestor);
+ blocks.add(ancestor.parent);
+ }
+ }
+
+ for (const change of model.document.differ.getChanges()) {
+ if (change.type !== "attribute" && change.position.parent.is("element", ELEMENTS.tabs)) {
+ blocks.add(change.position.parent);
+ }
+ }
+
+ if (blocks.size) {
+ this.updateActiveClasses(blocks);
+ }
+ }, { priority: "lowest" });
+ }
+
+ private updateActiveClasses(blocks: Set<ModelElement>) {
+ const editing = this.editor.editing;
+ editing.view.change(writer => {
+ for (const tabs of blocks) {
+ if (tabs.root.rootName === "$graveyard") {
+ continue;
+ }
+ const active = this.getActiveTab(tabs);
+ for (const tab of tabs.getChildren()) {
+ const view = editing.mapper.toViewElement(tab as ModelElement);
+ if (!view) {
+ continue;
+ }
+ if (tab === active) {
+ writer.addClass(CLASSES.activeTab, view);
+ } else {
+ writer.removeClass(CLASSES.activeTab, view);
+ }
+ }
+ }
+ });
+ }
+
+ /** A title holds a single line, so Enter moves the caret to the start of the tab's panel. */
+ private registerEnterInTitle() {
+ const editor = this.editor;
+ const model = editor.model;
+
+ this.listenTo<ViewDocumentEnterEvent>(editor.editing.view.document, "enter", (evt, data) => {
+ const position = model.document.selection.getFirstPosition();
+ const title = position?.findAncestor(ELEMENTS.tabTitle);
+ const panel = title?.nextSibling;
+ if (!panel?.is("element", ELEMENTS.tabPanel)) {
+ return;
+ }
+
+ model.change(writer => {
+ writer.setSelection(writer.createPositionAt(panel, 0));
+ });
+ data.preventDefault();
+ evt.stop();
+ }, { priority: "high" });
+ }
+}
+
+/** Adds every tabs block that encloses `position`. */
+function collectTabsAround(position: ModelPosition, blocks: Set<ModelElement>) {
+ for (const ancestor of position.getAncestors()) {
+ if (ancestor.is("element", ELEMENTS.tabs)) {
+ blocks.add(ancestor);
+ }
+ }
+}
+
+/** Adds `node` and every tabs block inside it. */
+function collectTabsWithin(node: ModelNode | null, blocks: Set<ModelElement>) {
+ if (!node?.is("element")) {
+ return;
+ }
+ if (node.is("element", ELEMENTS.tabs)) {
+ blocks.add(node);
+ }
+ for (const child of node.getChildren()) {
+ collectTabsWithin(child, blocks);
+ }
+}
+
+function fixTabs(writer: ModelWriter, tabs: ModelElement): boolean {
+ if (tabs.root.rootName === "$graveyard") {
+ return false;
+ }
+
+ if (tabs.isEmpty) {
+ writer.remove(tabs);
+ return true;
+ }
+
+ let changed = false;
+ for (const tab of [...tabs.getChildren()]) {
+ if (!tab.is("element", ELEMENTS.tab)) {
+ continue;
+ }
+ const children = [...tab.getChildren()];
+ const title = children.find(child => child.is("element", ELEMENTS.tabTitle));
+ const panel = children.find(child => child.is("element", ELEMENTS.tabPanel)) as ModelElement | undefined;
+
+ if (!title) {
+ writer.insertElement(ELEMENTS.tabTitle, tab, 0);
+ changed = true;
+ } else if (title.index !== 0) {
+ writer.move(writer.createRangeOn(title), tab, 0);
+ changed = true;
+ }
+
+ if (!panel) {
+ const newPanel = writer.createElement(ELEMENTS.tabPanel);
+ writer.appendElement("paragraph", newPanel);
+ writer.append(newPanel, tab);
+ changed = true;
+ } else if (panel.isEmpty) {
+ writer.appendElement("paragraph", panel);
+ changed = true;
+ }
+ }
+ return changed;
+}
diff --git a/packages/ckeditor5/src/plugins/tabs/tabs_ui.ts b/packages/ckeditor5/src/plugins/tabs/tabs_ui.ts
new file mode 100644
index 0000000000..c7b3c2d48b
--- /dev/null
+++ b/packages/ckeditor5/src/plugins/tabs/tabs_ui.ts
@@ -0,0 +1,88 @@
+import {
+ ButtonView,
+ IconNextArrow,
+ IconPlus,
+ IconPreviousArrow,
+ IconRemove,
+ isWidget,
+ Plugin,
+ type ViewDocumentSelection,
+ type ViewElement,
+ WidgetToolbarRepository
+} from "ckeditor5";
+
+import tabsIcon from "../../icons/tabs.svg?raw";
+import { TABS_WIDGET_PROPERTY } from "./constants.js";
+
+/**
+ * The insert button for tabs blocks and the contextual toolbar that adds, removes and reorders
+ * tabs while the selection is inside a block.
+ */
+export default class TabsUI extends Plugin {
+
+ public static get pluginName() {
+ return "TabsUI" as const;
+ }
+
+ public static get requires() {
+ return [WidgetToolbarRepository] as const;
+ }
+
+ public init(): void {
+ const t = this.editor.t;
+ this.addButton("tabs", t("Tabs"), tabsIcon);
+ this.addButton("insertTab", t("Add tab"), IconPlus);
+ this.addButton("removeTab", t("Remove tab"), IconRemove);
+ this.addButton("moveTabLeft", t("Move tab left"), IconPreviousArrow);
+ this.addButton("moveTabRight", t("Move tab right"), IconNextArrow);
+ }
+
+ public afterInit(): void {
+ const t = this.editor.t;
+ this.editor.plugins.get(WidgetToolbarRepository).register("tabs", {
+ ariaLabel: t("Tabs toolbar"),
+ items: ["insertTab", "removeTab", "|", "moveTabLeft", "moveTabRight"],
+ getRelatedElement: getTabsWidget
+ });
+ }
+
+ private addButton(name: string, label: string, icon: string) {
+ const editor = this.editor;
+ editor.ui.componentFactory.add(name, locale => {
+ const button = new ButtonView(locale);
+ button.set({ label, icon, tooltip: true });
+
+ const command = editor.commands.get(name);
+ if (command) {
+ button.bind("isEnabled").to(command, "isEnabled");
+ }
+
+ this.listenTo(button, "execute", () => {
+ editor.execute(name);
+ editor.editing.view.focus();
+ });
+ return button;
+ });
+ }
+}
+
+/** Returns the innermost tabs widget that is selected or holds the selection. */
+function getTabsWidget(selection: ViewDocumentSelection): ViewElement | null {
+ const selected = selection.getSelectedElement();
+ if (selected && isTabsWidget(selected)) {
+ return selected;
+ }
+
+ let node = selection.getFirstPosition()?.parent ?? null;
+ while (node) {
+ if (node.is("element") && isTabsWidget(node)) {
+ return node;
+ }
+ node = node.parent;
+ }
+ return null;
+}
+
+function isTabsWidget(element: ViewElement) {
+ return !!element.getCustomProperty(TABS_WIDGET_PROPERTY) && isWidget(element);
+}
diff --git a/packages/ckeditor5/src/theme/tabs.css b/packages/ckeditor5/src/theme/tabs.css
new file mode 100644
index 0000000000..4c8af08d0d
--- /dev/null
+++ b/packages/ckeditor5/src/theme/tabs.css
@@ -0,0 +1,52 @@
+.ck-editor__editable .trilium-tabs {
+ display: flex;
+ flex-wrap: wrap;
+ align-items: flex-end;
+ gap: 0 2px;
+ margin: 1em 0;
+
+ & > .trilium-tab {
+ display: contents;
+ }
+
+ & > .trilium-tab > .trilium-tab-title {
+ order: 0;
+ min-width: 4em;
+ max-width: 100%;
+ margin: 0;
+ padding: 4px 12px;
+ border: 1px solid var(--main-border-color, var(--ck-color-base-border));
+ border-bottom: 0;
+ border-radius: 6px 6px 0 0;
+ background: var(--accented-background-color, var(--ck-color-base-foreground));
+ color: var(--muted-text-color, inherit);
+ cursor: pointer;
+ }
+
+ & > .trilium-tab > .trilium-tab-panel {
+ display: none;
+ order: 1;
+ flex: 1 0 100%;
+ min-width: 0;
+ padding: 0 1em;
+ border: 1px solid var(--main-border-color, var(--ck-color-base-border));
+ border-radius: 0 6px 6px 6px;
+ }
+
+ & > .trilium-tab.trilium-tab--active {
+ & > .trilium-tab-title {
+ position: relative;
+ z-index: 1;
+ margin-bottom: -1px;
+ padding-bottom: 5px;
+ background: var(--main-background-color, var(--ck-color-base-background));
+ color: inherit;
+ font-weight: 600;
+ cursor: text;
+ }
+
+ & > .trilium-tab-panel {
+ display: block;
+ }
+ }
+}