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
client/text editor/drawing canvas: prevent the sidebar to overlap the toolbar
Adorian Dorane93f8d6e272d
diff --git a/apps/client/src/widgets/type_widgets/canvas/Canvas.spec.tsx b/apps/client/src/widgets/type_widgets/canvas/Canvas.spec.tsxindex 0f7c8b8d08..16738ba040 100644--- a/apps/client/src/widgets/type_widgets/canvas/Canvas.spec.tsx+++ b/apps/client/src/widgets/type_widgets/canvas/Canvas.spec.tsx@@ -75,16 +75,20 @@ describe("CanvasEditor", () => {}}- it("reads its position again before pointer input once the drawing moved", async () => {+ it("reads its position again before pointer input or a drop, not on scroll", async () => {const excalidraw = await mount({ isEmbedded: true });point(excalidraw);expect(refresh).not.toHaveBeenCalled();// The note scrolled, so the position that Excalidraw read last is out of date.- offsets = { offsetLeft: 0, offsetTop: 120 };- point(excalidraw);- expect(refresh).toHaveBeenCalledTimes(1);- expect(excalidrawProps).toHaveBeenLastCalledWith(expect.objectContaining({ detectScroll: true }));+ for (const type of [ "pointerover", "pointermove", "pointerdown", "dragover" ]) {+ offsets = { offsetLeft: 0, offsetTop: 120 };+ excalidraw?.dispatchEvent(new Event(type, { bubbles: true }));+ }+ expect(refresh).toHaveBeenCalledTimes(4);+ expect(excalidrawProps).toHaveBeenLastCalledWith(+ expect.objectContaining({ detectScroll: false })+ );});it("leaves the position to Excalidraw in a canvas note, which does not move", async () => {diff --git a/apps/client/src/widgets/type_widgets/canvas/Canvas.tsx b/apps/client/src/widgets/type_widgets/canvas/Canvas.tsxindex ec85906488..fbca428bc4 100644--- a/apps/client/src/widgets/type_widgets/canvas/Canvas.tsx+++ b/apps/client/src/widgets/type_widgets/canvas/Canvas.tsx@@ -71,9 +71,10 @@ export function CanvasEditor({const noteDrop = useCanvasNoteDrop(apiRef, isReadOnly);// Excalidraw maps the pointer with the container position it read last. An embedded editor- // moves with the note, so it reads the position again before the pointer acts. `refresh()`- // renders all of Excalidraw, so it runs only once the position changed.- const refreshPosition = useCallback((e: PointerEvent) => {+ // moves with the note, so it reads the position again before the pointer acts or something+ // drops, and not on each scroll as `detectScroll` would. `refresh()` renders all of+ // Excalidraw, the drawing included, so it runs only once the position changed.+ const refreshPosition = useCallback((e: Event) => {const api = apiRef.current;const container = (e.currentTarget as HTMLElement).querySelector(".excalidraw-container");if (!api || !container) return;@@ -126,6 +127,8 @@ export function CanvasEditor({onWheel={onWheel}onPointerOverCapture={isEmbedded ? refreshPosition : undefined}onPointerMoveCapture={isEmbedded ? refreshPosition : undefined}+ onPointerDownCapture={isEmbedded ? refreshPosition : undefined}+ onDragOverCapture={isEmbedded ? refreshPosition : undefined}><div className="excalidraw-wrapper" {...noteDrop}><Excalidraw@@ -133,7 +136,7 @@ export function CanvasEditor({viewModeEnabled={isReadOnly || options.is("databaseReadonly")}zenModeEnabled={false}isCollaborating={false}- detectScroll={isEmbedded}+ detectScroll={false}handleKeyboardGlobally={false}autoFocus={false}langCode={LANGUAGE_MAPPINGS[locale as DISPLAYABLE_LOCALE_IDS] ?? undefined}diff --git a/apps/client/src/widgets/type_widgets/canvas/CanvasDrawing.css b/apps/client/src/widgets/type_widgets/canvas/CanvasDrawing.cssindex 5316b74fb5..28e7a8f048 100644--- a/apps/client/src/widgets/type_widgets/canvas/CanvasDrawing.css+++ b/apps/client/src/widgets/type_widgets/canvas/CanvasDrawing.css@@ -79,6 +79,27 @@opacity: 0;}+/* Not inherited, so that moving a panel restyles the panel and not its contents. */+@property --side-panel-left {+ syntax: "*";+ inherits: false;+}++@property --side-panel-top {+ syntax: "*";+ inherits: false;+}++@property --side-panel-height {+ syntax: "*";+ inherits: false;+}++@property --side-panel-max-height {+ syntax: "*";+ inherits: false;+}+/* The library and the properties panel beside the drawing, in the top layer, placed by`useSidePanels()`. Resets the user agent style of a popover and Excalidraw's own placement. */.canvas-drawing-editor .excalidraw .Island[data-side-panel][popover] {diff --git a/apps/client/src/widgets/type_widgets/canvas/CanvasDrawing.spec.tsx b/apps/client/src/widgets/type_widgets/canvas/CanvasDrawing.spec.tsxindex 2d0cdaf0eb..eca70279d5 100644--- a/apps/client/src/widgets/type_widgets/canvas/CanvasDrawing.spec.tsx+++ b/apps/client/src/widgets/type_widgets/canvas/CanvasDrawing.spec.tsx@@ -1,9 +1,12 @@+import { readFileSync } from "node:fs";+import { join } from "node:path";+import { exportToSvg } from "@excalidraw/excalidraw";import type { ExcalidrawImperativeAPI } from "@excalidraw/excalidraw/types";import { type ComponentChildren, type RefObject, render, toChildArray, type VNode } from "preact";import { useEffect, useRef, useState } from "preact/hooks";import { act } from "preact/test-utils";-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { afterEach, beforeEach, describe, expect, it, onTestFinished, vi } from "vitest";import Component from "../../../components/component";import type { ContentEditor } from "../../../services/content_renderer";@@ -176,10 +179,12 @@ describe("useSidePanels", () => {useSidePanels(rootRef, isEnabled);return (<div className="scrolling-container">- <div className="include-note-body active">- <div ref={rootRef} className="drawing">- {hasLibrary && <div className="Island sidebar default-sidebar" />}- <div className="App-menu__left" />+ <div className="ck-editor__editable">+ <div className="include-note-body active">+ <div ref={rootRef} className="drawing">+ {hasLibrary && <div className="Island sidebar default-sidebar" />}+ <div className="App-menu__left" />+ </div></div></div></div>@@ -197,7 +202,7 @@ describe("useSidePanels", () => {rects.drawing = { left: 340, top: 200, right: 840, bottom: 520 };vi.spyOn(HTMLElement.prototype, "getBoundingClientRect").mockImplementation(function (this: HTMLElement) {- const { left, top, right, bottom } = rects[this.className] ?? rects.drawing;+ const { left, top, right, bottom } = rects[this.classList[0]] ?? rects.drawing;const size = { width: right - left, height: bottom - top };return { left, top, right, bottom, ...size } as DOMRect;});@@ -223,17 +228,24 @@ describe("useSidePanels", () => {Reflect.deleteProperty(document, "fullscreenElement");});- async function mount(panelHeight: number, hasLibrary = false) {+ /** Mounts the probe, in a text editor whose contextual balloon is `balloon`, if given. */+ async function mount(panelHeight: number, hasLibrary = false, balloon?: HTMLElement) {await act(async () => {render(<SidePanelProbe isEnabled={false} hasLibrary={hasLibrary} />, container);});const viewport = container.querySelector(".scrolling-container");+ const editable = container.querySelector(".ck-editor__editable");const body = container.querySelector(".include-note-body");const panel = container.querySelector<HTMLElement>(".App-menu__left");const library = container.querySelector<HTMLElement>(".default-sidebar");- if (!viewport || !body || !panel) {+ if (!viewport || !editable || !body || !panel) {throw new Error("Expected the probe.");}+ if (balloon) {+ Object.assign(editable, {+ ckeditorInstance: { plugins: { get: () => ({ view: { element: balloon } }) } }+ });+ }Object.defineProperties(viewport, {clientWidth: { value: 750 },clientHeight: { value: 700 }@@ -260,6 +272,28 @@ describe("useSidePanels", () => {.map((name) => panel?.style.getPropertyValue(`--side-panel-${name}`));}+ /** A contextual balloon of the text editor, hidden until `showBalloon()`. */+ function createBalloon() {+ const balloon = document.createElement("div");+ balloon.className = "ck-balloon-panel";+ document.body.append(balloon);+ onTestFinished(() => balloon.remove());+ return balloon;+ }++ /** Shows `balloon` at `rect`, or hides it, as CKEditor does. */+ async function showBalloon(+ balloon: HTMLElement,+ rect: (typeof rects)[string],+ isVisible = true+ ) {+ rects["ck-balloon-panel"] = rect;+ await act(async () => {+ balloon.style.top = `${rect.top}px`;+ balloon.classList.toggle("ck-balloon-panel_visible", isVisible);+ });+ }+it("places the panel level with the drawing's top, on its right or else its left", async () => {const { viewport, panel } = await mount(300);expect(getPlacement(panel)).toEqual([ "848px", "200px", "884px" ]);@@ -307,6 +341,77 @@ describe("useSidePanels", () => {expect(getPlacement(panel)).toEqual([ "848px", "8px", "884px" ]);});+ it("keeps the panel above or below the toolbar of the embed that reaches over it", async () => {+ const balloon = createBalloon();+ const { panel } = await mount(300, false, balloon);++ // Above a drawing at the bottom of the window, with the panel below it and shorter.+ rects.drawing = { left: 340, top: 700, right: 840, bottom: 1020 };+ await showBalloon(balloon, { left: 500, top: 650, right: 1100, bottom: 690 });+ expect(getPlacement(panel)).toEqual([ "848px", "698px", "194px" ]);++ // Below a drawing at the top of the window, with the panel above it.+ rects.drawing = { left: 340, top: 200, right: 840, bottom: 520 };+ Object.defineProperty(panel, "offsetHeight", { value: 600 });+ await showBalloon(balloon, { left: 500, top: 530, right: 1100, bottom: 570 });+ expect(getPlacement(panel)).toEqual([ "848px", "8px", "514px" ]);++ // At the top of the window, over a drawing that starts above it.+ rects.drawing = { left: 340, top: -300, right: 840, bottom: 800 };+ Object.defineProperty(panel, "offsetHeight", { value: 300 });+ await showBalloon(balloon, { left: 500, top: 100, right: 1100, bottom: 140 });+ expect(getPlacement(panel)).toEqual([ "848px", "148px", "744px" ]);++ await showBalloon(balloon, { left: 340, top: 101, right: 840, bottom: 141 });+ expect(getPlacement(panel)).toEqual([ "848px", "8px", "884px" ]);++ await showBalloon(balloon, { left: 500, top: 100, right: 1100, bottom: 140 }, false);+ expect(getPlacement(panel)).toEqual([ "848px", "8px", "884px" ]);+ });++ it("keeps the height of the panel while the note scrolls, and fits it after", async () => {+ const balloon = createBalloon();+ const { viewport, panel } = await mount(600, false, balloon);++ // A toolbar above a drawing at the bottom of the window leaves the panel 194px.+ rects.drawing = { left: 340, top: 700, right: 840, bottom: 1020 };+ await showBalloon(balloon, { left: 500, top: 650, right: 1100, bottom: 690 });+ expect(getPlacement(panel)).toEqual([ "848px", "698px", "194px" ]);++ // Scrolled up by 300px, they leave it 494px.+ rects.drawing = { left: 340, top: 400, right: 840, bottom: 720 };+ rects["ck-balloon-panel"] = { left: 500, top: 350, right: 1100, bottom: 390 };+ viewport.dispatchEvent(new Event("scroll"));+ expect(getPlacement(panel)).toEqual([ "848px", "400px", "194px" ]);++ viewport.dispatchEvent(new Event("scrollend"));+ expect(getPlacement(panel)).toEqual([ "848px", "398px", "494px" ]);++ // Without `scrollend`, a scroll ends once no scroll event comes for a while.+ vi.useFakeTimers({ toFake: [ "setTimeout", "clearTimeout" ] });+ onTestFinished(() => {+ vi.useRealTimers();+ });+ rects.drawing = { left: 340, top: 700, right: 840, bottom: 1020 };+ rects["ck-balloon-panel"] = { left: 500, top: 650, right: 1100, bottom: 690 };+ viewport.dispatchEvent(new Event("scroll"));+ expect(getPlacement(panel)).toEqual([ "848px", "698px", "494px" ]);++ vi.advanceTimersByTime(150);+ expect(getPlacement(panel)).toEqual([ "848px", "698px", "194px" ]);+ });++ it("declares the properties that place a panel as not inherited", () => {+ const styles = readFileSync(join(__dirname, "CanvasDrawing.css"), "utf8");+ const used = new Set(styles.match(/(?<=var\()--side-panel-[\w-]+/g));+ const declared = [ ...styles.matchAll(/@property (--side-panel-[\w-]+) \{([^}]*)\}/g) ]+ .filter(([ , , body ]) => /inherits:\s*false/.test(body))+ .map(([ , name ]) => name);++ expect(used.size).toBe(4);+ expect(new Set(declared)).toEqual(used);+ });+it("keeps the panel in the drawing without room beside it or out of view", async () => {const { viewport, panel } = await mount(300);diff --git a/apps/client/src/widgets/type_widgets/canvas/CanvasDrawing.tsx b/apps/client/src/widgets/type_widgets/canvas/CanvasDrawing.tsxindex 4e49358c6f..70422456f7 100644--- a/apps/client/src/widgets/type_widgets/canvas/CanvasDrawing.tsx+++ b/apps/client/src/widgets/type_widgets/canvas/CanvasDrawing.tsx@@ -19,7 +19,7 @@ import {} from "../../react/hooks";import { useAttachmentEditor } from "../text/attachment_saves";import { useContentEmbedEvent } from "../text/content_embed_tools";-import { useEditableEmbed } from "../text/editable_embed";+import { findTextEditorAround, useEditableEmbed } from "../text/editable_embed";import { CanvasEditor } from "./Canvas";import CanvasDrawingMenu from "./CanvasDrawingMenu";import CanvasEmbedTools, { CanvasTools } from "./CanvasEmbedTools";@@ -496,6 +496,8 @@ export function useIsToolbarOverPanel(rootRef: RefObject<HTMLElement | null>) {const WINDOW_GAP_REM = 0.5;/** The least height of a panel as tall as the drawing, in rem. */const SIDE_PANEL_MIN_HEIGHT_REM = 20;+/** The time without scroll events after which a scroll ends where `scrollend` does not fire. */+const SCROLL_END_DELAY_MS = 150;/** The panels of Excalidraw that go beside the drawing, in the order in which they take a side. */const SIDE_PANELS = [@@ -508,8 +510,9 @@ type Side = "left" | "right";/*** Shows Excalidraw's library and properties panel beside the drawing while the drawing has the- * focus, in the top layer so that no clip or stacking of the note covers them. A panel there has- * `data-side-panel`, and its position in `--side-panel-*`.+ * focus, in the top layer so that no clip or stacking of the note covers them, and clear of the+ * toolbar of the embed. A panel there has `data-side-panel`, and its position in+ * `--side-panel-*`.*/export function useSidePanels(rootRef: RefObject<HTMLElement | null>, isEnabled: boolean) {useEffect(() => {@@ -519,31 +522,62 @@ export function useSidePanels(rootRef: RefObject<HTMLElement | null>, isEnabled:if (!root || !viewport || !embedBody || !isEnabled) return;const panels = new Map<string, HTMLElement>();+ const balloon = findEditorBalloon(root);+ // The max height of each placed panel, which it keeps while the note scrolls.+ const maxHeights = new Map<HTMLElement, number>();+ let isScrolling = false;+ let scrollEndTimeout = 0;const update = () => {// `ContentEmbed` marks the body active while the drawing has the focus.const isShown = embedBody.classList.contains("active")&& !document.fullscreenElement?.contains(root);- const layout = isShown ? getSideLayout(root, viewport) : null;+ const layout = isShown ? getSideLayout(root, viewport, balloon) : null;const takenSides = new Set<Side>();for (const { selector, hasDrawingHeight } of SIDE_PANELS) {const panel = panels.get(selector);if (!panel) continue;- const position = layout- && getSidePanelPosition(layout, panel, hasDrawingHeight, takenSides);+ const heldMaxHeight = isScrolling ? maxHeights.get(panel) : undefined;+ const position = layout && getSidePanelPosition(+ layout, panel, hasDrawingHeight, takenSides, heldMaxHeight+ );if (position) {takenSides.add(position.side);+ maxHeights.set(panel, position.maxHeight);+ } else {+ maxHeights.delete(panel);}placePanel(panel, position || null);}};+ // A panel that changes height lays out and paints its contents again, so while the note+ // scrolls, the panels only move.+ const onScroll = () => {+ isScrolling = true;+ clearTimeout(scrollEndTimeout);+ scrollEndTimeout = window.setTimeout(onScrollEnd, SCROLL_END_DELAY_MS);+ update();+ };+ const onScrollEnd = () => {+ clearTimeout(scrollEndTimeout);+ isScrolling = false;+ update();+ };const resizeObserver = new ResizeObserver(update);resizeObserver.observe(root);resizeObserver.observe(viewport);- const activeObserver = new MutationObserver(update);- activeObserver.observe(embedBody, { attributes: true, attributeFilter: [ "class" ] });+ const attributeObserver = new MutationObserver(update);+ attributeObserver.observe(embedBody, { attributes: true, attributeFilter: [ "class" ] });+ // CKEditor shows, hides and moves the balloon by its classes and its inline position.+ if (balloon) {+ resizeObserver.observe(balloon);+ attributeObserver.observe(balloon, {+ attributes: true,+ attributeFilter: [ "class", "style" ]+ });+ }// The panels mount when they open, and the properties panel takes the height of the// properties of the selection.@@ -567,16 +601,19 @@ export function useSidePanels(rootRef: RefObject<HTMLElement | null>, isEnabled:};const mutationObserver = new MutationObserver(watchPanels);mutationObserver.observe(root, { childList: true, subtree: true });- viewport.addEventListener("scroll", update, { passive: true });+ viewport.addEventListener("scroll", onScroll, { passive: true });+ viewport.addEventListener("scrollend", onScrollEnd);document.addEventListener("fullscreenchange", update);watchPanels();update();return () => {+ clearTimeout(scrollEndTimeout);resizeObserver.disconnect();- activeObserver.disconnect();+ attributeObserver.disconnect();mutationObserver.disconnect();- viewport.removeEventListener("scroll", update);+ viewport.removeEventListener("scroll", onScroll);+ viewport.removeEventListener("scrollend", onScrollEnd);document.removeEventListener("fullscreenchange", update);for (const panel of panels.values()) {placePanel(panel, null);@@ -585,17 +622,31 @@ export function useSidePanels(rootRef: RefObject<HTMLElement | null>, isEnabled:}, [ rootRef, isEnabled ]);}+/**+ * The contextual balloon of the text editor around `element`, which shows the toolbar of its+ * embed.+ */+function findEditorBalloon(element: HTMLElement) {+ return findTextEditorAround(element)?.plugins.get("ContextualBalloon").view.element ?? null;+}+interface SideLayout {drawing: DOMRect;/** The window, which the panels stay inside. */area: VisibleArea;+ /** The balloon of the text editor while it shows, which the panels keep clear of. */+ balloon: DOMRect | null;gap: number;/** The least height of a panel as tall as the drawing. */minHeight: number;}/** The layout of the panels beside `root`, or `null` while it is scrolled out of `viewport`. */-function getSideLayout(root: HTMLElement, viewport: HTMLElement): SideLayout | null {+function getSideLayout(+ root: HTMLElement,+ viewport: HTMLElement,+ balloon: HTMLElement | null+): SideLayout | null {const rem = parseFloat(getComputedStyle(document.documentElement).fontSize);const drawing = root.getBoundingClientRect();const noteArea = getVisibleArea(viewport);@@ -606,6 +657,9 @@ function getSideLayout(root: HTMLElement, viewport: HTMLElement): SideLayout | nreturn {drawing,area: getWindowArea(),+ balloon: balloon?.classList.contains("ck-balloon-panel_visible")+ ? balloon.getBoundingClientRect()+ : null,gap: WINDOW_GAP_REM * rem,minHeight: SIDE_PANEL_MIN_HEIGHT_REM * rem};@@ -613,29 +667,58 @@ function getSideLayout(root: HTMLElement, viewport: HTMLElement): SideLayout | n/*** The position of `panel` beside the drawing: on its right when the window has room there and- * no other panel took that side, otherwise on its left, level with the top of the drawing and- * inside the window. `null` when no free side has room.+ * no other panel took that side, otherwise on its left, level with the top of the drawing, inside+ * the window and clear of the balloon. `null` when no free side has room. A `heldMaxHeight`+ * replaces the room that the window and the balloon leave, so the panel can reach past the window.*/function getSidePanelPosition(- { drawing, area, gap, minHeight }: SideLayout,+ layout: SideLayout,panel: HTMLElement,hasDrawingHeight: boolean,- takenSides: ReadonlySet<Side>+ takenSides: ReadonlySet<Side>,+ heldMaxHeight?: number) {- const placement = getSidePanelLeft(drawing, area, panel.offsetWidth, gap, takenSides);+ const { drawing, area, gap, minHeight } = layout;+ const width = panel.offsetWidth;+ const placement = getSidePanelLeft(drawing, area, width, gap, takenSides);if (!placement) {return null;}- const maxHeight = area.bottom - area.top - 2 * gap;+ const range = getSidePanelRange(layout, placement.left, width);+ const maxHeight = heldMaxHeight ?? range.bottom - range.top;const contentHeight = hasDrawingHeight? Math.max(drawing.height, minHeight): panel.offsetHeight;const height = Math.min(contentHeight, maxHeight);- const top = Math.max(area.top + gap, Math.min(drawing.top, area.bottom - gap - height));+ const top = Math.max(range.top, Math.min(drawing.top, range.bottom - height));return { ...placement, top, maxHeight, height: hasDrawingHeight ? height : null };}+/**+ * The top and bottom of the part of the window that holds a panel at `left`, `width` wide. While+ * the balloon reaches over the panel's column, that part is on the side of the balloon where the+ * drawing shows.+ */+function getSidePanelRange(+ { drawing, area, balloon, gap }: SideLayout,+ left: number,+ width: number+) {+ let top = area.top + gap;+ let bottom = area.bottom - gap;+ if (balloon && balloon.left < left + width && balloon.right > left) {+ const drawingMiddle = (Math.max(drawing.top, area.top)+ + Math.min(drawing.bottom, area.bottom)) / 2;+ if (drawingMiddle > (balloon.top + balloon.bottom) / 2) {+ top = Math.max(top, balloon.bottom + gap);+ } else {+ bottom = Math.min(bottom, balloon.top - gap);+ }+ }+ return { top, bottom: Math.max(top, bottom) };+}+type SidePanelPosition = NonNullable<ReturnType<typeof getSidePanelPosition>>;/** Moves `panel` to `position` beside the drawing, or back into the drawing for `null`. */diff --git a/packages/ckeditor5/src/plugins/content_embed/content_embed.ts b/packages/ckeditor5/src/plugins/content_embed/content_embed.tsindex ae5d102723..c29ddd9ba0 100644--- a/packages/ckeditor5/src/plugins/content_embed/content_embed.ts+++ b/packages/ckeditor5/src/plugins/content_embed/content_embed.ts@@ -518,7 +518,7 @@ class ContentEmbedEditing extends Plugin {propertyPrefix: '--include-note',isWidthResizable: true,isHeightResizable: true,- getAnchor: getResizeAnchor,+ getAnchor: getEmbedAnchor,heightTarget: '.include-note-content',minWidth: MIN_EMBED_SIZE.width,minHeight: MIN_EMBED_SIZE.height,@@ -1308,8 +1308,11 @@ function getEmbedPosition( embed: ModelElement ): PositionValue {return SAVED_POSITIONS.includes( position ) ? position as PositionValue : 'center';}-/** The edge of `embed` that stays in place while it is resized, as the stylesheet places it. */-function getResizeAnchor( embed: ModelElement ): ResizeAnchor {+/**+ * The edge that the stylesheet places `embed` against, which stays in place while it is resized+ * and which its toolbar is level with.+ */+export function getEmbedAnchor( embed: ModelElement ): ResizeAnchor {const position = getEmbedPosition( embed );if ( position === 'left' || position === 'wrap-left' ) {return 'left';diff --git a/packages/ckeditor5/src/plugins/content_embed/content_embed_toolbar.spec.ts b/packages/ckeditor5/src/plugins/content_embed/content_embed_toolbar.spec.tsindex c71414dd8c..de27a5d6d6 100644--- a/packages/ckeditor5/src/plugins/content_embed/content_embed_toolbar.spec.ts+++ b/packages/ckeditor5/src/plugins/content_embed/content_embed_toolbar.spec.ts@@ -1,4 +1,7 @@-import { ClassicEditor, Essentials, Paragraph, Plugin, toWidget, Widget, WidgetToolbarRepository, _setModelData as setModelData } from "ckeditor5";+import {+ ClassicEditor, Essentials, Paragraph, Plugin, type PositioningFunction, Rect, toWidget, Widget,+ WidgetToolbarRepository, _setModelData as setModelData+} from "ckeditor5";import { beforeEach, describe, expect, it } from "vitest";import { createTestEditor } from "../../../test/editor-kit.js";@@ -59,17 +62,22 @@ class SectionNoClassWidget extends Plugin {// Helpers// ----------------------------------------------------------------------------function getRelatedElementFn(ed: ClassicEditor): (selection: unknown) => unknown {+function getToolbarDefinition(ed: ClassicEditor) {const repository = ed.plugins.get(WidgetToolbarRepository) as unknown as {_toolbarDefinitions: Map<string, {getRelatedElement: (selection: unknown) => unknown;+ positions: PositioningFunction[];}>;};const def = repository._toolbarDefinitions.get("contentEmbed");if (!def) {throw new Error("ContentEmbed toolbar definition not found in WidgetToolbarRepository.");}- return def.getRelatedElement;+ return def;+}++function getRelatedElementFn(ed: ClassicEditor): (selection: unknown) => unknown {+ return getToolbarDefinition(ed).getRelatedElement;}/** A selection on nothing, standing in for the view selection. */@@ -122,6 +130,40 @@ describe("ContentEmbedToolbar", () => {]);});+ it("is level with the edge that the embed is placed against, else centered", () => {+ const { positions } = getToolbarDefinition(editor);+ const target = new Rect({+ left: 100, top: 300, right: 400, bottom: 500, width: 300, height: 200+ });+ const balloon = new Rect({+ left: 0, top: 0, right: 200, bottom: 40, width: 200, height: 40+ });+ const viewport = new Rect(window);+ const getFirstPositions = (data: string) => {+ editor.setData(data);+ editor.model.change((writer) => {+ const embed = editor.model.document.getRoot()?.getChild(0);+ if (embed?.is("element", "contentEmbed")) {+ writer.setSelection(embed, "on");+ }+ });+ return positions+ .map((position) => position(target, balloon, viewport))+ .filter((position) => position !== null)+ .slice(0, 2)+ .map(({ name, left }) => `${name} ${left}`);+ };+ const embed = (attributes: string) => "<figure class=\"include-note\" data-note-id=\"n1\""+ + ` data-box-size="medium"${attributes}></figure>`;++ expect(getFirstPositions(embed(" data-position=\"wrap-left\"")))+ .toEqual([ "arrow_sw 100", "arrow_nw 100" ]);+ expect(getFirstPositions(embed(" data-position=\"right\"")))+ .toEqual([ "arrow_se 200", "arrow_ne 200" ]);+ expect(getFirstPositions(embed(""))).toEqual([ "arrow_s 150", "arrow_sw 225" ]);+ expect(getFirstPositions("<p>Text</p>")).toEqual([ "arrow_s 150", "arrow_sw 225" ]);+ });+describe("getRelatedElement", () => {it("returns the include-note widget element when an contentEmbed model element is selected", () => {editor.model.change((writer) => {diff --git a/packages/ckeditor5/src/plugins/content_embed/content_embed_toolbar.ts b/packages/ckeditor5/src/plugins/content_embed/content_embed_toolbar.tsindex c1c6da08f2..c39fc9b687 100644--- a/packages/ckeditor5/src/plugins/content_embed/content_embed_toolbar.ts+++ b/packages/ckeditor5/src/plugins/content_embed/content_embed_toolbar.ts@@ -1,10 +1,16 @@-import { Plugin, WidgetToolbarRepository, isWidget, type ViewElement } from "ckeditor5";+import {+ BalloonPanelView, isWidget, Plugin, type PositioningFunction, type ViewDocumentSelection,+ type ViewElement, WidgetToolbarRepository+} from "ckeditor5";++import type { ResizeAnchor } from "../resizable_widgets/resizable_widgets.js";import ContentEmbed, {CONVERT_EMBED_TO_LINK_COMMAND,CONTENT_EMBED_MENU,CONTENT_EMBED_DISPLAY_MODE_SEPARATOR,DISPLAY_MODE_BUTTONS,DISPLAY_MODES,+ getEmbedAnchor,TOGGLE_CAPTION_COMMAND_NAME,TOGGLE_EDITABLE_COMMAND_NAME,TOGGLE_TITLE_COMMAND_NAME@@ -30,6 +36,11 @@ export default class ContentEmbedToolbar extends Plugin {afterInit() {const editor = this.editor;const widgetToolbarRepository = editor.plugins.get(WidgetToolbarRepository);+ const getAnchor = () => {+ const embed = findRelatedEmbed(editor.editing.view.document.selection);+ const modelEmbed = embed && editor.editing.mapper.toModelElement(embed);+ return modelEmbed ? getEmbedAnchor(modelEmbed) : "center";+ };widgetToolbarRepository.register("contentEmbed", {items: [@@ -46,27 +57,76 @@ export default class ContentEmbedToolbar extends Plugin {CONTENT_EMBED_MENU],balloonClassName: "ck-toolbar-container include-note-toolbar",- getRelatedElement(selection) {- const selectedElement = selection.getSelectedElement();-- if (selectedElement && isContentEmbedWidget(selectedElement)) {- return selectedElement;- }-- // The toolbar stays on the embed while its caption is edited.- for (const ancestor of selection.getFirstPosition()?.getAncestors() ?? []) {- if (ancestor.is("element") && isContentEmbedWidget(ancestor)) {- return ancestor;- }- }-- return null;- }+ positions: getToolbarPositions(getAnchor),+ getRelatedElement: findRelatedEmbed});}}+/** The embed that the toolbar shows for: the selected one, or the one whose caption is edited. */+function findRelatedEmbed(selection: ViewDocumentSelection) {+ const selectedElement = selection.getSelectedElement();++ if (selectedElement && isContentEmbedWidget(selectedElement)) {+ return selectedElement;+ }++ for (const ancestor of selection.getFirstPosition()?.getAncestors() ?? []) {+ if (ancestor.is("element") && isContentEmbedWidget(ancestor)) {+ return ancestor;+ }+ }++ return null;+}+function isContentEmbedWidget(element: ViewElement): boolean {return isWidget(element) && element.hasClass("include-note");}++/**+ * The positions of the toolbar: level with the edge of the embed that `getAnchor()` returns, then,+ * or where those do not fit, the positions that `WidgetToolbarRepository` gives a widget toolbar.+ */+function getToolbarPositions(getAnchor: () => ResizeAnchor): PositioningFunction[] {+ const {+ northArrowSouth, northArrowSouthWest, northArrowSouthEast, southArrowNorth,+ southArrowNorthWest, southArrowNorthEast, viewportStickyNorth+ } = BalloonPanelView.defaultPositions;++ return [+ alignToAnchor(northArrowSouth, { left: "arrow_sw", right: "arrow_se" }, getAnchor),+ alignToAnchor(southArrowNorth, { left: "arrow_nw", right: "arrow_ne" }, getAnchor),+ alignToAnchor(viewportStickyNorth, { left: "arrowless", right: "arrowless" }, getAnchor),+ northArrowSouth, northArrowSouthWest, northArrowSouthEast,+ southArrowNorth, southArrowNorthWest, southArrowNorthEast, viewportStickyNorth+ ];+}++/** The arrow names of a toolbar level with the left and with the right edge of its target. */+type EdgeArrows = Record<"left" | "right", string>;++/**+ * `position` moved level with the edge of the target that `getAnchor()` returns, with the arrow+ * that `arrows` names for that edge. A centered target gets no position.+ */+function alignToAnchor(+ position: PositioningFunction,+ arrows: EdgeArrows,+ getAnchor: () => ResizeAnchor+): PositioningFunction {+ return (targetRect, balloonRect, viewportRect, limiterRect) => {+ const anchor = getAnchor();+ if (anchor !== "left" && anchor !== "right") {+ return null;+ }++ const result = position(targetRect, balloonRect, viewportRect, limiterRect);+ return result && {+ ...result,+ left: anchor === "left" ? targetRect.left : targetRect.right - balloonRect.width,+ name: arrows[anchor]+ };+ };+}