Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
test(ckeditor5): cover the phone toolbar back above the gate
Elian Dorand3825b1b05e7
diff --git a/packages/ckeditor5/src/plugins/context_toolbar.spec.ts b/packages/ckeditor5/src/plugins/context_toolbar.spec.tsindex 87ac12e110..1dcf301671 100644--- a/packages/ckeditor5/src/plugins/context_toolbar.spec.ts+++ b/packages/ckeditor5/src/plugins/context_toolbar.spec.ts@@ -1,8 +1,8 @@import {_setModelData as setModelData,ButtonView, type ClassicEditor, ContextualBalloon, DropdownView, Essentials, IconLink, Image, ImageStyle, ImageToolbar,- IconBulletedList, IconNumberedList, IconPreviousArrow, IconTodoList, IconTable, Link, LinkUI, List, ListProperties, Paragraph, TodoList, Table, TableCaption, TableToolbar, ToolbarSeparatorView,- WidgetToolbarRepository+ IconBulletedList, IconNumberedList, IconPreviousArrow, IconThreeVerticalDots, IconTodoList, IconTable, Link, LinkUI, List, ListProperties, Paragraph, TodoList, Table, TableCaption, TableToolbar, ToolbarSeparatorView,+ type ViewElement, WidgetToolbarRepository} from "ckeditor5";import bxPencil from "boxicons/svg/regular/bx-pencil.svg?raw";import { describe, expect, it, vi } from "vitest";@@ -237,6 +237,12 @@ describe("ContextToolbar", () => {setModelData(editor.model, "<paragraph listIndent=\"0\" listItemId=\"a\" listType=\"bulleted\">a[]</paragraph>");editor.ui.update();expect([plugin.source?.id, plugin.isActive]).toStrictEqual(["bulletedList", false]);++ // Drawn anew while its row was never shown, the list still waits for the chip.+ const element = plugin.source?.element;+ editor.execute("listStyle", { type: "circle" });+ expect([plugin.source?.id, plugin.source?.element === element, plugin.isActive])+ .toStrictEqual(["bulletedList", false, false]);});it("adds the task states to the row of a to-do list", async () => {@@ -286,10 +292,10 @@ describe("ContextToolbar", () => {});describe("for a link", () => {- async function createLinkEditor(toolbar = ["undo", "contextToolbar"]) {+ async function createLinkEditor(toolbar = ["undo", "contextToolbar"], decorators = {}) {const editor = await createTestEditor([Essentials, Paragraph, Link, ContextToolbar], {toolbar,- link: { toolbar: ["editLink", "linkProperties", "unlink"] }+ link: { toolbar: ["editLink", "linkProperties", "unlink"], decorators }});editor.ui.focusTracker.isFocused = true;setModelData(editor.model, "<paragraph><$text linkHref=\"https://a.b\">li[]nk</$text> text</paragraph>");@@ -313,6 +319,14 @@ describe("ContextToolbar", () => {editor.ui.update();expect(plugin.isActive).toBe(false);expect(button.isVisible).toBe(false);++ // With a property a link can be given, the toolbar keeps its button.+ const withDecorators = await createLinkEditor(undefined, {+ openInNewTab: { mode: "manual", label: "Open in a new tab", attributes: { target: "_blank" } }+ });+ getButton(withDecorators).fire("execute");+ expect([...withDecorators.plugins.get(ContextToolbar).toolbarView.items].slice(3).map((item) => (item as ButtonView).label))+ .toStrictEqual(["Edit link", "Link properties", "Unlink"]);});it("swaps in on a tap in the link, which is about the link rather than its text", async () => {@@ -375,9 +389,51 @@ describe("ContextToolbar", () => {expect([...editor.plugins.get(ContextToolbar).toolbarView.items][2]).toMatchObject({ label: "Link" });});- it("leaves the balloons alone in an editor without its button", async () => {+ it("names the toolbar of each widget, or takes the toolbar's own label for a widget it has no name for", async () => {+ const editor = await createTestEditor([Essentials, Paragraph, ContextToolbar], { toolbar: ["contextToolbar"] });+ editor.ui.focusTracker.isFocused = true;+ const plugin = editor.plugins.get(ContextToolbar);+ const names: Record<string, string | undefined> = {+ codeblock: "Code block", inlineCode: "Code", admonition: "Admonition", tabs: "Tabs",+ multicolumnLayout: "Columns", contentEmbed: "Embed", other: undefined+ };+ // Stand-ins for the toolbars of those widgets, each for the paragraph while it is the current one.+ let current = "";+ for (const id of Object.keys(names)) {+ editor.plugins.get(WidgetToolbarRepository).register(id, {+ ariaLabel: `${id} toolbar`, items: ["undo"],+ getRelatedElement: (selection) => (current === id ? selection.getFirstPosition()?.parent as ViewElement : null)+ });+ }+ setModelData(editor.model, "<paragraph>a[]</paragraph>");+ const button = getButton(editor);++ for (const [id, name] of Object.entries(names)) {+ current = id;+ editor.ui.update();+ button.fire("execute");+ const title = [...plugin.toolbarView.items][2];+ if (name) {+ expect(button).toMatchObject({ label: name, withText: true, tooltip: `${id} toolbar` });+ expect(title).toMatchObject({ isVisible: true, label: name });+ } else {+ expect(button).toMatchObject({ label: "other toolbar", withText: false, icon: IconThreeVerticalDots });+ expect(title).toMatchObject({ isVisible: false, label: "", icon: "" });+ }+ }+ });++ it("takes over the balloons only in an editor whose toolbar holds its button, at any depth", async () => {const { editor } = await createEditor(["undo"]);expect(editor.plugins.get(WidgetToolbarRepository).isEnabled).toBe(true);++ const unset = await createTestEditor([Essentials, Paragraph, Table, TableToolbar, ContextToolbar], {});+ expect(unset.plugins.get(WidgetToolbarRepository).isEnabled).toBe(true);++ const nested = await createTestEditor([Essentials, Paragraph, Table, TableToolbar, ContextToolbar], {+ toolbar: { items: ["undo", { label: "More", items: ["contextToolbar"] }] }+ });+ expect(nested.plugins.get(WidgetToolbarRepository).isEnabled).toBe(false);});});diff --git a/packages/ckeditor5/src/plugins/context_toolbar.ts b/packages/ckeditor5/src/plugins/context_toolbar.tsindex fd704c218f..dfa80cad29 100644--- a/packages/ckeditor5/src/plugins/context_toolbar.ts+++ b/packages/ckeditor5/src/plugins/context_toolbar.ts@@ -370,7 +370,8 @@ function getLinkToolbarItems(editor: Editor): ToolbarConfigItem[] {if (!editor.plugins.has(LinkUI)) {return [];}- const items = editor.config.get("link.toolbar") ?? [];+ // `LinkUI` defines a default.+ const items = editor.config.get("link.toolbar") as ToolbarConfigItem[];const command = editor.commands.get("link") as LinkCommand | undefined;return command?.manualDecorators.length ? items : items.filter((item) => item !== "linkProperties");}diff --git a/packages/ckeditor5/src/plugins/image_position.spec.ts b/packages/ckeditor5/src/plugins/image_position.spec.tsindex 402f0edc30..f4d5bc1c41 100644--- a/packages/ckeditor5/src/plugins/image_position.spec.ts+++ b/packages/ckeditor5/src/plugins/image_position.spec.ts@@ -53,6 +53,13 @@ describe("ImagePosition", () => {setModelData(editor.model, "<paragraph>b[]</paragraph>");expect(dropdown.isEnabled).toBe(false);});++ it("leaves out a group with no style, and shows the first style while none of them is set", async () => {+ const { editor, dropdown } = await createEditor(["alignLeft", "alignRight"]);+ setModelData(editor.model, BLOCK_IMAGE);+ expect(rows(dropdown)).toStrictEqual(["# Wrap text", "Align left", "Align right"]);+ expect(dropdown.buttonView.icon).toBe(styleIcon(editor, "alignLeft"));+ });});function getDropdown(editor: ClassicEditor) {diff --git a/packages/ckeditor5/src/plugins/image_position.ts b/packages/ckeditor5/src/plugins/image_position.tsindex 83d133f08d..4a3bb07859 100644--- a/packages/ckeditor5/src/plugins/image_position.ts+++ b/packages/ckeditor5/src/plugins/image_position.ts@@ -35,8 +35,9 @@ export default class ImagePosition extends Plugin {const t = editor.t;// Always registered: `ImageStyleEditing` adds it.const command = editor.commands.get("imageStyle") as Command;- const styles = new Map((editor.plugins.get(ImageStyleEditing).normalizedStyles ?? [])- .map((style) => [style.name, style]));+ // Set by `ImageStyleEditing.init()`, which runs first as a plugin this one requires.+ const normalizedStyles = editor.plugins.get(ImageStyleEditing).normalizedStyles as ImageStyleOptionDefinition[];+ const styles = new Map(normalizedStyles.map((style) => [style.name, style]));const groups: { label?: string; rows: [string, string][] }[] = [{ rows: [["inline", t("In line")]] },diff --git a/packages/ckeditor5/src/plugins/internallink.spec.ts b/packages/ckeditor5/src/plugins/internallink.spec.tsindex 982cfe640a..71ea629cdb 100644--- a/packages/ckeditor5/src/plugins/internallink.spec.ts+++ b/packages/ckeditor5/src/plugins/internallink.spec.ts@@ -95,6 +95,18 @@ describe("the link at the selection", () => {setModelData(editor.model,"<paragraph>a[] <$text linkHref=\"https://a.example\">foo</$text></paragraph>");expect(getLinkAtSelection(editor)).toBeNull();+ // Nothing to replace there either.+ replaceLinkAtSelection(editor, "#root/abc", "See there");+ expect(getModelData(editor.model, { withoutSelection: true }))+ .toBe("<paragraph>a <$text linkHref=\"https://a.example\">foo</$text></paragraph>");+ });++ it("reads only the text of a link that holds an inline object", () => {+ editor.model.schema.extend("reference", { allowAttributes: "linkHref" });+ setModelData(editor.model, "<paragraph><$text linkHref=\"https://a.example\">a[]b</$text>"+ + "<reference href=\"#root/abc\" linkHref=\"https://a.example\"></reference>"+ + "<$text linkHref=\"https://a.example\">c</$text></paragraph>");+ expect(getLinkAtSelection(editor)).toStrictEqual({ href: "https://a.example", text: "abc" });});it("replaces the address and the text of the whole link, keeping its formatting", () => {@@ -134,6 +146,17 @@ describe("the link at the selection", () => {await expect(replacing).rejects.toThrow("not found");expect(data()).toBe(original);});++ it("makes no reference once the link is gone by the time the title loads", async () => {+ setModelData(editor.model, LINKED);+ const replacing = replaceLinkAtSelection(editor, "#root/abc", null);+ editor.model.change((writer) => {+ const paragraph = editor.model.document.getRoot()?.getChild(0);+ if (paragraph) writer.remove(paragraph);+ });+ await replacing;+ expect(getModelData(editor.model, { withoutSelection: true })).not.toContain("<reference");+ });});describe("the edit button of the link toolbar", () => {diff --git a/packages/ckeditor5/src/plugins/internallink.ts b/packages/ckeditor5/src/plugins/internallink.tsindex 40a101b3d3..24e59a3c5e 100644--- a/packages/ckeditor5/src/plugins/internallink.ts+++ b/packages/ckeditor5/src/plugins/internallink.ts@@ -140,9 +140,9 @@ export async function replaceLinkAtSelection(editor: Editor, href: string, text:}model.change((writer) => {+ // A link ends where its attribute does, so its range starts at the boundary of a node.const start = found.range.start;- const first = start.textNode ?? start.nodeAfter;- const attributes = new Map(first?.getAttributes() ?? []);+ const attributes = new Map(start.nodeAfter?.getAttributes());writer.remove(found.range);attributes.set('linkHref', href);writer.insertText(text, attributes, start);diff --git a/packages/ckeditor5/src/plugins/mobile_toolbar_items.spec.ts b/packages/ckeditor5/src/plugins/mobile_toolbar_items.spec.tsindex b883065ad4..ff495d4c95 100644--- a/packages/ckeditor5/src/plugins/mobile_toolbar_items.spec.ts+++ b/packages/ckeditor5/src/plugins/mobile_toolbar_items.spec.ts@@ -352,6 +352,11 @@ describe("addLink", () => {editor.enableReadOnlyMode("spec");expect(button.isEnabled).toBe(false);});++ it("is off in an editor without the internal link button, whose dialog it opens", async () => {+ const editor = await createTestEditor([Essentials, Paragraph, MobileToolbarItems], { toolbar: ["addLink"] });+ expect((editor.ui.view.toolbar.items.get(0) as ButtonView).isEnabled).toBe(false);+ });});describe("list properties", () => {@@ -407,6 +412,9 @@ describe("list properties", () => {expect(listType()).toBe("todo");expect(style.buttonView.icon).toBe(IconTodoList);expect(open().map(rowText)).toContain("To-do List ✓");+ // Picked again, it keeps the to-do list.+ entry(open(), "To-do List").run?.();+ expect(listType()).toBe("todo");entry(open(), "Square").run?.();expect([listType(), editor.commands.get("listStyle")?.value]).toStrictEqual(["bulleted", "square"]);@@ -440,6 +448,39 @@ describe("list properties", () => {expect(reversed.isOn).toBe(true);expect(editor.commands.get("listReversed")?.value).toBe(true);});++ it("leaves out the markers the list's `type` attribute cannot hold", async () => {+ const requests: ToolbarGroupMenuRequest[] = [];+ const host = { show: vi.fn((request: ToolbarGroupMenuRequest) => requests.push(request)), hide: vi.fn(), destroy: vi.fn() };+ const editor = await createTestEditor([Essentials, Paragraph, List, ListProperties, MobileToolbarItems, ToolbarGroupMenu], {+ toolbar: ["listTypeMenu"],+ list: { properties: { styles: { useAttribute: true } } },+ toolbarGroupMenu: { host: () => host }+ });+ setModelData(editor.model, BULLETED_LIST);+ (editor.ui.view.toolbar.items.first as DropdownView).buttonView.fire("open");+ const labels = (requests.at(-1)?.items ?? []).map(rowText);+ expect(labels).toContain("Decimal");+ expect(labels).not.toContain("Decimal with leading zero");+ expect(labels).not.toContain("Arabic-indic");+ });++ it("asks for the start from 1 while the list has none, and only with a prompt to ask", async () => {+ const { editor, promptListStart, start } = await createListEditor();+ setModelData(editor.model, "<paragraph>a[]</paragraph>");+ start.fire("execute");+ expect(promptListStart).toHaveBeenCalledExactlyOnceWith("Start at", 1);++ const withoutPrompt = await createTestEditor([Essentials, Paragraph, List, ListProperties, MobileToolbarItems], {+ toolbar: ["listStartAt"],+ list: { properties: { startIndex: true } }+ });+ setModelData(withoutPrompt.model, NUMBERED_LIST);+ const execute = vi.spyOn(withoutPrompt, "execute");+ (withoutPrompt.ui.view.toolbar.items.first as ButtonView).fire("execute");+ await Promise.resolve();+ expect(execute).not.toHaveBeenCalled();+ });});describe("attachMenu", () => {diff --git a/packages/ckeditor5/src/plugins/mobile_toolbar_items.ts b/packages/ckeditor5/src/plugins/mobile_toolbar_items.tsindex 7bd6214638..f8813201a0 100644--- a/packages/ckeditor5/src/plugins/mobile_toolbar_items.ts+++ b/packages/ckeditor5/src/plugins/mobile_toolbar_items.ts@@ -45,7 +45,7 @@ import {UIModel} from "ckeditor5";import type {- Command, DropdownView, Editor, ListDropdownItemDefinition, ListStyleCommand, Locale+ Command, DropdownView, Editor, ListDropdownItemDefinition, ListStyleCommand, Locale, ModelElement} from "ckeditor5";import admonitionIcon from "../icons/admonition.svg?raw";@@ -451,8 +451,9 @@ const DEFAULT_LIST_STYLES: Record<string, string | undefined> = { bulleted: "dis* with, or `undefined` outside a bulleted or numbered list.*/function getCurrentListStyle(editor: Editor) {- const block = editor.model.document.selection.getFirstPosition()?.parent;- const listType = block?.is("element") ? block.getAttribute("listType") : undefined;+ // In the document, a position is always in an element.+ const block = editor.model.document.selection.getFirstPosition()?.parent as ModelElement | undefined;+ const listType = block?.getAttribute("listType");const value = editor.commands.get("listStyle")?.value;const type = !value || value === "default" ? DEFAULT_LIST_STYLES[String(listType)] : value;return LIST_STYLES.find((style) => style.listType === listType && style.type === type);diff --git a/packages/ckeditor5/src/plugins/table_column_bar/table_column_bar.ts b/packages/ckeditor5/src/plugins/table_column_bar/table_column_bar.tsindex 71bc90a1e8..566ccc44d2 100644--- a/packages/ckeditor5/src/plugins/table_column_bar/table_column_bar.ts+++ b/packages/ckeditor5/src/plugins/table_column_bar/table_column_bar.ts@@ -252,7 +252,8 @@ export default class TableColumnBar extends Plugin {// `position: fixed` places the bar against the layout viewport, which iOS shifts away// from the viewport that `getBoundingClientRect()` measures while the keyboard is up.view.set({ left: area.left, top: barTop, width: area.right - area.left });- const shift = getFixedShift(view.element, view.left, view.top);+ // Rendered as `init()` adds it to the body collection.+ const shift = getFixedShift(view.element as HTMLElement, view.left, view.top);view.set({ left: area.left - shift.x, top: barTop - shift.y });view.setTrack(trackLeft - area.left, trackRight - trackLeft, tableRect.left - trackLeft);this.trackBox = { left: trackLeft, right: trackRight };@@ -706,7 +707,7 @@ declare module "ckeditor5" {* How far `position: fixed` places `element` from where its `left` and `top` put it in the* viewport, in pixels.*/-function getFixedShift(element: HTMLElement | null, left: number, top: number) {- const rect = element?.getBoundingClientRect();- return rect ? { x: rect.left - left, y: rect.top - top } : { x: 0, y: 0 };+function getFixedShift(element: HTMLElement, left: number, top: number) {+ const rect = element.getBoundingClientRect();+ return { x: rect.left - left, y: rect.top - top };}