Skip to content

Build your personal knowledge base with Trilium Notes

client/text editor/canvas: add support for resizable embed content widget

Adorian Doran7b7ee42196ec
diff --git a/apps/client/src/stylesheets/style.css b/apps/client/src/stylesheets/style.css
index a8cc3f41d3..9944c5d099 100644
--- a/apps/client/src/stylesheets/style.css
+++ b/apps/client/src/stylesheets/style.css
@@ -1489,7 +1489,7 @@ body.mobile .modal-content-with-sidebar > .modal-main > .modal-header > .modal-t
/* Using data- attribute to support both CKEditor and readonly view */
.include-note[data-box-size="small"] .include-note-content {
- max-height: 10em;
+ max-height: var(--include-note-height, 10em);
overflow: auto;
}
@@ -1497,7 +1497,7 @@ body.mobile .modal-content-with-sidebar > .modal-main > .modal-header > .modal-t
height per box size instead of an intrinsic, content-driven one. */
.include-note[data-box-size="small"] .include-note-content.type-pdf,
.include-note[data-box-size="small"] .include-note-content.type-webView {
- height: 10em;
+ height: var(--include-note-height, 10em);
}
/* The small box has room for the compact audio player's visualizer band (which carries a floor of its own) or
@@ -1512,13 +1512,13 @@ body.mobile .modal-content-with-sidebar > .modal-main > .modal-header > .modal-t
}
.include-note[data-box-size="medium"] .include-note-content {
- max-height: 20em;
+ max-height: var(--include-note-height, 20em);
overflow: auto;
}
.include-note[data-box-size="medium"] .include-note-content.type-pdf .rendered-content,
.include-note[data-box-size="medium"] .include-note-content.type-webView .rendered-content {
- height: 20em;
+ height: var(--include-note-height, 20em);
}
.include-note[data-box-size="full"] .include-note-content.type-pdf .rendered-content,
@@ -1527,7 +1527,7 @@ body.mobile .modal-content-with-sidebar > .modal-main > .modal-header > .modal-t
}
.include-note[data-box-size="expandable"] .include-note-content.type-webView .rendered-content {
- height: 20em;
+ height: var(--include-note-height, 20em);
}
/* Full-height collection views (table, board, calendar, geo map, presentation) render their own
@@ -1536,12 +1536,12 @@ body.mobile .modal-content-with-sidebar > .modal-main > .modal-header > .modal-t
collections are content-driven and keep the generic max-height above. */
.include-note[data-box-size="small"] .include-note-content.type-book:has(.note-list-widget.full-height),
.include-note[data-box-size="small"] .include-note-content.type-search:has(.note-list-widget.full-height) {
- height: 10em;
+ height: var(--include-note-height, 10em);
}
.include-note[data-box-size="medium"] .include-note-content.type-book:has(.note-list-widget.full-height),
.include-note[data-box-size="medium"] .include-note-content.type-search:has(.note-list-widget.full-height) {
- height: 20em;
+ height: var(--include-note-height, 20em);
}
.include-note[data-box-size="full"] .include-note-content.type-book:has(.note-list-widget.full-height),
@@ -1551,25 +1551,47 @@ body.mobile .modal-content-with-sidebar > .modal-main > .modal-header > .modal-t
.include-note[data-box-size="expandable"] .include-note-content.type-book:has(.note-list-widget.full-height),
.include-note[data-box-size="expandable"] .include-note-content.type-search:has(.note-list-widget.full-height) {
- height: 20em;
+ height: var(--include-note-height, 20em);
}
/* Pictures, diagrams and players fit the box height, where text scrolls in it. */
.include-note[data-box-size="small"] {
- --include-note-media-max-height: 10em;
+ --include-note-media-max-height: var(--include-note-height, 10em);
}
.include-note[data-box-size="medium"] {
- --include-note-media-max-height: 20em;
+ --include-note-media-max-height: var(--include-note-height, 20em);
}
+.include-note[data-box-size="expandable"] {
+ --include-note-media-max-height: var(--include-note-height);
+}
+
+/* Media takes a resized height inside the border and padding, as with the edge-to-edge types. */
.include-note[data-box-size] .include-note-content:is(
.type-image, .type-canvas, .type-canvasDrawing, .type-mindMap, .type-spreadsheet, .type-mermaid,
.type-video
) {
+ box-sizing: content-box;
max-height: none;
}
+/* Tiny and Full fit their content: only these box sizes take a resized size. */
+.include-note:is([data-box-size="small"], [data-box-size="medium"], [data-box-size="expandable"]) {
+ max-width: 100%;
+ width: var(--include-note-width, auto);
+
+ .include-note-content {
+ height: var(--include-note-height, auto);
+ overflow: auto;
+ }
+
+ &:has(.include-note-content[hidden]) > .ck-widget__resize-handles
+ > :not(.ck-widget__resize-handle_width) {
+ display: none;
+ }
+}
+
.include-note-content:not(:fullscreen) :is(
.rendered-content > img, .rendered-content > svg, .image-viewer-content > img,
.video-preview-wrapper:not(:fullscreen) > .video-preview
@@ -1767,6 +1789,7 @@ body.mobile .modal-content-with-sidebar > .modal-main > .modal-header > .modal-t
.include-note-content.type-webView,
.include-note-content.type-book:has(.note-list-widget.full-height),
.include-note-content.type-search:has(.note-list-widget.full-height) {
+ box-sizing: content-box;
padding: 0;
}
diff --git a/apps/client/src/widgets/type_widgets/canvas/CanvasDrawing.css b/apps/client/src/widgets/type_widgets/canvas/CanvasDrawing.css
index 15cffc4cf3..6acbd853c9 100644
--- a/apps/client/src/widgets/type_widgets/canvas/CanvasDrawing.css
+++ b/apps/client/src/widgets/type_widgets/canvas/CanvasDrawing.css
@@ -14,7 +14,7 @@
}
.canvas-drawing {
- height: 20em;
+ height: var(--include-note-height, 20em);
background-color: var(--canvas-drawing-background-color);
/* Resets the typography inherited from the text note. */
@@ -110,7 +110,7 @@
.include-note {
&[data-box-size="small"] .canvas-drawing {
- height: 10em;
+ height: var(--include-note-height, 10em);
}
&[data-box-size="full"] .canvas-drawing {
diff --git a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Basic Concepts and Features/Notes/Attachments.html b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Basic Concepts and Features/Notes/Attachments.html
index df9585d507..da8e6ae7f3 100644
--- a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Basic Concepts and Features/Notes/Attachments.html
+++ b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Basic Concepts and Features/Notes/Attachments.html
@@ -81,7 +81,9 @@
<li>An embed gets the box size that suits the attachment, as a new included
note does (see <em>Box sizes</em> there). To change its size, select the
embed and use the box size menu in its toolbar, or the <em>Size</em> submenu
- of its <span class="tn-icon bx bx-dots-vertical-rounded"></span> <em>More actions</em> menu.</li>
+ of its <span class="tn-icon bx bx-dots-vertical-rounded"></span> <em>More actions</em> menu.
+ A <em>Small</em>, <em>Medium</em> or <em>Expandable</em> embed can also be resized
+ by dragging its handles (see <em>Resizing</em> there).</li>
<li>An embed can have a caption, as an included note can (see <em>Caption</em> there).</li>
<li>To show only the attachment, select the embed and press the <span class="tn-icon bx bx-window-alt"></span> <em>Show title</em> button
in its toolbar, as for an included note (see <em>Title</em> there).</li>
diff --git a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Text/Include Note.html b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Text/Include Note.html
index 61339864c9..3e7e2e5baa 100644
--- a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Text/Include Note.html
+++ b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Text/Include Note.html
@@ -40,6 +40,29 @@
and you can choose another one there. To change the size later, select
the include and use the <em>Box size</em> menu in its toolbar, or the <em>Size</em> submenu
of its <em>More actions</em> menu.</p>
+<h2>Resizing</h2>
+<p>A <em>Small</em>, <em>Medium</em> or <em>Expandable</em> include can be resized
+ to any width and height. A <em>Tiny</em> or <em>Full</em> include always fits
+ its content.</p>
+<ul>
+ <li>To resize an include, select it and drag one of its handles: the handle
+ on its right edge changes the width, the handle on its bottom edge changes
+ the height, and the handle in its bottom-right corner changes both. In
+ right-to-left text, the width handle is on the left edge. With a mouse,
+ the handles also show while the pointer is over the include.</li>
+ <li>The handles work with a mouse, a pen or a finger. On a touch screen, tap
+ the include first to show them.</li>
+ <li>While the height changes, moving the handle near the top or the bottom
+ of the note scrolls the note.</li>
+ <li>Making an include as wide as the note returns it to the full width.</li>
+ <li>To cancel a resize, press <kbd>Esc</kbd> before releasing the handle.</li>
+ <li>To reset the size, double-click a handle, or double-tap it on a touch
+ screen. The corner handle resets both the width and the height.</li>
+ <li>Choosing a box size resets the height. Choosing <em>Tiny</em> or <em>Full</em> resets
+ the width too.</li>
+ <li>While an <em>Expandable</em> include is collapsed, only its width can be
+ changed.</li>
+</ul>
<h2>Caption</h2>
<p>An include can have a caption, shown centered at the bottom of its box.
The caption is part of the text note, so it can be formatted like the rest
@@ -153,8 +176,8 @@
the text.</li>
<li>A new drawing has the background color of the note. A background chosen
from the Excalidraw menu replaces it.</li>
- <li>The box sizes, the caption and the title work as for an included note.
- In a short box, Excalidraw uses a more compact layout for its toolbars.
+ <li>The box sizes, resizing, the caption and the title work as for an included
+ note. In a short box, Excalidraw uses a more compact layout for its toolbars.
For more room, choose <em>Full</em>, or show the title and press <span class="tn-icon bx bx-fullscreen"></span> <em>Fullscreen</em>.</li>
<li>Pictures added to the drawing are stored in the same attachment.</li>
<li>In a <a href="#root/_help_CoFPLs3dRlXc">read-only note</a>, the drawing
diff --git a/docs/User Guide/User Guide/Basic Concepts and Features/Notes/Attachments.md b/docs/User Guide/User Guide/Basic Concepts and Features/Notes/Attachments.md
index bd944d558a..e6df92ca43 100644
--- a/docs/User Guide/User Guide/Basic Concepts and Features/Notes/Attachments.md
+++ b/docs/User Guide/User Guide/Basic Concepts and Features/Notes/Attachments.md
@@ -42,7 +42,7 @@ An attachment can be shown in the text instead of linked, the way <a class="ref
* To attach files and embed them straight away, select _Attach and embed file_ from the arrow beside the <span class="tn-icon cke cke-paper-clip"></span> _Attach file_ button. Each file gets an embed of its own, which shows the file name while the file uploads.
* To embed an attachment that is already linked, right-click a link to it in a text note being edited and select _Convert link to an embed_, at the end of the menu.
* A drawing canvas, inserted with the <span class="tn-icon bx bx-pen"></span> _Insert drawing canvas_ button, is an embed of a `Canvas.excalidraw` attachment that can be drawn on in place (see _Drawing canvases_ in <a class="reference-link" href="../../Note%20Types/Text/Include%20Note.md">Include Note</a>).
-* An embed gets the box size that suits the attachment, as a new included note does (see _Box sizes_ there). To change its size, select the embed and use the box size menu in its toolbar, or the _Size_ submenu of its <span class="tn-icon bx bx-dots-vertical-rounded"></span> _More actions_ menu.
+* An embed gets the box size that suits the attachment, as a new included note does (see _Box sizes_ there). To change its size, select the embed and use the box size menu in its toolbar, or the _Size_ submenu of its <span class="tn-icon bx bx-dots-vertical-rounded"></span> _More actions_ menu. A _Small_, _Medium_ or _Expandable_ embed can also be resized by dragging its handles (see _Resizing_ there).
* An embed can have a caption, as an included note can (see _Caption_ there).
* To show only the attachment, select the embed and press the <span class="tn-icon bx bx-window-alt"></span> _Show title_ button in its toolbar, as for an included note (see _Title_ there).
* To open the attachment in a new tab, press the <span class="tn-icon bx bx-link-external"></span> _Open in new tab_ button at the end of the embed's title.
diff --git a/docs/User Guide/User Guide/Note Types/Text/Include Note.md b/docs/User Guide/User Guide/Note Types/Text/Include Note.md
index b7cebb442f..2833938fa8 100644
--- a/docs/User Guide/User Guide/Note Types/Text/Include Note.md
+++ b/docs/User Guide/User Guide/Note Types/Text/Include Note.md
@@ -29,6 +29,19 @@ A new include gets the size that suits what it shows:
The dialog that includes a note selects that size once the note is picked, and you can choose another one there. To change the size later, select the include and use the _Box size_ menu in its toolbar, or the _Size_ submenu of its _More actions_ menu.
+## Resizing
+
+A _Small_, _Medium_ or _Expandable_ include can be resized to any width and height. A _Tiny_ or _Full_ include always fits its content.
+
+* To resize an include, select it and drag one of its handles: the handle on its right edge changes the width, the handle on its bottom edge changes the height, and the handle in its bottom-right corner changes both. In right-to-left text, the width handle is on the left edge. With a mouse, the handles also show while the pointer is over the include.
+* The handles work with a mouse, a pen or a finger. On a touch screen, tap the include first to show them.
+* While the height changes, moving the handle near the top or the bottom of the note scrolls the note.
+* Making an include as wide as the note returns it to the full width.
+* To cancel a resize, press <kbd>Esc</kbd> before releasing the handle.
+* To reset the size, double-click a handle, or double-tap it on a touch screen. The corner handle resets both the width and the height.
+* Choosing a box size resets the height. Choosing _Tiny_ or _Full_ resets the width too.
+* While an _Expandable_ include is collapsed, only its width can be changed.
+
## Caption
An include can have a caption, shown centered at the bottom of its box. The caption is part of the text note, so it can be formatted like the rest of the text, for example in bold or with a link.
@@ -96,7 +109,7 @@ A drawing canvas is an Excalidraw canvas, like the one of a <a class="reference-
* To insert a drawing canvas, press the <span class="tn-icon bx bx-pen"></span> _Insert drawing canvas_ button in the <a class="reference-link" href="Formatting%20toolbar.md">Formatting toolbar</a>, next to the <span class="tn-icon cke cke-paper-clip"></span> _Attach file_ button. The canvas is added empty, in a _Medium_ box with its title hidden, and takes the focus, ready for drawing.
* To draw on a canvas that does not have the focus, click it first. Until then, the mouse wheel and touch gestures scroll the note. The canvas then has the tools, menus and keyboard shortcuts of a Canvas note. The toolbars, the menus and the properties of the selected shapes show only while the canvas has the focus, so elsewhere the drawing reads like a picture in the text.
* A new drawing has the background color of the note. A background chosen from the Excalidraw menu replaces it.
-* The box sizes, the caption and the title work as for an included note. In a short box, Excalidraw uses a more compact layout for its toolbars. For more room, choose _Full_, or show the title and press <span class="tn-icon bx bx-fullscreen"></span> _Fullscreen_.
+* The box sizes, resizing, the caption and the title work as for an included note. In a short box, Excalidraw uses a more compact layout for its toolbars. For more room, choose _Full_, or show the title and press <span class="tn-icon bx bx-fullscreen"></span> _Fullscreen_.
* Pictures added to the drawing are stored in the same attachment.
* In a [read-only note](../../Basic%20Concepts%20and%20Features/Notes/Read-Only%20Notes.md), the drawing can be viewed but not changed.
diff --git a/packages/ckeditor5/src/plugins/content_embed/content_embed.spec.ts b/packages/ckeditor5/src/plugins/content_embed/content_embed.spec.ts
index fa6b15b2c1..8b324e7dd1 100644
--- a/packages/ckeditor5/src/plugins/content_embed/content_embed.spec.ts
+++ b/packages/ckeditor5/src/plugins/content_embed/content_embed.spec.ts
@@ -1284,6 +1284,73 @@ describe("ContentEmbed title", () => {
});
});
+describe("ContentEmbed resizing", () => {
+ const RESIZED = "<figure class=\"include-note\""
+ + " style=\"--include-note-height:12.5em;--include-note-width:30em;\""
+ + " data-note-id=\"n1\" data-box-size=\"medium\">&nbsp;</figure>";
+ let editor: ClassicEditor;
+
+ beforeEach(async () => {
+ installGlobMock({ getComponentByEl: () => ({ loadEmbeddedNote: vi.fn() }) });
+ editor = await createTestEditor([ Essentials, Paragraph, Undo, Widget, ContentEmbed ]);
+ });
+
+ function getRenderedEmbed() {
+ const embed = editor.editing.view.getDomRoot()?.querySelector("figure.include-note");
+ if (!embed) {
+ throw new Error("Expected a rendered embed.");
+ }
+ return embed;
+ }
+
+ it("loads and saves the size of a resized embed", () => {
+ editor.setData(RESIZED);
+
+ expect(getModelData(editor.model, { withoutSelection: true })).toBe(
+ "<contentEmbed boxSize=\"medium\" customHeight=\"12.5em\" customWidth=\"30em\""
+ + " noteId=\"n1\"></contentEmbed>"
+ );
+ expect(editor.getData()).toBe(RESIZED);
+ });
+
+ it("offers resizing to a Small, Medium or Expandable embed, but not to a Tiny or Full one", () => {
+ insertContentEmbed(editor, "n1", "medium");
+ const embed = getRenderedEmbed();
+ const handles = embed.querySelector(":scope > .ck-widget__resize-handles");
+ expect([ ...handles?.children ?? [] ].map((handle) => handle.className)).toEqual([
+ "ck-widget__resize-handle ck-widget__resize-handle_width",
+ "ck-widget__resize-handle ck-widget__resize-handle_height",
+ "ck-widget__resize-handle ck-widget__resize-handle_corner"
+ ]);
+
+ for (const [ boxSize, isResizable ] of [
+ [ "tiny", false ], [ "small", true ], [ "full", false ], [ "expandable", true ],
+ [ "medium", true ]
+ ] as const) {
+ editor.execute(BOX_SIZE_COMMAND_NAME, { value: boxSize });
+ expect(embed.classList.contains("ck-widget_resizable"), boxSize).toBe(isResizable);
+ }
+ });
+
+ it("resets the height on a new box size, and the width too on Tiny or Full", () => {
+ editor.setData(RESIZED);
+ const embed = findContentEmbed(editor);
+ if (!embed) {
+ throw new Error("Expected an embed.");
+ }
+ editor.model.change((writer) => writer.setSelection(embed, "on"));
+
+ editor.execute(BOX_SIZE_COMMAND_NAME, { value: "small" });
+ expect(editor.getData()).toContain("style=\"--include-note-width:30em;\"");
+
+ for (const value of [ "tiny", "full" ] as const) {
+ editor.execute("undo");
+ editor.execute(BOX_SIZE_COMMAND_NAME, { value });
+ expect(editor.getData(), value).not.toContain("style=");
+ }
+ });
+});
+
function findContentEmbed(editor: ClassicEditor): ModelElement | undefined {
const root = editor.model.document.getRoot();
if (!root) {
diff --git a/packages/ckeditor5/src/plugins/content_embed/content_embed.ts b/packages/ckeditor5/src/plugins/content_embed/content_embed.ts
index b7b418a15d..847e863bac 100644
--- a/packages/ckeditor5/src/plugins/content_embed/content_embed.ts
+++ b/packages/ckeditor5/src/plugins/content_embed/content_embed.ts
@@ -24,6 +24,7 @@ import {
import windowIcon from 'boxicons/svg/regular/bx-window-alt.svg?raw';
import noteIcon from '../../icons/note.svg?raw';
import { getAttachmentId, getNoteId } from '../referencelink.js';
+import ResizableWidgets, { SIZE_ATTRIBUTES } from '../resizable_widgets/resizable_widgets.js';
export const COMMAND_NAME = 'insertContentEmbed';
export const BOX_SIZE_COMMAND_NAME = 'contentEmbedBoxSize';
@@ -38,6 +39,9 @@ export const BOX_SIZES = [ 'tiny', 'small', 'medium', 'full', 'expandable' ] as
export type BoxSizeValue = typeof BOX_SIZES[number];
+/** The box sizes that can be resized. Tiny and Full fit their content. */
+const RESIZABLE_BOX_SIZES: unknown[] = [ 'small', 'medium', 'expandable' ];
+
/** What the toolbar of an embed shows of it, for a menu offering the same commands. */
export interface ContentEmbedState {
boxSize: BoxSizeValue | null;
@@ -273,7 +277,7 @@ class ContentEmbedUI extends Plugin {
class ContentEmbedEditing extends Plugin {
static get requires() {
- return [ Widget ];
+ return [ Widget, ResizableWidgets ];
}
static get pluginName() {
@@ -291,6 +295,16 @@ class ContentEmbedEditing extends Plugin {
this._defineConverters();
const editor = this.editor;
+ editor.plugins.get( ResizableWidgets ).register( 'contentEmbed', {
+ propertyPrefix: '--include-note',
+ isWidthResizable: true,
+ isHeightResizable: true,
+ heightTarget: '.include-note-content',
+ minWidth: 10,
+ minHeight: 3,
+ isResizable: embed => RESIZABLE_BOX_SIZES.includes( embed.getAttribute( 'boxSize' ) )
+ } );
+
const commands = editor.commands;
commands.add( COMMAND_NAME, new InsertContentEmbedCommand( editor ) );
commands.add( BOX_SIZE_COMMAND_NAME, new ContentEmbedBoxSizeCommand( editor ) );
@@ -585,8 +599,8 @@ class ContentEmbedBoxSizeCommand extends Command {
declare value: BoxSizeValue | null;
/**
- * Sets the box size of the selected embed. Tiny takes the caption away, and a larger size
- * shows it again.
+ * Sets the box size of the selected embed and resets its height. Tiny and Full reset the
+ * width too. Tiny takes the caption away, and a larger size shows it again.
*/
override execute( options: { value: BoxSizeValue } ) {
const editor = this.editor;
@@ -596,6 +610,10 @@ class ContentEmbedBoxSizeCommand extends Command {
editor.model.change( writer => {
const wasTiny = embedElement.getAttribute( 'boxSize' ) === 'tiny';
writer.setAttribute( 'boxSize', options.value, embedElement );
+ writer.removeAttribute( SIZE_ATTRIBUTES.height, embedElement );
+ if ( !RESIZABLE_BOX_SIZES.includes( options.value ) ) {
+ writer.removeAttribute( SIZE_ATTRIBUTES.width, embedElement );
+ }
if ( options.value === 'tiny' ) {
writer.setSelection( embedElement, 'on' );
diff --git a/packages/ckeditor5/src/plugins/resizable_widgets/resizable_widgets.spec.ts b/packages/ckeditor5/src/plugins/resizable_widgets/resizable_widgets.spec.ts
new file mode 100644
index 0000000000..188dcc5dc3
--- /dev/null
+++ b/packages/ckeditor5/src/plugins/resizable_widgets/resizable_widgets.spec.ts
@@ -0,0 +1,393 @@
+import {
+ _getModelData as getModelData,
+ type ClassicEditor,
+ Essentials,
+ Paragraph,
+ Plugin,
+ Undo,
+ WidgetToolbarRepository
+} from "ckeditor5";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+import { createTestEditor } from "../../../test/editor-kit.js";
+import { TestBoxPlugin } from "../../../test/fixture-plugins.js";
+import { registerTestCleanup } from "../../../test/globals-test-kit.js";
+import ResizableWidgets, { type ResizableWidgetConfig } from "./resizable_widgets.js";
+
+const STYLES = `
+ .ck.ck-editor__editable { width: 400px; padding: 0; font-size: 10px; }
+ .test-box { width: var(--test-width, auto); }
+ .test-box-content { height: var(--test-height, 50px); }
+ .test-rtl .test-box { direction: rtl; }
+ .test-scroller .ck.ck-editor__main { height: 150px; overflow-y: auto; }
+ .test-scroller .ck.ck-editor__editable { height: 1000px; }
+`;
+
+const RESIZED = "<div class=\"test-box\" style=\"--test-height:8em;--test-width:30em;\">"
+ + "&nbsp;</div>";
+
+describe("ResizableWidgets", () => {
+ let editor: ClassicEditor;
+ let capture: ReturnType<typeof vi.spyOn>;
+
+ beforeEach(() => {
+ const style = document.createElement("style");
+ style.textContent = STYLES;
+ document.head.append(style);
+ capture = vi.spyOn(Element.prototype, "setPointerCapture").mockImplementation(() => {});
+ registerTestCleanup(() => {
+ style.remove();
+ capture.mockRestore();
+ document.body.classList.remove("test-rtl", "test-scroller");
+ });
+ });
+
+ async function createEditor(
+ config: Partial<ResizableWidgetConfig> = {},
+ extraPlugins: Array<typeof Plugin> = []
+ ) {
+ class ResizableTestBox extends Plugin {
+ static get requires() {
+ return [ TestBoxPlugin, ResizableWidgets ];
+ }
+
+ init() {
+ const { conversion, model, plugins } = this.editor;
+ model.schema.extend("testBox", { allowAttributes: "kind" });
+ conversion.for("editingDowncast").add((dispatcher) => {
+ dispatcher.on("insert:testBox", (_evt, data, { mapper, writer }) => {
+ const box = mapper.toViewElement(data.item);
+ if (box) {
+ const content = writer.createUIElement("div", {
+ class: "test-box-content"
+ });
+ writer.insert(writer.createPositionAt(box, 0), content);
+ }
+ });
+ });
+ plugins.get(ResizableWidgets).register("testBox", {
+ propertyPrefix: "--test",
+ isWidthResizable: true,
+ isHeightResizable: true,
+ heightTarget: ".test-box-content",
+ ...config
+ });
+ }
+ }
+
+ editor = await createTestEditor([
+ Essentials, Paragraph, Undo, ResizableTestBox, ...extraPlugins
+ ]);
+ return editor;
+ }
+
+ function getBox() {
+ const box = editor.editing.view.getDomRoot()?.querySelector<HTMLElement>(".test-box");
+ if (!box) {
+ throw new Error("Expected a rendered box.");
+ }
+ return box;
+ }
+
+ function getHandle(name: string) {
+ const handle = getBox().querySelector(`.ck-widget__resize-handle_${name}`);
+ if (!handle) {
+ throw new Error(`Expected the ${name} handle.`);
+ }
+ return handle;
+ }
+
+ function getSize() {
+ return getModelData(editor.model, { withoutSelection: true });
+ }
+
+ it("loads and saves a size in em, and ignores one in other units", async () => {
+ await createEditor();
+ editor.setData(RESIZED);
+ expect(getSize()).toBe("<testBox customHeight=\"8em\" customWidth=\"30em\"></testBox>");
+ expect(editor.getData()).toBe(RESIZED);
+
+ editor.setData("<div class=\"test-box\" style=\"--test-width:300px;\"></div>");
+ expect(getSize()).toBe("<testBox></testBox>");
+ });
+
+ it("draws a handle for each axis, and a corner for both", async () => {
+ const getHandles = () => [ ...getBox().querySelectorAll(".ck-widget__resize-handle") ]
+ .map((handle) => handle.className.replace("ck-widget__resize-handle ", ""));
+
+ for (const [ config, handles ] of [
+ [ { isHeightResizable: false }, [ "ck-widget__resize-handle_width" ] ],
+ [ { isWidthResizable: false }, [ "ck-widget__resize-handle_height" ] ],
+ [ {}, [
+ "ck-widget__resize-handle_width",
+ "ck-widget__resize-handle_height",
+ "ck-widget__resize-handle_corner"
+ ] ]
+ ] as const) {
+ await createEditor(config);
+ editor.setData("<div class=\"test-box\"></div>");
+ expect(getHandles()).toEqual(handles);
+ }
+ expect(getBox().classList.contains("ck-widget_resizable")).toBe(true);
+ });
+
+ it("marks a widget resizable while isResizable allows it", async () => {
+ await createEditor({ isResizable: (element) => element.getAttribute("kind") !== "fixed" });
+ editor.setData("<div class=\"test-box\"></div><p>text</p>");
+ const root = editor.model.document.getRoot();
+ const box = root?.getChild(0);
+ if (!box?.is("element")) {
+ throw new Error("Expected a box.");
+ }
+ expect(getBox().classList.contains("ck-widget_resizable")).toBe(true);
+
+ editor.model.change((writer) => writer.setAttribute("kind", "fixed", box));
+ expect(getBox().classList.contains("ck-widget_resizable")).toBe(false);
+
+ const paragraph = root?.getChild(1);
+ if (!paragraph?.is("element")) {
+ throw new Error("Expected a paragraph.");
+ }
+ editor.model.change((writer) => writer.setAttribute("kind", "fixed", paragraph));
+ editor.model.change((writer) => writer.removeAttribute("kind", box));
+ expect(getBox().classList.contains("ck-widget_resizable")).toBe(true);
+ });
+
+ it("resizes from the corner, previewing in the view and saving in one undo step", async () => {
+ await createEditor();
+ editor.setData("<p>text</p><div class=\"test-box\"></div>");
+ const box = getBox();
+
+ press(getHandle("corner"));
+ expect(capture).toHaveBeenCalledWith(1);
+ expect(editor.model.document.selection.getSelectedElement()?.name).toBe("testBox");
+
+ move(101, 301);
+ expect(box.classList.contains("ck-widget_resizing")).toBe(false);
+ move(0, 330);
+ await nextFrame();
+ expect(box.classList.contains("ck-widget_resizing")).toBe(true);
+ expect([ box.style.getPropertyValue("--test-width"), box.offsetWidth ])
+ .toEqual([ "30em", 300 ]);
+ expect(box.style.getPropertyValue("--test-height")).toBe("8em");
+ expect(getSize()).toBe("<paragraph>text</paragraph><testBox></testBox>");
+
+ release();
+ expect(box.classList.contains("ck-widget_resizing")).toBe(false);
+ expect(getSize()).toBe("<paragraph>text</paragraph>"
+ + "<testBox customHeight=\"8em\" customWidth=\"30em\"></testBox>");
+
+ editor.execute("undo");
+ expect(getSize()).toBe("<paragraph>text</paragraph><testBox></testBox>");
+ expect(box.getAttribute("style")).toBeNull();
+ });
+
+ it("makes the width full at the container's, and keeps the smallest size", async () => {
+ await createEditor({ minHeight: 3 });
+ editor.setData(RESIZED);
+
+ press(getHandle("width"));
+ move(200, 300);
+ release();
+ press(getHandle("height"));
+ move(100, 100);
+ release();
+
+ expect(getSize()).toBe("<testBox customHeight=\"3em\"></testBox>");
+ expect(getBox().offsetWidth).toBe(400);
+ });
+
+ it("narrows the width towards the right in a right-to-left widget", async () => {
+ document.body.classList.add("test-rtl");
+ await createEditor();
+ editor.setData("<div class=\"test-box\"></div>");
+
+ press(getHandle("width"));
+ move(150, 300);
+ release();
+
+ expect(getSize()).toBe("<testBox customWidth=\"35em\"></testBox>");
+ });
+
+ it("cancels on Escape or a pointercancel, and ignores other pointers", async () => {
+ await createEditor();
+ editor.setData(RESIZED);
+ const box = getBox();
+
+ press(getHandle("width"));
+ move(150, 300);
+ move(300, 300, 2);
+ window.dispatchEvent(new PointerEvent("pointerup", { pointerId: 2 }));
+ expect(box.style.getPropertyValue("--test-width")).toBe("35em");
+ const other = new KeyboardEvent("keydown", { key: "a", cancelable: true });
+ window.dispatchEvent(other);
+ const escape = new KeyboardEvent("keydown", { key: "Escape", cancelable: true });
+ window.dispatchEvent(escape);
+ expect([ other.defaultPrevented, escape.defaultPrevented ]).toEqual([ false, true ]);
+ expect(box.style.getPropertyValue("--test-width")).toBe("30em");
+ expect(box.classList.contains("ck-widget_resizing")).toBe(false);
+
+ press(getHandle("width"));
+ move(150, 300);
+ window.dispatchEvent(new PointerEvent("pointercancel", { pointerId: 2 }));
+ expect(box.style.getPropertyValue("--test-width")).toBe("35em");
+ window.dispatchEvent(new PointerEvent("pointercancel", { pointerId: 1 }));
+ release();
+ expect(box.style.getPropertyValue("--test-width")).toBe("30em");
+ expect(editor.getData()).toBe(RESIZED);
+ });
+
+ it("resets the size of a handle on a double tap", async () => {
+ await createEditor();
+ editor.setData(RESIZED);
+
+ tap(getHandle("width"));
+ tap(getHandle("height"));
+ tap(getHandle("width"));
+ expect(editor.getData()).toBe(RESIZED);
+
+ tap(getHandle("width"));
+ expect(getSize()).toBe("<testBox customHeight=\"8em\"></testBox>");
+ tap(getHandle("height"));
+ tap(getHandle("height"));
+ expect(getSize()).toBe("<testBox></testBox>");
+
+ editor.setData(RESIZED);
+ tap(getHandle("corner"));
+ tap(getHandle("corner"));
+ expect(getSize()).toBe("<testBox></testBox>");
+ });
+
+ it("resizes the height of the widget itself without a height target", async () => {
+ await createEditor({ heightTarget: undefined });
+ editor.setData("<div class=\"test-box\"></div>");
+ const height = parseFloat(getComputedStyle(getBox()).height) + 30;
+
+ press(getHandle("height"));
+ move(100, 330);
+ release();
+
+ expect(getSize()).toBe(`<testBox customHeight="${Math.round(height) / 10}em"></testBox>`);
+ });
+
+ it("ignores a press it cannot resize from", async () => {
+ await createEditor();
+ editor.setData(RESIZED);
+ const box = getBox();
+ const isResizing = () => box.classList.contains("ck-widget_resizing");
+
+ for (const init of [ { button: 2 }, { isPrimary: false } ]) {
+ press(getHandle("corner"), init);
+ move(200, 400);
+ expect(isResizing()).toBe(false);
+ }
+
+ editor.enableReadOnlyMode("test");
+ press(getHandle("corner"));
+ move(200, 400);
+ expect(isResizing()).toBe(false);
+ editor.disableReadOnlyMode("test");
+
+ const content = box.querySelector(".test-box-content");
+ content?.setAttribute("class", "loading");
+ press(getHandle("height"));
+ move(200, 400);
+ expect(isResizing()).toBe(false);
+ content?.setAttribute("class", "test-box-content");
+ content?.setAttribute("hidden", "");
+ press(getHandle("height"));
+ move(200, 400);
+ expect(isResizing()).toBe(false);
+ press(getHandle("corner"));
+ move(150, 400);
+ release();
+ expect(getSize()).toBe("<testBox customHeight=\"8em\" customWidth=\"35em\"></testBox>");
+
+ const handle = getHandle("corner");
+ handle.parentElement?.remove();
+ press(handle);
+ expect(capture).toHaveBeenCalledTimes(1);
+ });
+
+ it("scrolls its container near the edges while the height changes", async () => {
+ document.body.classList.add("test-scroller");
+ await createEditor();
+ editor.setData("<div class=\"test-box\"></div>");
+ const scroller = getBox().closest(".ck-editor__main");
+ if (!scroller) {
+ throw new Error("Expected the scroll container.");
+ }
+ const { top, bottom } = scroller.getBoundingClientRect();
+ const startY = top + 60;
+
+ press(getHandle("height"), {}, 100, startY);
+ await nextFrame();
+ move(100, bottom - 5);
+ await nextFrame();
+ await nextFrame();
+ const scrolled = scroller.scrollTop;
+ expect(scrolled).toBeGreaterThan(0);
+
+ move(100, top + 30);
+ await nextFrame();
+ expect(scroller.scrollTop).toBeLessThan(scrolled);
+
+ const height = 50 + (top + 30 - startY) + scroller.scrollTop;
+ release();
+ expect(getSize()).toBe(`<testBox customHeight="${Math.round(height) / 10}em"></testBox>`);
+ });
+
+ it("hides the widget toolbar while resizing", async () => {
+ await createEditor({}, [ WidgetToolbarRepository ]);
+ editor.setData("<div class=\"test-box\"></div>");
+ const toolbars = editor.plugins.get(WidgetToolbarRepository);
+
+ press(getHandle("width"));
+ move(150, 300);
+ expect(toolbars.isEnabled).toBe(false);
+ release();
+ expect(toolbars.isEnabled).toBe(true);
+ });
+
+ it("saves nothing for a widget removed while it was resized", async () => {
+ await createEditor();
+ editor.setData("<div class=\"test-box\"></div>");
+
+ press(getHandle("width"));
+ move(150, 300);
+ editor.setData("<p>text</p>");
+ release();
+
+ expect(editor.getData()).toBe("<p>text</p>");
+ });
+});
+
+function press(target: Element, init: PointerEventInit = {}, clientX = 100, clientY = 300) {
+ target.dispatchEvent(new PointerEvent("pointerdown", {
+ bubbles: true,
+ cancelable: true,
+ pointerId: 1,
+ isPrimary: true,
+ clientX,
+ clientY,
+ ...init
+ }));
+}
+
+function move(clientX: number, clientY: number, pointerId = 1) {
+ window.dispatchEvent(new PointerEvent("pointermove", { pointerId, clientX, clientY }));
+}
+
+function release() {
+ window.dispatchEvent(new PointerEvent("pointerup", { pointerId: 1 }));
+}
+
+function tap(target: Element) {
+ press(target);
+ move(101, 300);
+ release();
+}
+
+function nextFrame() {
+ return new Promise((resolve) => requestAnimationFrame(resolve));
+}
diff --git a/packages/ckeditor5/src/plugins/resizable_widgets/resizable_widgets.ts b/packages/ckeditor5/src/plugins/resizable_widgets/resizable_widgets.ts
new file mode 100644
index 0000000000..531cb0fc27
--- /dev/null
+++ b/packages/ckeditor5/src/plugins/resizable_widgets/resizable_widgets.ts
@@ -0,0 +1,337 @@
+import "../../theme/resizable_widgets.css";
+
+import {
+ type DowncastAttributeEvent,
+ type DowncastInsertEvent,
+ type ModelElement,
+ Plugin,
+ type ViewDowncastWriter,
+ type ViewElement,
+ WidgetToolbarRepository
+} from "ckeditor5";
+
+import { type ResizeAxes, type ResizeSize, startResizeGesture } from "./resize_gesture.js";
+
+/** How the widgets of a model element are resized. */
+export interface ResizableWidgetConfig {
+ /**
+ * The prefix of the CSS custom properties that save the size on the widget,
+ * `<prefix>-width` and `<prefix>-height`. The widget's stylesheet applies them.
+ */
+ propertyPrefix: string;
+ isWidthResizable?: boolean;
+ isHeightResizable?: boolean;
+ /** A selector for the element inside the widget whose height changes, or the widget. */
+ heightTarget?: string;
+ /** The smallest width, in `em`. */
+ minWidth?: number;
+ /** The smallest height, in `em`. */
+ minHeight?: number;
+ /** Whether `element` can be resized in its current state. Always by default. */
+ isResizable?: (element: ModelElement) => boolean;
+}
+
+type Axis = keyof ResizeAxes;
+
+/** The model attributes that store the size, in `em`. */
+export const SIZE_ATTRIBUTES: Record<Axis, string> = {
+ width: "customWidth",
+ height: "customHeight"
+};
+
+const HANDLES: Record<string, ResizeAxes> = {
+ width: { width: true, height: false },
+ height: { width: false, height: true },
+ corner: { width: true, height: true }
+};
+
+const RESIZABLE_CLASS = "ck-widget_resizable";
+const RESIZING_CLASS = "ck-widget_resizing";
+const TOOLBAR_LOCK = "ResizableWidgets";
+const DEFAULT_MIN_SIZE = 2;
+const DOUBLE_TAP_MS = 400;
+const EM_PATTERN = /^\d+(\.\d+)?em$/;
+
+/**
+ * Lets the user resize widgets by dragging handles on their inline-end edge, bottom edge and
+ * corner, with a mouse, a pen or a finger. Double-clicking a handle resets its size.
+ */
+export default class ResizableWidgets extends Plugin {
+
+ private lastTap: { handle: Element; time: number } | null = null;
+
+ static get pluginName() {
+ return "ResizableWidgets" as const;
+ }
+
+ /** Makes the widgets of `modelName` resizable. Call it from `init()` of the widget's plugin. */
+ register(modelName: string, config: ResizableWidgetConfig) {
+ const editor = this.editor;
+ const axes = getAxes(config);
+ editor.model.schema.extend(modelName, {
+ allowAttributes: axes.map((axis) => SIZE_ATTRIBUTES[axis])
+ });
+
+ for (const axis of axes) {
+ const property = `${config.propertyPrefix}-${axis}`;
+ editor.conversion.for("upcast").attributeToAttribute({
+ view: { styles: { [property]: EM_PATTERN } },
+ model: {
+ key: SIZE_ATTRIBUTES[axis],
+ value: (viewElement: ViewElement) => viewElement.getStyle(property)
+ }
+ });
+ editor.conversion.for("downcast").attributeToAttribute({
+ model: { name: modelName, key: SIZE_ATTRIBUTES[axis] },
+ view: (value: string) => ({ key: "style", value: { [property]: value } })
+ });
+ }
+
+ editor.conversion.for("editingDowncast").add((dispatcher) => {
+ const insertEvent = `insert:${modelName}` as const;
+ dispatcher.on<DowncastInsertEvent<ModelElement>>(insertEvent, (_evt, { item }, api) => {
+ const viewElement = api.mapper.toViewElement(item);
+ /* v8 ignore next 3 -- the widget's own converter has drawn it */
+ if (!viewElement) {
+ return;
+ }
+
+ const subject = { element: item, viewElement, config };
+ const handles = this.createHandles(api.writer, subject, axes);
+ api.writer.insert(api.writer.createPositionAt(viewElement, "end"), handles);
+ updateResizableClass(api.writer, viewElement, item, config);
+ }, { priority: "low" });
+
+ if (config.isResizable) {
+ dispatcher.on<DowncastAttributeEvent>("attribute", (_evt, { item }, api) => {
+ if (!item.is("element", modelName)) {
+ return;
+ }
+
+ const viewElement = api.mapper.toViewElement(item);
+ /* v8 ignore next 3 -- converted after the widget itself, so always mapped */
+ if (!viewElement) {
+ return;
+ }
+
+ updateResizableClass(api.writer, viewElement, item, config);
+ }, { priority: "low" });
+ }
+ });
+ }
+
+ private createHandles(writer: ViewDowncastWriter, subject: ResizeSubject, axes: Axis[]) {
+ const names = axes.length === 2 ? Object.keys(HANDLES) : axes;
+ const startResize = (event: PointerEvent, handle: HTMLElement, name: string) => {
+ this.startResize(event, handle, HANDLES[name], subject);
+ };
+
+ return writer.createUIElement("div", {
+ class: "ck-widget__resize-handles",
+ "aria-hidden": "true",
+ "data-cke-ignore-events": "true"
+ }, function (domDocument) {
+ const domElement = this.toDomElement(domDocument);
+ for (const name of names) {
+ const handle = domDocument.createElement("div");
+ handle.className = `ck-widget__resize-handle ck-widget__resize-handle_${name}`;
+ handle.addEventListener("pointerdown", (event) => startResize(event, handle, name));
+ domElement.append(handle);
+ }
+ return domElement;
+ });
+ }
+
+ private startResize(
+ event: PointerEvent,
+ handle: HTMLElement,
+ handleAxes: ResizeAxes,
+ { element, viewElement, config }: ResizeSubject
+ ) {
+ const editor = this.editor;
+ const widget = handle.parentElement?.parentElement;
+ if (!widget || editor.isReadOnly || event.button !== 0 || !event.isPrimary) {
+ return;
+ }
+
+ const heightTarget = handleAxes.height ? findHeightTarget(widget, config) : null;
+ const axes = { width: handleAxes.width, height: !!heightTarget };
+ if (!axes.width && !axes.height) {
+ return;
+ }
+
+ event.preventDefault();
+ editor.editing.view.focus();
+ editor.model.enqueueChange({ isUndoable: false }, (writer) => {
+ writer.setSelection(element, "on");
+ });
+
+ const targets: Record<Axis, HTMLElement> = {
+ width: widget,
+ height: heightTarget ?? widget
+ };
+ const toolbars = editor.plugins.has(WidgetToolbarRepository)
+ ? editor.plugins.get(WidgetToolbarRepository)
+ : null;
+ const finish = () => {
+ toolbars?.clearForceDisabled(TOOLBAR_LOCK);
+ this.showSize(viewElement, getSavedSize(element, config), config, false);
+ };
+
+ startResizeGesture(event, {
+ handle,
+ axes,
+ widthTarget: targets.width,
+ heightTarget: targets.height,
+ minWidth: toPixels(config.minWidth ?? DEFAULT_MIN_SIZE, targets.width),
+ minHeight: toPixels(config.minHeight ?? DEFAULT_MIN_SIZE, targets.height),
+ onPreview: (size) => {
+ toolbars?.forceDisabled(TOOLBAR_LOCK);
+ this.showSize(viewElement, toEmSize(size, targets), config, true);
+ },
+ onCommit: (size) => {
+ this.saveSize(element, toEmSize(size, targets));
+ finish();
+ },
+ onCancel: finish,
+ onTap: () => {
+ if (this.isDoubleTap(handle)) {
+ this.saveSize(element, {
+ ...(axes.width ? { width: null } : {}),
+ ...(axes.height ? { height: null } : {})
+ });
+ }
+ }
+ });
+ }
+
+ /** Shows `size` on the widget's view without changing the model. */
+ private showSize(
+ viewElement: ViewElement,
+ size: SizeValues,
+ config: ResizableWidgetConfig,
+ isResizing: boolean
+ ) {
+ this.editor.editing.view.change((writer) => {
+ if (isResizing) {
+ writer.addClass(RESIZING_CLASS, viewElement);
+ } else {
+ writer.removeClass(RESIZING_CLASS, viewElement);
+ }
+
+ for (const [ axis, value ] of Object.entries(size)) {
+ const property = `${config.propertyPrefix}-${axis}`;
+ if (value) {
+ writer.setStyle(property, value, viewElement);
+ } else {
+ writer.removeStyle(property, viewElement);
+ }
+ }
+ });
+ }
+
+ /** Saves `size` on `element` in one undo step, unless it was removed meanwhile. */
+ private saveSize(element: ModelElement, size: SizeValues) {
+ const model = this.editor.model;
+ if (element.root === model.document.graveyard) {
+ return;
+ }
+
+ model.change((writer) => {
+ for (const [ axis, value ] of Object.entries(size) as [Axis, string | null][]) {
+ if (value) {
+ writer.setAttribute(SIZE_ATTRIBUTES[axis], value, element);
+ } else {
+ writer.removeAttribute(SIZE_ATTRIBUTES[axis], element);
+ }
+ }
+ });
+ }
+
+ /** Whether a tap on `handle` follows another one on it closely enough to make a double tap. */
+ private isDoubleTap(handle: Element) {
+ const now = performance.now();
+ const isDoubleTap = this.lastTap?.handle === handle
+ && now - this.lastTap.time < DOUBLE_TAP_MS;
+ this.lastTap = isDoubleTap ? null : { handle, time: now };
+ return isDoubleTap;
+ }
+}
+
+/** A size in `em`, where `null` is the size the widget takes by itself. */
+type SizeValues = Partial<Record<Axis, string | null>>;
+
+/** A rendered widget that can be resized. */
+interface ResizeSubject {
+ element: ModelElement;
+ viewElement: ViewElement;
+ config: ResizableWidgetConfig;
+}
+
+function getAxes(config: ResizableWidgetConfig) {
+ const axes: Axis[] = [];
+ if (config.isWidthResizable) {
+ axes.push("width");
+ }
+ if (config.isHeightResizable) {
+ axes.push("height");
+ }
+ return axes;
+}
+
+function updateResizableClass(
+ writer: ViewDowncastWriter,
+ viewElement: ViewElement,
+ element: ModelElement,
+ config: ResizableWidgetConfig
+) {
+ if (config.isResizable?.(element) ?? true) {
+ writer.addClass(RESIZABLE_CLASS, viewElement);
+ } else {
+ writer.removeClass(RESIZABLE_CLASS, viewElement);
+ }
+}
+
+/** The element whose height changes, when it is rendered. */
+function findHeightTarget(widget: HTMLElement, config: ResizableWidgetConfig) {
+ const target = config.heightTarget
+ ? widget.querySelector<HTMLElement>(config.heightTarget)
+ : widget;
+ return target?.getClientRects().length ? target : null;
+}
+
+/** The size saved on `element`, for every axis it can be resized on. */
+function getSavedSize(element: ModelElement, config: ResizableWidgetConfig): SizeValues {
+ const size: SizeValues = {};
+ for (const axis of getAxes(config)) {
+ size[axis] = element.getAttribute(SIZE_ATTRIBUTES[axis]) as string | undefined ?? null;
+ }
+ return size;
+}
+
+function toEmSize(size: ResizeSize, targets: Record<Axis, HTMLElement>): SizeValues {
+ const values: SizeValues = {};
+ for (const axis of [ "width", "height" ] as const) {
+ const pixels = size[axis];
+ if (pixels !== undefined) {
+ values[axis] = pixels === null ? null : toEm(pixels, targets[axis]);
+ }
+ }
+ return values;
+}
+
+/** `pixels` in `em` of `element`, to one decimal. */
+function toEm(pixels: number, element: HTMLElement) {
+ const fontSize = parseFloat(getComputedStyle(element).fontSize);
+ return `${Math.round(pixels / fontSize * 10) / 10}em`;
+}
+
+function toPixels(em: number, element: HTMLElement) {
+ return em * parseFloat(getComputedStyle(element).fontSize);
+}
+
+declare module "ckeditor5" {
+ interface PluginsMap {
+ [ ResizableWidgets.pluginName ]: ResizableWidgets;
+ }
+}
diff --git a/packages/ckeditor5/src/plugins/resizable_widgets/resize_gesture.ts b/packages/ckeditor5/src/plugins/resizable_widgets/resize_gesture.ts
new file mode 100644
index 0000000000..7df5966ca7
--- /dev/null
+++ b/packages/ckeditor5/src/plugins/resizable_widgets/resize_gesture.ts
@@ -0,0 +1,183 @@
+/** The axes that a resize changes. */
+export interface ResizeAxes {
+ width: boolean;
+ height: boolean;
+}
+
+/** A size in pixels. An axis that is left out does not change, and a `null` width is full. */
+export interface ResizeSize {
+ width?: number | null;
+ height?: number;
+}
+
+export interface ResizeGestureOptions {
+ /** The pressed element, which captures the pointer. */
+ handle: Element;
+ axes: ResizeAxes;
+ /** The element whose width changes. Its width is full once it reaches its parent's. */
+ widthTarget: HTMLElement;
+ /** The element whose height changes. */
+ heightTarget: HTMLElement;
+ /** The smallest width, in pixels. */
+ minWidth: number;
+ /** The smallest height, in pixels. */
+ minHeight: number;
+ /** Shows the size while the pointer moves. */
+ onPreview: (size: ResizeSize) => void;
+ /** Saves the size at which the pointer is released. */
+ onCommit: (size: ResizeSize) => void;
+ /** Ends the gesture without a change, on Escape or a `pointercancel`. */
+ onCancel: () => void;
+ /** Ends the gesture when the pointer is released without moving. */
+ onTap: () => void;
+}
+
+/** The distance a pointer moves before a press becomes a resize, in pixels. */
+const DRAG_THRESHOLD = 3;
+
+/** The distance from the top or bottom of the scroll container that scrolls it, in pixels. */
+const AUTO_SCROLL_EDGE = 40;
+
+/** The largest distance scrolled per frame, in pixels. */
+const AUTO_SCROLL_STEP = 16;
+
+/**
+ * Resizes until the pointer pressed in `event` is released. The width grows towards the inline
+ * end, the height towards the bottom, and the scroll container scrolls near its edges.
+ */
+export function startResizeGesture(event: PointerEvent, options: ResizeGestureOptions) {
+ const { axes, widthTarget, heightTarget } = options;
+ const { pointerId, clientX: startX, clientY: startY } = event;
+ const startWidth = parseFloat(getComputedStyle(widthTarget).width);
+ const startHeight = parseFloat(getComputedStyle(heightTarget).height);
+ const maxWidth = getContainerWidth(widthTarget);
+ const inlineDirection = getComputedStyle(widthTarget).direction === "rtl" ? -1 : 1;
+ const scroller = findScrollContainer(heightTarget);
+ const startScrollTop = scroller.scrollTop;
+
+ let x = startX;
+ let y = startY;
+ let isMoved = false;
+ let frame = 0;
+
+ options.handle.setPointerCapture(pointerId);
+
+ const getSize = () => {
+ const size: ResizeSize = {};
+ if (axes.width) {
+ const width = Math.max(startWidth + (x - startX) * inlineDirection, options.minWidth);
+ size.width = width >= maxWidth ? null : width;
+ }
+ if (axes.height) {
+ const scrolled = scroller.scrollTop - startScrollTop;
+ size.height = Math.max(startHeight + y - startY + scrolled, options.minHeight);
+ }
+ return size;
+ };
+
+ const update = () => {
+ isMoved ||= Math.hypot(x - startX, y - startY) >= DRAG_THRESHOLD;
+ if (isMoved) {
+ options.onPreview(getSize());
+ }
+ };
+
+ const scrollStep = () => {
+ const step = isMoved ? getAutoScrollStep(scroller, y) : 0;
+ if (step) {
+ scroller.scrollTop += step;
+ update();
+ }
+ frame = requestAnimationFrame(scrollStep);
+ };
+
+ const onPointerMove = (moveEvent: PointerEvent) => {
+ if (moveEvent.pointerId === pointerId) {
+ x = moveEvent.clientX;
+ y = moveEvent.clientY;
+ update();
+ }
+ };
+
+ const onPointerUp = (upEvent: PointerEvent) => {
+ if (upEvent.pointerId !== pointerId) {
+ return;
+ }
+ stop();
+ if (isMoved) {
+ options.onCommit(getSize());
+ } else {
+ options.onTap();
+ }
+ };
+
+ const onPointerCancel = (cancelEvent: PointerEvent) => {
+ if (cancelEvent.pointerId === pointerId) {
+ stop();
+ options.onCancel();
+ }
+ };
+
+ const onKeyDown = (keyEvent: KeyboardEvent) => {
+ if (keyEvent.key === "Escape") {
+ keyEvent.preventDefault();
+ keyEvent.stopPropagation();
+ stop();
+ options.onCancel();
+ }
+ };
+
+ const stop = () => {
+ cancelAnimationFrame(frame);
+ window.removeEventListener("pointermove", onPointerMove, true);
+ window.removeEventListener("pointerup", onPointerUp, true);
+ window.removeEventListener("pointercancel", onPointerCancel, true);
+ window.removeEventListener("keydown", onKeyDown, true);
+ };
+
+ window.addEventListener("pointermove", onPointerMove, true);
+ window.addEventListener("pointerup", onPointerUp, true);
+ window.addEventListener("pointercancel", onPointerCancel, true);
+ window.addEventListener("keydown", onKeyDown, true);
+ if (axes.height) {
+ frame = requestAnimationFrame(scrollStep);
+ }
+}
+
+/** The width inside the padding of the parent of `element`. */
+function getContainerWidth(element: HTMLElement) {
+ const parent = element.parentElement ?? document.documentElement;
+ const style = getComputedStyle(parent);
+ return parent.clientWidth - parseFloat(style.paddingLeft) - parseFloat(style.paddingRight);
+}
+
+/** The closest ancestor of `element` that scrolls vertically, or the document. */
+function findScrollContainer(element: HTMLElement): Element {
+ for (let parent = element.parentElement; parent; parent = parent.parentElement) {
+ if (/auto|scroll/.test(getComputedStyle(parent).overflowY)) {
+ return parent;
+ }
+ }
+
+ return document.documentElement;
+}
+
+/**
+ * The distance to scroll `scroller` by while the pointer is at `y`: further the closer it is to
+ * the top or bottom edge, and nothing away from them.
+ */
+function getAutoScrollStep(scroller: Element, y: number) {
+ const { top, bottom } = scroller === document.documentElement
+ ? { top: 0, bottom: window.innerHeight }
+ : scroller.getBoundingClientRect();
+
+ let depth = 0;
+ if (y > bottom - AUTO_SCROLL_EDGE) {
+ depth = y - (bottom - AUTO_SCROLL_EDGE);
+ } else if (y < top + AUTO_SCROLL_EDGE) {
+ depth = y - (top + AUTO_SCROLL_EDGE);
+ }
+
+ const ratio = Math.max(-1, Math.min(1, depth / AUTO_SCROLL_EDGE));
+ return Math.round(ratio * AUTO_SCROLL_STEP);
+}
diff --git a/packages/ckeditor5/src/theme/resizable_widgets.css b/packages/ckeditor5/src/theme/resizable_widgets.css
new file mode 100644
index 0000000000..f04fe5d6b7
--- /dev/null
+++ b/packages/ckeditor5/src/theme/resizable_widgets.css
@@ -0,0 +1,96 @@
+:where(:root) {
+ --ck-resize-handle-color: var(--ck-color-focus-border);
+ --ck-resize-handle-hit-size: 12px;
+ --ck-resize-handle-length: 32px;
+ --ck-resize-handle-thickness: 4px;
+}
+
+@media (pointer: coarse) {
+ :where(:root) {
+ --ck-resize-handle-hit-size: 32px;
+ }
+}
+
+.ck .ck-widget > .ck-widget__resize-handles {
+ display: none;
+ position: absolute;
+ inset: 0;
+ pointer-events: none;
+}
+
+.ck .ck-widget_resizable:is(.ck-widget_selected, .ck-widget_resizing) > .ck-widget__resize-handles {
+ display: block;
+}
+
+@media (hover: hover) {
+ .ck .ck-widget_resizable:hover > .ck-widget__resize-handles {
+ display: block;
+ }
+}
+
+.ck.ck-editor__editable.ck-read-only .ck-widget > .ck-widget__resize-handles {
+ display: none;
+}
+
+.ck .ck-widget__resize-handle {
+ --_offset: calc(var(--ck-resize-handle-hit-size) / -2);
+
+ position: absolute;
+ pointer-events: auto;
+ touch-action: none;
+
+ &::after {
+ content: "";
+ position: absolute;
+ inset: 50% auto auto 50%;
+ border-radius: var(--ck-resize-handle-thickness);
+ background-color: var(--ck-resize-handle-color);
+ translate: -50% -50%;
+ }
+
+ /* Edge handles cover the middle half of the edge, away from the type-around buttons. */
+ &.ck-widget__resize-handle_width {
+ inset-block: 25%;
+ inset-inline-end: var(--_offset);
+ width: var(--ck-resize-handle-hit-size);
+ cursor: ew-resize;
+
+ &::after {
+ width: var(--ck-resize-handle-thickness);
+ height: min(var(--ck-resize-handle-length), 100%);
+ }
+ }
+
+ &.ck-widget__resize-handle_height {
+ inset-inline: 25%;
+ bottom: var(--_offset);
+ height: var(--ck-resize-handle-hit-size);
+ cursor: ns-resize;
+
+ &::after {
+ width: min(var(--ck-resize-handle-length), 100%);
+ height: var(--ck-resize-handle-thickness);
+ }
+ }
+
+ &.ck-widget__resize-handle_corner {
+ bottom: var(--_offset);
+ inset-inline-end: var(--_offset);
+ width: var(--ck-resize-handle-hit-size);
+ height: var(--ck-resize-handle-hit-size);
+ cursor: nwse-resize;
+
+ &:dir(rtl) {
+ cursor: nesw-resize;
+ }
+
+ &::after {
+ width: calc(var(--ck-resize-handle-thickness) * 2);
+ height: calc(var(--ck-resize-handle-thickness) * 2);
+ }
+ }
+}
+
+.ck .ck-widget_resizing iframe {
+ pointer-events: none;
+}
diff --git a/packages/trilium-core/src/services/sanitizer.spec.ts b/packages/trilium-core/src/services/sanitizer.spec.ts
index 56e94bf39a..0aa902290d 100644
--- a/packages/trilium-core/src/services/sanitizer.spec.ts
+++ b/packages/trilium-core/src/services/sanitizer.spec.ts
@@ -52,6 +52,14 @@ describe("sanitize", () => {
expect(sanitizeHtml(dirty)).toBe(clean);
});
+ it("keeps the size of a resized embed and drops other variables on it", () => {
+ const html = `<figure class="include-note" style="--include-note-width:30em;--include-note-height:12.5em" data-note-id="abc" data-box-size="medium"></figure>`;
+ expect(sanitizeHtml(html)).toBe(html);
+
+ const dirty = `<figure class="include-note" style="--include-note-height:calc(100vh);--other:1em" data-note-id="abc"></figure>`;
+ expect(sanitizeHtml(dirty)).toBe(`<figure class="include-note" data-note-id="abc"></figure>`);
+ });
+
it("keeps the hidden-border style on table header cells", () => {
// The OneNote importer maps hidden borders to border-color:transparent on table, td and th —
// all three must survive sanitization, or header cells render with visible borders.
diff --git a/packages/trilium-core/src/services/sanitizer.ts b/packages/trilium-core/src/services/sanitizer.ts
index ceef2d2e96..15fca05028 100644
--- a/packages/trilium-core/src/services/sanitizer.ts
+++ b/packages/trilium-core/src/services/sanitizer.ts
@@ -84,7 +84,10 @@ export function sanitizeHtml(dirtyHtml: string) {
figure: {
float: [/^\s*(left|right|none)\s*$/],
width: sizeRegex,
- height: sizeRegex
+ height: sizeRegex,
+ // The size of a resized embed.
+ "--include-note-width": sizeRegex,
+ "--include-note-height": sizeRegex
},
img: {
// Allow fractional ratios too (e.g. OneNote reports 577.5×277.5 screen clippings).