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/canvas: improve the fullscreen experience
Adorian Dorana44d7ee82cb4
diff --git a/apps/client/src/widgets/type_widgets/canvas/CanvasDrawing.css b/apps/client/src/widgets/type_widgets/canvas/CanvasDrawing.cssindex f946759d92..8d919e39f1 100644--- a/apps/client/src/widgets/type_widgets/canvas/CanvasDrawing.css+++ b/apps/client/src/widgets/type_widgets/canvas/CanvasDrawing.css@@ -27,6 +27,13 @@> .canvas-render {height: 100%;+ transition: opacity 150ms ease-out;+ }++ /* Hidden while `useRecenteringOnFullscreen()` centers the drawing in its new size. */+ &.recentering > .canvas-render {+ opacity: 0;+ transition: none;}}diff --git a/apps/client/src/widgets/type_widgets/canvas/CanvasDrawing.spec.tsx b/apps/client/src/widgets/type_widgets/canvas/CanvasDrawing.spec.tsxindex dbeb3a6a90..91001ee416 100644--- a/apps/client/src/widgets/type_widgets/canvas/CanvasDrawing.spec.tsx+++ b/apps/client/src/widgets/type_widgets/canvas/CanvasDrawing.spec.tsx@@ -1,6 +1,6 @@import { exportToSvg } from "@excalidraw/excalidraw";import type { ExcalidrawImperativeAPI } from "@excalidraw/excalidraw/types";-import { type ComponentChildren, render, toChildArray, type VNode } from "preact";+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";@@ -23,8 +23,10 @@ vi.mock("../text/attachment_saves", () => ({ useAttachmentEditor: () => detailEdconst canvasEditorProps = vi.fn();const persistenceArgs = vi.fn();+const canvasApi = { scrollToContent: vi.fn() };interface MockCanvasEditorProps {+ apiRef?: RefObject<unknown>;isDesktopLayout?: boolean;isReadOnly?: boolean;children?: ComponentChildren;@@ -555,6 +557,43 @@ describe("CanvasDrawing", () => {expect(getEditingState()).toEqual({ isReadOnly: false, menu: true, tools: true });});+ it("centers the drawing after a change of fullscreen, hidden until then", async () => {+ await mount();+ const root = box.querySelector(".canvas-drawing-editor");+ const isHidden = () => !!root?.classList.contains("recentering");+ const { apiRef } = canvasEditorProps.mock.lastCall?.[0] as MockCanvasEditorProps;+ if (!apiRef) {+ throw new Error("Expected the API reference of the editor.");+ }+ apiRef.current = canvasApi;+ canvasApi.scrollToContent.mockClear();+ const other = document.createElement("div");+ document.body.append(other);++ for (const name of [ "enterFullscreen", "leaveFullscreen" ]) {+ await act(async () => {+ other.dispatchEvent(new Event("fullscreenChangeStart", { bubbles: true }));+ });+ expect(isHidden()).toBe(false);+ await act(async () => {+ box.dispatchEvent(new Event("fullscreenChangeStart", { bubbles: true }));+ });+ expect(isHidden()).toBe(true);++ await act(async () => {+ box.dispatchEvent(new Event(name, { bubbles: true }));+ other.dispatchEvent(new Event(name, { bubbles: true }));+ });+ // Shown again once Excalidraw drew the centered view, on the next frame.+ expect(isHidden()).toBe(true);+ await vi.waitFor(() => expect(isHidden()).toBe(false));+ }+ expect(canvasApi.scrollToContent).toHaveBeenCalledTimes(2);+ expect(canvasApi.scrollToContent).toHaveBeenCalledWith();+ apiRef.current = null;+ other.remove();+ });+it("takes the focus that its embed box holds once Excalidraw renders", async () => {box.focus();const excalidraw = await mount();diff --git a/apps/client/src/widgets/type_widgets/canvas/CanvasDrawing.tsx b/apps/client/src/widgets/type_widgets/canvas/CanvasDrawing.tsxindex b8e4b63292..2b77c27fbc 100644--- a/apps/client/src/widgets/type_widgets/canvas/CanvasDrawing.tsx+++ b/apps/client/src/widgets/type_widgets/canvas/CanvasDrawing.tsx@@ -15,7 +15,7 @@ import { getEffectiveThemeStyle } from "../../../services/theme";import { isDesktop } from "../../../services/utils";import { useColorScheme, useEffectiveReadOnly } from "../../react/hooks";import { useAttachmentEditor } from "../text/attachment_saves";-import { useIsContentEmbedEditable } from "../text/content_embed_tools";+import { useContentEmbedEvent, useIsContentEmbedEditable } from "../text/content_embed_tools";import { CanvasEditor } from "./Canvas";import CanvasDrawingMenu from "./CanvasDrawingMenu";import CanvasEmbedTools from "./CanvasEmbedTools";@@ -47,13 +47,18 @@ export default function CanvasDrawing({ attachment, editor }: CanvasDrawingProps);const isToolbarOverPanel = useIsToolbarOverPanel(rootRef);useFocusFromEmbedBox(rootRef);+ const isRecentering = useRecenteringOnFullscreen(rootRef, apiRef);useSidePanels(rootRef, isEditable);useTopLayerContextMenu(rootRef, apiRef);return (<divref={rootRef}- className={clsx("canvas-drawing-editor", isToolbarOverPanel && "toolbar-over-panel")}+ className={clsx(+ "canvas-drawing-editor",+ isToolbarOverPanel && "toolbar-over-panel",+ isRecentering && "recentering"+ )}><CanvasEditorapiRef={apiRef}@@ -133,6 +138,36 @@ export function CanvasDrawingDetail({ attachment, note, noteContext }: CanvasDra);}+/**+ * Centers the drawing once fullscreen changed its size, which moves the view off center. Returns+ * whether the drawing is hidden for it: from the start of the change until it is drawn centered.+ */+function useRecenteringOnFullscreen(+ rootRef: RefObject<HTMLElement>,+ apiRef: RefObject<ExcalidrawImperativeAPI>+) {+ const [ isRecentering, setIsRecentering ] = useState(false);+ const frameRef = useRef(0);++ useContentEmbedEvent(rootRef, "fullscreenChangeStart", () => {+ cancelAnimationFrame(frameRef.current);+ setIsRecentering(true);+ });++ const recenter = () => {+ apiRef.current?.scrollToContent();+ // Excalidraw draws the centered view on the next frame.+ frameRef.current = requestAnimationFrame(() => {+ frameRef.current = requestAnimationFrame(() => setIsRecentering(false));+ });+ };+ useContentEmbedEvent(rootRef, "enterFullscreen", recenter);+ useContentEmbedEvent(rootRef, "leaveFullscreen", recenter);+ useEffect(() => () => cancelAnimationFrame(frameRef.current), []);++ return isRecentering;+}+/*** Moves the focus into Excalidraw when the embed box around the drawing holds it. Excalidraw* renders its container only once its language loads, which can be after the box took the focus.diff --git a/apps/client/src/widgets/type_widgets/canvas/CanvasEmbedTools.spec.tsx b/apps/client/src/widgets/type_widgets/canvas/CanvasEmbedTools.spec.tsxindex e114856ee5..ee31376ef9 100644--- a/apps/client/src/widgets/type_widgets/canvas/CanvasEmbedTools.spec.tsx+++ b/apps/client/src/widgets/type_widgets/canvas/CanvasEmbedTools.spec.tsx@@ -8,6 +8,7 @@ const translate = vi.hoisted(() => (key: string) => `t:${key}`);vi.mock("@excalidraw/excalidraw", () => ({useI18n: () => ({ t: translate, langCode: "en" })}));+vi.mock("../../../services/i18n", () => ({ t: (key: string) => key }));const { default: CanvasEmbedTools } = await import("./CanvasEmbedTools");const {@@ -43,12 +44,18 @@ describe("CanvasEmbedTools", () => {const rootRef = useRef<HTMLDivElement>(null);const apiRef = useRef<ExcalidrawImperativeAPI>(api.api);return (- <figure className="include-note">- <div ref={rootRef}>- <div className="excalidraw-container" tabIndex={0} />- <button type="button" data-testid="button-undo" onClick={() => undo()} />- <button type="button" data-testid="button-redo" disabled />- <CanvasEmbedTools rootRef={rootRef} apiRef={apiRef} isEditable={isEditable} />+ <figure className="include-note" data-box-size="medium">+ <div className="include-note-content">+ <div ref={rootRef}>+ <div className="excalidraw-container" tabIndex={0} />+ <button type="button" data-testid="button-undo" onClick={() => undo()} />+ <button type="button" data-testid="button-redo" disabled />+ <CanvasEmbedTools+ rootRef={rootRef}+ apiRef={apiRef}+ isEditable={isEditable}+ />+ </div></div></figure>);@@ -133,7 +140,7 @@ describe("CanvasEmbedTools", () => {const stopOutside = watchContentEmbedTools(document.createElement("div"), outside);const { embed } = await mount();- const root = embed.querySelector(":scope > div");+ const root = embed.querySelector(".include-note-content > div");expect(inside).toHaveBeenCalledTimes(1);expect(outside).not.toHaveBeenCalled();expect(root?.hasAttribute("data-embed-tools")).toBe(true);@@ -190,6 +197,33 @@ describe("CanvasEmbedTools", () => {expect(getEnabled()).toContain("zoomOut:false");});+ it("offers fullscreen after zoom in while the title of the embed is hidden", async () => {+ const { embed, provider } = await mount();+ const box = embed.querySelector<HTMLElement>(".include-note-content");+ if (!box) {+ throw new Error("Expected the content box of the embed.");+ }+ box.requestFullscreen = vi.fn(async () => {});+ const getLastTool = () => provider.getTools().at(-1);+ expect(getLastTool()?.id).toBe("zoomIn");++ embed.dataset.hideTitle = "true";+ expect(getLastTool()).toEqual({+ id: "fullscreen", label: "common.fullscreen", icon: ICON, group: "zoom"+ });+ // The sizes whose title row has a fullscreen button.+ const offeredBySize = [ "small", "full", "medium" ].map((size) => {+ embed.dataset.boxSize = size;+ return `${size}:${getLastTool()?.id === "fullscreen"}`;+ });+ expect(offeredBySize).toEqual([ "small:false", "full:true", "medium:true" ]);++ provider.execute("fullscreen");+ expect(box.requestFullscreen).toHaveBeenCalledOnce();+ expect(api.updateScene).not.toHaveBeenCalled();+ expect(api.setActiveTool).not.toHaveBeenCalled();+ });+it("runs a tool with the focus in the drawing", async () => {const { provider } = await mount();diff --git a/apps/client/src/widgets/type_widgets/canvas/CanvasEmbedTools.tsx b/apps/client/src/widgets/type_widgets/canvas/CanvasEmbedTools.tsxindex 5cf0b93f06..bbdd51512c 100644--- a/apps/client/src/widgets/type_widgets/canvas/CanvasEmbedTools.tsx+++ b/apps/client/src/widgets/type_widgets/canvas/CanvasEmbedTools.tsx@@ -8,6 +8,7 @@ import moreToolsIcon from "boxicons/svg/regular/bx-category.svg?raw";import ellipseIcon from "boxicons/svg/regular/bx-circle.svg?raw";import eraserIcon from "boxicons/svg/regular/bx-eraser.svg?raw";import textIcon from "boxicons/svg/regular/bx-font.svg?raw";+import fullscreenIcon from "boxicons/svg/regular/bx-fullscreen.svg?raw";import imageIcon from "boxicons/svg/regular/bx-image.svg?raw";import lockIcon from "boxicons/svg/regular/bx-lock-open-alt.svg?raw";import lineIcon from "boxicons/svg/regular/bx-minus.svg?raw";@@ -24,11 +25,13 @@ import handIcon from "boxicons/svg/solid/bxs-hand.svg?raw";import type { RefObject } from "preact";import { useEffect, useState } from "preact/hooks";+import { t } from "../../../services/i18n";import {type ContentEmbedTool,type ContentEmbedToolbarItem,type ContentEmbedToolProvider,- registerContentEmbedTools+ registerContentEmbedTools,+ showContentEmbedFullscreen} from "../text/content_embed_tools";/** The tools with a button of their own, in the order of their buttons. */@@ -42,6 +45,8 @@ const TOOLS = [ ...MAIN_TOOLS, ...EXTRA_TOOLS ];export const LOCK = "lock";/** The button that opens the "More tools" menu, named by Excalidraw's `toolBar.extraTools`. */export const MORE_TOOLS = "moreTools";+/** Shows the embed in fullscreen, as the button of its title row does while the title is hidden. */+const FULLSCREEN = "fullscreen";/** The commands that click Excalidraw's own `button-undo` and `button-redo`. */export const HISTORY_ACTIONS = [ "undo", "redo" ] as const;@@ -184,7 +189,10 @@ export class CanvasTools implements ContentEmbedToolProvider {return [];}- const zoomTools = this.getZoomTools(appState.zoom.value);+ const zoomTools = [+ ...this.getZoomTools(appState.zoom.value),+ ...this.getFullscreenTools()+ ];return this.isEditable? [ ...this.getEditingTools(appState.activeTool), ...zoomTools ]: zoomTools;@@ -202,7 +210,9 @@ export class CanvasTools implements ContentEmbedToolProvider {const appState = api.getAppState();const getZoom = ZOOMS[id];- if (getZoom) {+ if (id === FULLSCREEN) {+ showContentEmbedFullscreen(this.rootRef.current);+ } else if (getZoom) {api.updateScene({ appState: getZoomState(appState, getZoom(appState.zoom.value)) });} else if (this.isEditable) {this.runEditingTool(api, appState, id);@@ -265,6 +275,22 @@ export class CanvasTools implements ContentEmbedToolProvider {];}+ /**+ * Fullscreen, while the title of the embed is hidden at a box size whose title row has a button+ * for it.+ */+ private getFullscreenTools(): ContentEmbedTool[] {+ const embed = this.rootRef.current?.closest<HTMLElement>(".include-note");+ const { hideTitle, boxSize } = embed?.dataset ?? {};+ if (hideTitle !== "true" || (boxSize !== "medium" && boxSize !== "full")) {+ return [];+ }++ return [+ { id: FULLSCREEN, label: t("common.fullscreen"), icon: fullscreenIcon, group: "zoom" }+ ];+ }+/** Zoom out, the zoom level that resets it, and zoom in. */private getZoomTools(zoom: number): ContentEmbedTool[] {return [diff --git a/apps/client/src/widgets/type_widgets/canvas/excalidraw_contract.spec.ts b/apps/client/src/widgets/type_widgets/canvas/excalidraw_contract.spec.tsindex a3229765a1..f39d1b5fa6 100644--- a/apps/client/src/widgets/type_widgets/canvas/excalidraw_contract.spec.ts+++ b/apps/client/src/widgets/type_widgets/canvas/excalidraw_contract.spec.ts@@ -15,7 +15,8 @@ const { FITTED_MENU_STYLES } = await import("./CanvasDrawing");/** The classes of Trilium that `CanvasDrawing.css` selects. Every other class is Excalidraw's. */const TRILIUM_CLASSES = new Set(["note-detail", "canvas-drawing", "canvas-drawing-editor", "canvas-render",- "canvas-drawing-picture", "toolbar-over-panel", "include-note", "include-note-body",+ "canvas-drawing-picture", "toolbar-over-panel", "recentering", "include-note",+ "include-note-body","include-note-content", "active", "tn-icon"]);diff --git a/apps/client/src/widgets/type_widgets/text/ContentEmbed.spec.tsx b/apps/client/src/widgets/type_widgets/text/ContentEmbed.spec.tsxindex 3a871a28a1..a3e2b64c80 100644--- a/apps/client/src/widgets/type_widgets/text/ContentEmbed.spec.tsx+++ b/apps/client/src/widgets/type_widgets/text/ContentEmbed.spec.tsx@@ -288,6 +288,67 @@ describe("ContentEmbed", () => {Reflect.deleteProperty(document, "exitFullscreen");});+ it("tells its content when its fullscreen changes, and once it took the new size", () => {+ const observers: { callback: (entries: unknown[]) => void; isObserving: boolean }[] = [];+ vi.stubGlobal("ResizeObserver", class {+ private readonly entry;++ constructor(callback: (entries: unknown[]) => void) {+ this.entry = { callback, isObserving: false };+ observers.push(this.entry);+ }++ observe() {+ this.entry.isObserving = true;+ }++ disconnect() {+ this.entry.isObserving = false;+ }+ });+ const resize = () => {+ for (const observer of observers.filter((entry) => entry.isObserving)) {+ observer.callback([]);+ }+ };+ const setFullscreenElement = (element: Element | null) => {+ Object.defineProperty(document, "fullscreenElement", {+ value: element,+ configurable: true+ });+ document.dispatchEvent(new Event("fullscreenchange"));+ };+ renderBox({ boxSize: "medium" });+ const box = contentBox();+ const events: string[] = [];+ const listener = (event: Event) => events.push(`${event.type}:${event.target === box}`);+ const names = [ "fullscreenChangeStart", "enterFullscreen", "leaveFullscreen" ];+ for (const name of names) {+ document.addEventListener(name, listener);+ }++ setFullscreenElement(box);+ expect(events).toEqual([ "fullscreenChangeStart:true" ]);+ resize();+ resize();+ expect(events).toEqual([ "fullscreenChangeStart:true", "enterFullscreen:true" ]);++ setFullscreenElement(null);+ resize();+ expect(events.slice(2)).toEqual([ "fullscreenChangeStart:true", "leaveFullscreen:true" ]);++ // Another element in fullscreen leaves the box as it is.+ setFullscreenElement(document.body);+ resize();+ expect(events).toHaveLength(4);++ for (const name of names) {+ document.removeEventListener(name, listener);+ }+ Reflect.deleteProperty(document, "fullscreenElement");+ vi.unstubAllGlobals();+ });+it("opens its menu on a right click on the title row, leaving the title link its own", () => {renderBox({ notePath: "owner", viewScope: ATTACHMENT_SCOPE });const row = container.querySelector(".include-note-title-row");diff --git a/apps/client/src/widgets/type_widgets/text/ContentEmbed.tsx b/apps/client/src/widgets/type_widgets/text/ContentEmbed.tsxindex 6b07b134d8..0d6dea68b6 100644--- a/apps/client/src/widgets/type_widgets/text/ContentEmbed.tsx+++ b/apps/client/src/widgets/type_widgets/text/ContentEmbed.tsx@@ -1,5 +1,6 @@import clsx from "clsx";-import { useLayoutEffect, useRef, useState } from "preact/hooks";+import type { RefObject } from "preact";+import { useEffect, useLayoutEffect, useRef, useState } from "preact/hooks";import appContext from "../../../components/app_context";import linkContextMenu from "../../../menus/link_context_menu";@@ -10,6 +11,7 @@ import ActionButton from "../../react/ActionButton";import { useFocusWithin } from "../../react/hooks";import Icon from "../../react/Icon";import OverlayControlGroup, { OverlayControlButton } from "../../react/OverlayControlGroup";+import { type ContentEmbedEvent, showContentEmbedFullscreen } from "./content_embed_tools";/** An action on the embedded note or attachment, offered as a button in the title row. */export interface ContentEmbedAction {@@ -51,6 +53,7 @@ export default function ContentEmbed({}: ContentEmbedProps) {const contentRef = useRef<HTMLDivElement>(null);const isContentActive = useFocusWithin(contentRef);+ useFullscreenEvents(contentRef);const [ isExpanded, setIsExpanded ] = useState(false);const isExpandable = boxSize === "expandable";const hasFullscreen = boxSize === "medium" || boxSize === "full";@@ -101,9 +104,7 @@ export default function ContentEmbed({text={t("common.fullscreen")}onClick={(e) => {e.stopPropagation();- contentRef.current?.requestFullscreen().catch((error: unknown) => {- console.warn("Could not show the embed in fullscreen:", error);- });+ showContentEmbedFullscreen(contentRef.current);}}/>)}@@ -249,6 +250,41 @@ function ContentEmbedActionButton({ className, action }: {* Opens the menu of the embed for a right click on its title row. The title link is left to the* handler of every link, which opens the same menu, or a quick edit with Ctrl.*/+/**+ * Dispatches `fullscreenChangeStart` on the content box as it enters or leaves fullscreen, then+ * `enterFullscreen` or `leaveFullscreen` once it has the size that fullscreen gives or takes back.+ */+function useFullscreenEvents(contentRef: RefObject<HTMLElement>) {+ useEffect(() => {+ const content = contentRef.current;+ if (!content) return;++ let isFullscreen = document.fullscreenElement === content;+ let observer: ResizeObserver | undefined;+ const onFullscreenChange = () => {+ if ((document.fullscreenElement === content) === isFullscreen) return;+ isFullscreen = !isFullscreen;+ const name: ContentEmbedEvent = isFullscreen ? "enterFullscreen" : "leaveFullscreen";+ content.dispatchEvent(new Event("fullscreenChangeStart", { bubbles: true }));++ // Created after the observers of the content, such as Excalidraw's, so it runs after+ // them, once they have read the new size.+ observer?.disconnect();+ observer = new ResizeObserver(() => {+ observer?.disconnect();+ content.dispatchEvent(new Event(name, { bubbles: true }));+ });+ observer.observe(content);+ };++ document.addEventListener("fullscreenchange", onFullscreenChange);+ return () => {+ document.removeEventListener("fullscreenchange", onFullscreenChange);+ observer?.disconnect();+ };+ }, [ contentRef ]);+}+function openMenuOnRightClick(e: MouseEvent, notePath: string, viewScope?: ViewScope) {if (e.target instanceof Element && e.target.closest("a")) {return;diff --git a/apps/client/src/widgets/type_widgets/text/content_embed_tools.ts b/apps/client/src/widgets/type_widgets/text/content_embed_tools.tsindex bd05005df4..564789d015 100644--- a/apps/client/src/widgets/type_widgets/text/content_embed_tools.ts+++ b/apps/client/src/widgets/type_widgets/text/content_embed_tools.ts@@ -1,5 +1,5 @@import type { RefObject } from "preact";-import { useEffect, useState } from "preact/hooks";+import { useEffect, useRef, useState } from "preact/hooks";/** A button that the content of an embed adds to the toolbar of the embed. */export interface ContentEmbedTool {@@ -41,6 +41,13 @@ export interface ContentEmbedToolProvider {hasEditableFlag?: boolean;}+/**+ * What an embed tells its content, with an event that bubbles from its content box:+ * `fullscreenChangeStart` as it enters or leaves fullscreen, then `enterFullscreen` or+ * `leaveFullscreen` once it has the new size.+ */+export type ContentEmbedEvent = "fullscreenChangeStart" | "enterFullscreen" | "leaveFullscreen";+const providers = new Map<HTMLElement, ContentEmbedToolProvider>();const watchers = new Set<{ container: HTMLElement; callback: () => void }>();@@ -85,6 +92,13 @@ export function getContentEmbedTools(embed: HTMLElement) {return null;}+/** Shows the content box of the embed that contains `element` in fullscreen. */+export function showContentEmbedFullscreen(element: Element | null) {+ element?.closest(".include-note-content")?.requestFullscreen().catch((error: unknown) => {+ console.warn("Could not show the embed in fullscreen:", error);+ });+}+/*** Whether the Editable toggle of the embed that contains `ref` is on, for content whose provider* sets `hasEditableFlag`. Content outside an embed has no toggle, and is editable. `false` until@@ -109,3 +123,27 @@ export function useIsContentEmbedEditable(ref: RefObject<HTMLElement>) {return isEditable;}++/**+ * Calls `callback` when the embed that contains `ref` dispatches `name`. Listens on the document,+ * as content can mount before its embed box takes it in.+ */+export function useContentEmbedEvent(+ ref: RefObject<HTMLElement>,+ name: ContentEmbedEvent,+ callback: () => void+) {+ const callbackRef = useRef(callback);+ callbackRef.current = callback;++ useEffect(() => {+ const listener = (event: Event) => {+ const element = ref.current;+ if (element && event.target instanceof Node && event.target.contains(element)) {+ callbackRef.current();+ }+ };+ document.addEventListener(name, listener);+ return () => document.removeEventListener(name, listener);+ }, [ ref, name ]);+}diff --git a/packages/ckeditor5/src/plugins/content_embed/content_embed_tools.spec.ts b/packages/ckeditor5/src/plugins/content_embed/content_embed_tools.spec.tsindex cf49788a39..8c8918f5ed 100644--- a/packages/ckeditor5/src/plugins/content_embed/content_embed_tools.spec.ts+++ b/packages/ckeditor5/src/plugins/content_embed/content_embed_tools.spec.ts@@ -265,6 +265,26 @@ describe("ContentEmbedTools", () => {expect(getShown()).toEqual([ true, true, true, true ]);});+ it("reads the tools again when the editor updates, as they can follow the embed", () => {+ const tools = createView();+ const embedProvider = {+ tools: [ SELECTION ],+ getTools() {+ return this.tools;+ },+ execute: vi.fn(),+ subscribe: () => () => {}+ };+ getContentEmbedTools.mockReturnValue(embedProvider);+ selectEmbed();+ expect(getItems(tools)).toEqual([ "1" ]);++ embedProvider.tools = [ SELECTION, RECTANGLE ];+ expect(getItems(tools)).toEqual([ "1" ]);+ editor.ui.update();+ expect(getItems(tools)).toEqual([ "1", "2" ]);+ });+it("focuses its first button, and stops following the provider once destroyed", () => {const tools = createView();selectEmbed();diff --git a/packages/ckeditor5/src/plugins/content_embed/content_embed_tools.ts b/packages/ckeditor5/src/plugins/content_embed/content_embed_tools.tsindex 326b98fc68..c8c7672566 100644--- a/packages/ckeditor5/src/plugins/content_embed/content_embed_tools.ts+++ b/packages/ckeditor5/src/plugins/content_embed/content_embed_tools.ts@@ -31,11 +31,12 @@ export default class ContentEmbedTools extends Plugin {editor.ui.componentFactory.add(CONTENT_EMBED_TOOLS, locale => {const view = new ContentEmbedToolsView(locale);- view.setProvider(contentEmbed.selectedEmbedTools);- this.listenTo(contentEmbed, "change:selectedEmbedTools", () => {+ // The tools can follow the embed, which the editor updates. Runs before+ // `WidgetToolbarRepository` positions the toolbar from its width.+ this.listenTo(editor.ui, "update", () => {view.setProvider(contentEmbed.selectedEmbedTools);- });+ }, { priority: "high" });this.listenTo<ContentEmbedToolsResizeEvent>(view, "resize", () => editor.ui.update());return view;@@ -91,17 +92,15 @@ export class ContentEmbedToolsView extends View {/** Shows the buttons of `provider`, and updates them when it changes. */setProvider(provider: ContentEmbedToolProvider | null) {- if (provider === this.provider) {- return;+ if (provider !== this.provider) {+ this.unsubscribe?.();+ this.provider = provider;+ this.unsubscribe = provider?.subscribe(() => {+ if (this.showTools()) {+ this.fire<ContentEmbedToolsResizeEvent>("resize");+ }+ });}-- this.unsubscribe?.();- this.provider = provider;- this.unsubscribe = provider?.subscribe(() => {- if (this.showTools()) {- this.fire<ContentEmbedToolsResizeEvent>("resize");- }- });this.showTools();}