Skip to content

Build your personal knowledge base with Trilium Notes

feat(text): copy a link to a tab

Elian Doran690e8c2c893e
diff --git a/apps/client/src/menus/note_context_menu.spec.ts b/apps/client/src/menus/note_context_menu.spec.ts
index 53a2e7fd62..8fd086800f 100644
--- a/apps/client/src/menus/note_context_menu.spec.ts
+++ b/apps/client/src/menus/note_context_menu.spec.ts
@@ -322,6 +322,7 @@ describe("buildNoteContextMenuItems", () => {
} as TableMenuSections);
vi.mocked(buildBlockReferenceMenuItems).mockResolvedValueOnce({
copy: { title: "BC" },
+ copyTab: { title: "BT" },
paste: [ { title: "BP1" }, { title: "BP2" } ]
});
const host = browserLikeHost({
@@ -338,7 +339,8 @@ describe("buildNoteContextMenuItems", () => {
"electron_context_menu.copy",
"electron_context_menu.copy-as-markdown",
"---",
- "BC"
+ "BC",
+ "BT"
]);
// Without a selection only the reference can be copied, so the row opens its submenu.
expect(findItem(items, "electron_context_menu.copy"))
diff --git a/apps/client/src/menus/note_context_menu.ts b/apps/client/src/menus/note_context_menu.ts
index 5ad00c0963..79c231bee2 100644
--- a/apps/client/src/menus/note_context_menu.ts
+++ b/apps/client/src/menus/note_context_menu.ts
@@ -190,8 +190,10 @@ export async function buildNoteContextMenuItems(
handler: copySelectionAsMarkdown
}
];
- if (blockReferenceItems?.copy) {
- copyVariants.push({ kind: "separator" }, blockReferenceItems.copy);
+ const referenceItems = [ blockReferenceItems?.copy, blockReferenceItems?.copyTab ]
+ .filter((item): item is MenuItem<CommandNames> => !!item);
+ if (referenceItems.length) {
+ copyVariants.push({ kind: "separator" }, ...referenceItems);
}
items.push(splitMenuItem({
diff --git a/apps/client/src/services/block_excerpts.spec.ts b/apps/client/src/services/block_excerpts.spec.ts
index 1ff86bebb8..08fe1ebb6f 100644
--- a/apps/client/src/services/block_excerpts.spec.ts
+++ b/apps/client/src/services/block_excerpts.spec.ts
@@ -93,4 +93,14 @@ describe("getBlockExcerpt", () => {
expect(single.endsWith("word…")).toBe(true);
expect(range).toBe(`${"word ".repeat(6).trimEnd()}… … end`);
});
+
+ it("names a tab by its title", () => {
+ const container = document.createElement("div");
+ container.innerHTML = "<section class=\"trilium-tab\"><p class=\"trilium-tab-title\">Linux</p>"
+ + "<div class=\"trilium-tab-panel\"><p>Use the package.</p></div></section>";
+ const tab = container.querySelector(".trilium-tab");
+ expect(tab).not.toBeNull();
+
+ expect(getBlockExcerpt(tab as Element, tab as Element)).toBe("Linux");
+ });
});
diff --git a/apps/client/src/services/block_excerpts.ts b/apps/client/src/services/block_excerpts.ts
index 1f1a1b64d2..01de14ed3b 100644
--- a/apps/client/src/services/block_excerpts.ts
+++ b/apps/client/src/services/block_excerpts.ts
@@ -97,8 +97,12 @@ function loadContent(note: FNote) {
return entry.loaded;
}
+/** The text of `element`; a tab is named by its title. */
function getText(element: Element) {
- return (element.textContent ?? "").replace(/\s+/g, " ").trim();
+ const title = element.matches(".trilium-tab")
+ ? element.querySelector(":scope > .trilium-tab-title")
+ : null;
+ return ((title ?? element).textContent ?? "").replace(/\s+/g, " ").trim();
}
function truncate(text: string, maxLength: number) {
diff --git a/apps/client/src/services/block_reference.spec.ts b/apps/client/src/services/block_reference.spec.ts
index 2936bf9857..d96ac0f342 100644
--- a/apps/client/src/services/block_reference.spec.ts
+++ b/apps/client/src/services/block_reference.spec.ts
@@ -5,7 +5,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import type { CommandNames } from "../components/app_context.js";
import type { MenuCommandItem, MenuItem } from "../menus/context_menu.js";
import {
- buildBlockReferenceMenuItems, consumeBlockReference, copyBlockReference,
+ buildBlockReferenceMenuItems, consumeBlockReference, copyBlockReference, copyTabReference,
getBlockRangeElements, getClipboardBlockReference, highlightBlockReference,
openBlockHandleMenu, revealHighlightedBlocks
} from "./block_reference.js";
@@ -229,6 +229,27 @@ describe("copyBlockReference", () => {
});
});
+describe("copyTabReference", () => {
+ it("copies a link to the tab holding the selection, named by its title, and flashes it", async () => {
+ const root = buildContainer(
+ "<div class=\"trilium-tabs\"><section class=\"trilium-tab\" data-trilium-block-id=\"t1\">"
+ + "<p class=\"trilium-tab-title\">Linux</p>"
+ + "<div class=\"trilium-tab-panel\"><p>Use the package.</p></div></section></div>"
+ );
+ const editor = buildEditor(root, { startId: "t1", endId: "t1", count: 1 });
+
+ await copyTabReference(editor, "root/n1", "Note");
+
+ const href = "#root/n1?block=t1";
+ expect(editor.execute).toHaveBeenCalledWith("assignTabReference");
+ expect(copyHtmlWithToast).toHaveBeenCalledWith(
+ `<a class="reference-link" href="${href}">Note - Linux</a>`,
+ href
+ );
+ expect(root.querySelector(".trilium-tab")?.classList.contains("block-reference-flash")).toBe(true);
+ });
+});
+
describe("openBlockHandleMenu", () => {
it("offers to copy a reference to the selected blocks", () => {
const event = new MouseEvent("contextmenu", { clientX: 10, clientY: 20 });
@@ -295,6 +316,25 @@ describe("buildBlockReferenceMenuItems", () => {
expect(items?.paste).toEqual([]);
});
+ it("copies a link to the tab holding the selection through the host of the editor", async () => {
+ const copyTabReference = vi.fn();
+ const { editor } = buildMenuEditor();
+ getTextEditorContaining.mockResolvedValue(editor);
+ getComponentByEl.mockReturnValue({ copyBlockReference: vi.fn(), copyTabReference });
+
+ const items = await buildBlockReferenceMenuItems(element);
+ runItem(items?.copyTab);
+
+ expect(items?.copyTab).toMatchObject({ title: "block_reference.copy_tab" });
+ expect(copyTabReference).toHaveBeenCalledTimes(1);
+
+ getTextEditorContaining.mockResolvedValue(buildMenuEditor({ isInTab: false }).editor);
+ expect((await buildBlockReferenceMenuItems(element))?.copyTab).toBeNull();
+ getComponentByEl.mockReturnValue({ copyBlockReference: vi.fn() });
+ getTextEditorContaining.mockResolvedValue(editor);
+ expect((await buildBlockReferenceMenuItems(element))?.copyTab).toBeNull();
+ });
+
it("offers no copy row where no reference can be made or the host cannot copy", async () => {
getComponentByEl.mockReturnValue({ copyBlockReference: vi.fn() });
getTextEditorContaining.mockResolvedValue(buildMenuEditor({ canReference: false }).editor);
@@ -389,12 +429,13 @@ describe("buildBlockReferenceMenuItems", () => {
});
function buildMenuEditor({
- count = 2, canReference = true, canEmbed = true, hasPlugin = true
+ count = 2, canReference = true, canEmbed = true, hasPlugin = true, isInTab = true
} = {}) {
const root = document.createElement("div");
const pasteTarget = { paste: vi.fn(), release: vi.fn() };
const commands: Record<string, { isEnabled: boolean; value?: number }> = {
assignBlockReference: { isEnabled: canReference, value: count },
+ assignTabReference: { isEnabled: isInTab },
insertContentEmbed: { isEnabled: canEmbed }
};
const editor = {
diff --git a/apps/client/src/services/block_reference.ts b/apps/client/src/services/block_reference.ts
index b9a4044bf9..0632bb7c3c 100644
--- a/apps/client/src/services/block_reference.ts
+++ b/apps/client/src/services/block_reference.ts
@@ -1,6 +1,6 @@
import type { CKTextEditor } from "@triliumnext/ckeditor5";
import {
- formatBlockRange, parseBlockRange, resolveBlockRange, resolveBlockReference
+ type BlockRange, formatBlockRange, parseBlockRange, resolveBlockRange, resolveBlockReference
} from "@triliumnext/commons";
import type { CommandNames } from "../components/app_context.js";
@@ -33,6 +33,8 @@ export interface ClipboardBlockReference {
export interface BlockReferenceMenuItems {
/** Copies a reference to the selected blocks, in the _Copy_ submenu, or `null`. */
copy: MenuItem<CommandNames> | null;
+ /** Copies a link to the tab that holds the selection, in the _Copy_ submenu, or `null`. */
+ copyTab: MenuItem<CommandNames> | null;
/** Pastes the reference on the clipboard, in the _Paste_ submenu. */
paste: MenuItem<CommandNames>[];
}
@@ -40,6 +42,7 @@ export interface BlockReferenceMenuItems {
/** The component of a text editor that copies references to the blocks of its note. */
interface BlockReferenceHost {
copyBlockReference?(): Promise<void>;
+ copyTabReference?(): void;
}
/** Opens the menu of the block handle at `event`, which copies a reference to `count` blocks. */
@@ -67,6 +70,7 @@ export async function buildBlockReferenceMenuItems(
return {
copy: getCopyMenuItem(editor),
+ copyTab: getCopyTabMenuItem(editor),
paste: clipboard ? getPasteMenuItems(editor, clipboard) : []
};
}
@@ -102,7 +106,28 @@ export async function copyBlockReference(
notePath: string,
noteTitle: string
) {
- const target = editor.execute("assignBlockReference");
+ await copyReference(editor, editor.execute("assignBlockReference"), notePath, noteTitle);
+}
+
+/**
+ * Gives an id to the tab that holds the selection of `editor`, flashes the tab and copies a link
+ * to it, named by its title. `notePath` and `noteTitle` are of the note the editor shows.
+ */
+export async function copyTabReference(
+ editor: CKTextEditor,
+ notePath: string,
+ noteTitle: string
+) {
+ await copyReference(editor, editor.execute("assignTabReference"), notePath, noteTitle);
+}
+
+/** Flashes the blocks of `target` and copies a reference link to them. */
+async function copyReference(
+ editor: CKTextEditor,
+ target: BlockRange | null | undefined,
+ notePath: string,
+ noteTitle: string
+) {
const root = editor.editing.view.getDomRoot();
const { start, end } = target && root
? resolveBlockRange<HTMLElement>(root, target)
@@ -236,6 +261,21 @@ function getCopyMenuItem(editor: CKTextEditor) {
return getCopyItem(command.value, () => void host.copyBlockReference?.());
}
+function getCopyTabMenuItem(editor: CKTextEditor): MenuItem<CommandNames> | null {
+ const command = editor.commands.get("assignTabReference");
+ const root = editor.editing.view.getDomRoot();
+ const host: BlockReferenceHost | undefined = root && glob.getComponentByEl(root);
+ if (!command?.isEnabled || !host?.copyTabReference) {
+ return null;
+ }
+
+ return {
+ title: t("block_reference.copy_tab"),
+ uiIcon: "bx bx-link",
+ handler: () => host.copyTabReference?.()
+ };
+}
+
function getPasteMenuItems(
editor: CKTextEditor,
clipboard: ClipboardAccess
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.json
index 831dccf36f..81660184cf 100644
--- a/apps/client/src/translations/en/translation.json
+++ b/apps/client/src/translations/en/translation.json
@@ -4388,6 +4388,7 @@
"remove-tab": "Remove tab",
"move-tab-left": "Move tab left",
"move-tab-right": "Move tab right",
+ "copy-link-to-tab": "Copy link to tab",
"tabs-toolbar": "Tabs toolbar",
"insert-titled-tabs-that-show-one-panel-at-a-time": "Insert titled tabs that show one panel at a time."
},
@@ -4512,6 +4513,7 @@
"block_reference": {
"copy_one": "Copy reference to this block",
"copy_other": "Copy reference to these {{count}} blocks",
+ "copy_tab": "Copy link to this tab",
"paste_as_link": "Paste reference as a link",
"paste_as_excerpt": "Paste reference as an excerpt",
"no_reference_on_clipboard": "The clipboard does not contain a block reference.",
diff --git a/apps/client/src/widgets/type_widgets/text/EditableText.tsx b/apps/client/src/widgets/type_widgets/text/EditableText.tsx
index 04933fe045..8751111d40 100644
--- a/apps/client/src/widgets/type_widgets/text/EditableText.tsx
+++ b/apps/client/src/widgets/type_widgets/text/EditableText.tsx
@@ -15,7 +15,7 @@ import { useCallback, useEffect, useRef, useState } from "preact/hooks";
import appContext from "../../../components/app_context";
import {
- consumeBlockReference, copyBlockReference, openBlockHandleMenu
+ consumeBlockReference, copyBlockReference, copyTabReference, openBlockHandleMenu
} from "../../../services/block_reference";
import { consumeBookmark } from "../../../services/bookmark_jump";
import { getUploadBoxSize } from "../../../services/content_renderer";
@@ -170,12 +170,12 @@ export default function EditableText({
consumeBlockReference(root, noteContext?.viewScope);
}
- async function copyReference() {
+ async function copyReference(copy = copyBlockReference) {
const editor = watchdogRef.current?.editor as CKTextEditor | undefined;
if (!editor) return;
const notePath = noteContext?.notePath ?? `root/${note.noteId}`;
- await copyBlockReference(editor, notePath, note.title);
+ await copy(editor, notePath, note.title);
// Saved now, so that the link resolves in other notes at once.
spacedUpdate.updateNowIfNecessary();
}
@@ -282,7 +282,8 @@ export default function EditableText({
openBlockHandleMenu(event: MouseEvent, count: number) {
openBlockHandleMenu(event, count, () => void copyReference());
},
- copyBlockReference: copyReference,
+ copyBlockReference: () => copyReference(),
+ copyTabReference: () => void copyReference(copyTabReference),
getContentEmbedTools,
// Link preview functionality. The insert flow itself lives in the editor (a balloon form),
// so the host only has to supply the metadata and the rendering.
diff --git a/packages/ckeditor5/src/augmentation.ts b/packages/ckeditor5/src/augmentation.ts
index 5a41eb56d1..5526c792f4 100644
--- a/packages/ckeditor5/src/augmentation.ts
+++ b/packages/ckeditor5/src/augmentation.ts
@@ -118,6 +118,11 @@ declare global {
* without block references leave it out.
*/
openBlockHandleMenu?(event: MouseEvent, count: number): void;
+ /**
+ * Copies a link to the tab that holds the selection. Hosts without block references leave
+ * it out.
+ */
+ copyTabReference?(): void;
/**
* The buttons that what `embed` shows adds to the toolbar of the embed, or `null`. Hosts
* without embeds leave it out.
diff --git a/packages/ckeditor5/src/index.ts b/packages/ckeditor5/src/index.ts
index 202955b65e..097dcf3cd1 100644
--- a/packages/ckeditor5/src/index.ts
+++ b/packages/ckeditor5/src/index.ts
@@ -34,6 +34,7 @@ import "./plugins/file_upload/uploadfileplugin.js";
import "./plugins/block_reference/block_reference.js";
import "./plugins/content_embed/content_embed.js";
import "./plugins/math/math.js";
+import "./plugins/tabs/tabs.js";
import "./plugins/mermaid/mermaid.js";
import "./plugins/referencelink.js";
import "./plugins/table_context_menu.js";
diff --git a/packages/ckeditor5/src/plugins/block_reference/block_reference_editing.ts b/packages/ckeditor5/src/plugins/block_reference/block_reference_editing.ts
index 6f445f9b7c..c6da5c4bf8 100644
--- a/packages/ckeditor5/src/plugins/block_reference/block_reference_editing.ts
+++ b/packages/ckeditor5/src/plugins/block_reference/block_reference_editing.ts
@@ -236,7 +236,8 @@ function getBlocksById(model: Model, excluded: Set<ModelElement>) {
return blocks;
}
-function generateBlockId() {
+/** A new random block id. */
+export function generateBlockId() {
const bytes = crypto.getRandomValues(new Uint8Array(BLOCK_ID_LENGTH));
const characters = Array.from(bytes, (byte) =>
BLOCK_ID_CHARACTERS[byte % BLOCK_ID_CHARACTERS.length]);
diff --git a/packages/ckeditor5/src/plugins/tabs/tabs.spec.ts b/packages/ckeditor5/src/plugins/tabs/tabs.spec.ts
index 78030f6422..a7bba6c8dd 100644
--- a/packages/ckeditor5/src/plugins/tabs/tabs.spec.ts
+++ b/packages/ckeditor5/src/plugins/tabs/tabs.spec.ts
@@ -10,6 +10,7 @@ import {
} from "ckeditor5";
import { afterEach, beforeEach, describe, expect, it } from "vitest";
+import BlockReferenceEditing from "../block_reference/block_reference_editing.js";
import Tabs from "./tabs.js";
import { revealTab } from "./tabs_read_only.js";
@@ -30,7 +31,7 @@ describe("Tabs", () => {
document.body.appendChild(domElement);
editor = await ClassicEditor.create(domElement, {
licenseKey: "GPL",
- plugins: [Bookmark, Essentials, FindAndReplaceEditing, Paragraph, Tabs]
+ plugins: [BlockReferenceEditing, Bookmark, Essentials, FindAndReplaceEditing, Paragraph, Tabs]
});
});
@@ -182,6 +183,28 @@ describe("Tabs", () => {
expect(activeTitles()).toEqual(["Windows"]);
});
+ it("gives the tab holding the selection a reference id, saved on its section", () => {
+ editor.setData(TWO_TABS);
+ const command = editor.commands.get("assignTabReference");
+ expect(command).toBeDefined();
+ editor.model.change(writer => writer.setSelection(tabsElement(), "on"));
+ expect(command?.isEnabled).toBe(false);
+
+ const linux = tabsElement().getChild(1) as ModelElement;
+ editor.model.change(writer => writer.setSelection(linux.getChild(1) as ModelElement, 0));
+ expect(command?.isEnabled).toBe(true);
+ const target = editor.execute("assignTabReference") as { startId: string; endId: string; count: number };
+
+ expect(target.startId).toMatch(/^[A-Za-z0-9]{12}$/);
+ expect(target).toEqual({ startId: target.startId, endId: target.startId, count: 1 });
+ const data = editor.getData();
+ expect(data).toContain(`<section class="trilium-tab" data-trilium-block-id="${target.startId}"><p class="trilium-tab-title">Linux</p>`);
+ expect(editor.execute("assignTabReference")).toEqual(target);
+
+ editor.setData(data);
+ expect((tabsElement().getChild(1) as ModelElement).getAttribute("blockId")).toBe(target.startId);
+ });
+
it("exposes the active tab and each panel's title to assistive technology", () => {
editor.setData(TWO_TABS);
const root = editor.editing.view.getDomRoot();
diff --git a/packages/ckeditor5/src/plugins/tabs/tabs.ts b/packages/ckeditor5/src/plugins/tabs/tabs.ts
index 52f7787366..027fba5822 100644
--- a/packages/ckeditor5/src/plugins/tabs/tabs.ts
+++ b/packages/ckeditor5/src/plugins/tabs/tabs.ts
@@ -1,7 +1,9 @@
import { Plugin } from "ckeditor5";
import "../../theme/tabs.css";
-import type { InsertTabCommand, InsertTabsCommand, MoveTabCommand, RemoveTabCommand } from "./tabs_commands.js";
+import type {
+ AssignTabReferenceCommand, InsertTabCommand, InsertTabsCommand, MoveTabCommand, RemoveTabCommand
+} from "./tabs_commands.js";
import TabsEditing from "./tabs_editing.js";
import TabsUI from "./tabs_ui.js";
@@ -35,5 +37,6 @@ declare module "ckeditor5" {
removeTab: RemoveTabCommand;
moveTabLeft: MoveTabCommand;
moveTabRight: MoveTabCommand;
+ assignTabReference: AssignTabReferenceCommand;
}
}
diff --git a/packages/ckeditor5/src/plugins/tabs/tabs_commands.ts b/packages/ckeditor5/src/plugins/tabs/tabs_commands.ts
index 6272c13d03..ac569c645d 100644
--- a/packages/ckeditor5/src/plugins/tabs/tabs_commands.ts
+++ b/packages/ckeditor5/src/plugins/tabs/tabs_commands.ts
@@ -1,5 +1,6 @@
import { Command, type Editor, type ModelElement, type ModelWriter } from "ckeditor5";
+import { BLOCK_ID, type BlockReferenceTarget, generateBlockId } from "../block_reference/block_reference_editing.js";
import { ELEMENTS } from "./constants.js";
/**
@@ -136,6 +137,32 @@ export class MoveTabCommand extends Command {
}
}
+/**
+ * Gives the tab holding the selection a block id, unless it has one, and returns it as the target
+ * of a block reference, so that a link to the tab resolves like a link to a block.
+ */
+export class AssignTabReferenceCommand extends Command {
+
+ public override refresh(): void {
+ const tab = getSelectedTab(this.editor);
+ this.isEnabled = !!tab && this.editor.model.schema.checkAttribute(tab, BLOCK_ID);
+ }
+
+ public override execute(): BlockReferenceTarget | null {
+ const tab = getSelectedTab(this.editor);
+ /* v8 ignore next 3 -- execute() runs only while refresh() keeps the command enabled */
+ if (!tab) {
+ return null;
+ }
+
+ if (!tab.hasAttribute(BLOCK_ID)) {
+ this.editor.model.change(writer => writer.setAttribute(BLOCK_ID, generateBlockId(), tab));
+ }
+ const id = tab.getAttribute(BLOCK_ID) as string;
+ return { startId: id, endId: id, count: 1 };
+ }
+}
+
/** Creates a tab with the given title and a panel holding one empty paragraph. */
export function createTab(writer: ModelWriter, titleText: string): ModelElement {
const tab = writer.createElement(ELEMENTS.tab);
diff --git a/packages/ckeditor5/src/plugins/tabs/tabs_editing.ts b/packages/ckeditor5/src/plugins/tabs/tabs_editing.ts
index 844fef5853..b25da2d5ad 100644
--- a/packages/ckeditor5/src/plugins/tabs/tabs_editing.ts
+++ b/packages/ckeditor5/src/plugins/tabs/tabs_editing.ts
@@ -14,8 +14,11 @@ import {
Widget
} from "ckeditor5";
+import { BLOCK_ID } from "../block_reference/block_reference_editing.js";
import { CLASSES, ELEMENTS, TABS_WIDGET_PROPERTY } from "./constants.js";
-import { InsertTabCommand, InsertTabsCommand, MoveTabCommand, RemoveTabCommand } from "./tabs_commands.js";
+import {
+ AssignTabReferenceCommand, InsertTabCommand, InsertTabsCommand, MoveTabCommand, RemoveTabCommand
+} from "./tabs_commands.js";
/**
* Schema, conversion, commands and key handling for tabs blocks. The active tab is editing-view
@@ -44,6 +47,7 @@ export default class TabsEditing extends Plugin {
editor.commands.add("removeTab", new RemoveTabCommand(editor));
editor.commands.add("moveTabLeft", new MoveTabCommand(editor, "left"));
editor.commands.add("moveTabRight", new MoveTabCommand(editor, "right"));
+ editor.commands.add("assignTabReference", new AssignTabReferenceCommand(editor));
this.registerSchema();
this.registerConversion();
@@ -105,6 +109,7 @@ export default class TabsEditing extends Plugin {
});
schema.register(ELEMENTS.tab, {
allowIn: ELEMENTS.tabs,
+ allowAttributes: BLOCK_ID,
isLimit: true
});
schema.register(ELEMENTS.tabTitle, {
diff --git a/packages/ckeditor5/src/plugins/tabs/tabs_ui.spec.ts b/packages/ckeditor5/src/plugins/tabs/tabs_ui.spec.ts
index 5f7933e400..51b50dbd0e 100644
--- a/packages/ckeditor5/src/plugins/tabs/tabs_ui.spec.ts
+++ b/packages/ckeditor5/src/plugins/tabs/tabs_ui.spec.ts
@@ -1,6 +1,7 @@
import { ButtonView, ClassicEditor, Essentials, Paragraph } from "ckeditor5";
-import { afterEach, beforeEach, describe, expect, it } from "vitest";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { installGlobMock } from "../../../test/globals-test-kit.js";
import Tabs from "./tabs.js";
describe("TabsUI", () => {
@@ -33,4 +34,19 @@ describe("TabsUI", () => {
expect(buttons.map(button => button.isEnabled)).toEqual([false, true, true, false, true]);
expect(buttons.every(button => button.label && button.icon && button.tooltip)).toBe(true);
});
+
+ it("copies a link to the tab holding the selection through the host", () => {
+ const copyTabReference = vi.fn();
+ installGlobMock({ getComponentByEl: () => ({ copyTabReference }) });
+ editor.setData("<p>x</p>");
+ const button = editor.ui.componentFactory.create("copyTabLink") as ButtonView;
+ expect(button.isEnabled).toBe(false);
+
+ editor.execute("tabs");
+ expect(button.isEnabled).toBe(true);
+ expect(button.label && button.icon && button.tooltip).toBeTruthy();
+ button.fire("execute");
+
+ expect(copyTabReference).toHaveBeenCalledTimes(1);
+ });
});
diff --git a/packages/ckeditor5/src/plugins/tabs/tabs_ui.ts b/packages/ckeditor5/src/plugins/tabs/tabs_ui.ts
index d4a80d8c29..5fe2dc7b99 100644
--- a/packages/ckeditor5/src/plugins/tabs/tabs_ui.ts
+++ b/packages/ckeditor5/src/plugins/tabs/tabs_ui.ts
@@ -1,6 +1,8 @@
import {
ButtonView,
type Command,
+ type Editor,
+ IconLink,
IconNextArrow,
IconPlus,
IconPreviousArrow,
@@ -36,17 +38,32 @@ export default class TabsUI extends Plugin {
this.addButton("removeTab", t("Remove tab"), IconRemove);
this.addButton("moveTabLeft", t("Move tab left"), IconPreviousArrow);
this.addButton("moveTabRight", t("Move tab right"), IconNextArrow);
+ this.addCopyLinkButton();
}
public afterInit(): void {
const t = this.editor.t;
this.editor.plugins.get(WidgetToolbarRepository).register("tabs", {
ariaLabel: t("Tabs toolbar"),
- items: ["insertTab", "removeTab", "|", "moveTabLeft", "moveTabRight"],
+ items: ["insertTab", "removeTab", "|", "moveTabLeft", "moveTabRight", "|", "copyTabLink"],
getRelatedElement: getTabsWidget
});
}
+ /** Adds the button that copies a link to the tab holding the selection, through the host. */
+ private addCopyLinkButton() {
+ const editor = this.editor;
+ editor.ui.componentFactory.add("copyTabLink", locale => {
+ const button = new ButtonView(locale);
+ button.set({ label: editor.t("Copy link to tab"), icon: IconLink, tooltip: true });
+
+ const command = editor.commands.get("assignTabReference") as Command;
+ button.bind("isEnabled").to(command, "isEnabled");
+ this.listenTo(button, "execute", () => getHost(editor).copyTabReference?.());
+ return button;
+ });
+ }
+
private addButton(name: string, label: string, icon: string) {
const editor = this.editor;
editor.ui.componentFactory.add(name, locale => {
@@ -66,6 +83,11 @@ export default class TabsUI extends Plugin {
}
}
+/** Returns the host component of `editor`, which copies links. */
+function getHost(editor: Editor) {
+ return glob.getComponentByEl<EditorComponent>(editor.editing.view.getDomRoot());
+}
+
/** Returns the innermost tabs widget that is selected or holds the selection. */
function getTabsWidget(selection: ViewDocumentSelection): ViewElement | null {
const selected = selection.getSelectedElement();