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
fix(text): place the icon picker's balloon once it has been painted
Elian Doranb132963bc2bc
diff --git a/packages/ckeditor5/src/plugins/inline_icon/inline_icon.spec.ts b/packages/ckeditor5/src/plugins/inline_icon/inline_icon.spec.tsindex 82085dfebc..4e59224744 100644--- a/packages/ckeditor5/src/plugins/inline_icon/inline_icon.spec.ts+++ b/packages/ckeditor5/src/plugins/inline_icon/inline_icon.spec.ts@@ -2,9 +2,10 @@ import {_getModelData as getModelData, _getViewData as getViewData, _setModelData as setModelData,type ButtonView, type ClassicEditor, ContextualBalloon, GeneralHtmlSupport, Paragraph} from "ckeditor5";-import { beforeEach, describe, expect, it, type Mock, vi } from "vitest";+import editorStylesheetUrl from "ckeditor5/ckeditor5.css?url";+import { beforeAll, beforeEach, describe, expect, it, type Mock, vi } from "vitest";-import { createTestEditor } from "../../../test/editor-kit.js";+import { createTestEditor, getEditorElement } from "../../../test/editor-kit.js";import { installGlobMock } from "../../../test/globals-test-kit.js";import InlineIcon from "./inline_icon.js";import InlineIconEditing from "./inline_icon_editing.js";@@ -106,6 +107,21 @@ describe("the balloon InlineIcon picks in", () => {expect(container.classList.contains("ck-reset_all-excluded")).toBe(true);});+ it("aims at the caret, read afresh on every placing", () => {+ const balloon = editor.plugins.get(ContextualBalloon);+ setModelData(editor.model, "<paragraph>Hello[] there</paragraph>");++ pressInsertIcon(editor);++ const { target } = balloon.getPositionOptions() ?? {};+ expect(typeof target).toBe("function");++ const caret = typeof target === "function" ? target() : target;+ expect(caret).toBeInstanceOf(Range);+ expect((caret as Range).collapsed).toBe(true);+ expect((caret as Range).startContainer.textContent).toBe("Hello there");+ });+it("inserts what the host reports, and lets go of the picker", () => {pressInsertIcon(editor);@@ -176,6 +192,46 @@ describe("the balloon InlineIcon picks in", () => {});});+describe("where the balloon holding the picker ends up", () => {+ // Real geometry needs the editor's own stylesheet, which the specs otherwise do without: it is+ // what makes the balloon panel an absolutely positioned box the placing can move.+ beforeAll(() => new Promise<void>((resolve, reject) => {+ const link = document.createElement("link");+ link.rel = "stylesheet";+ link.href = editorStylesheetUrl;+ link.onload = () => resolve();+ link.onerror = () => reject(new Error("the editor stylesheet did not load"));+ document.head.appendChild(link);+ }));++ beforeEach(() => installPaintingHost());++ it("places itself again once the host has painted, so the arrow finds the caret", async () => {+ const editor = await createTestEditor([ Paragraph, InlineIcon ]);+ getEditorElement(editor).style.cssText = "width: 300px; margin: 200px 0 0 20px;";+ setModelData(editor.model, "<paragraph>Hello[] there</paragraph>");++ pressInsertIcon(editor);++ const balloon = editor.plugins.get(ContextualBalloon);+ const placedWhileEmpty = balloonRect(balloon).left;++ // The observer delivers on a later frame, as it does for a host that paints through its+ // own renderer rather than synchronously.+ await new Promise((resolve) => setTimeout(resolve, 100));++ const view = editor.editing.view;+ const range = view.document.selection.getFirstRange();+ if (!range) throw new Error("the caret has no range");+ const caret = view.domConverter.viewRangeToDom(range).getBoundingClientRect();+ const panel = balloonRect(balloon);++ expect(panel.width).toBeGreaterThan(PAINTED_PICKER_WIDTH);+ expect(Math.abs(arrowX(balloon.view.position, panel) - caret.x)).toBeLessThan(20);+ expect(panel.left).not.toBe(placedWhileEmpty);+ });+});+describe("InlineIcon under the shipped General HTML Support configuration", () => {// `textNoteHtmlSupportEnabled` ships off, which leaves GHS with an empty allow-list: a span// carrying nothing but classes is dropped unless a plugin claims it.@@ -205,3 +261,42 @@ function pressInsertIcon(editor: ClassicEditor) {function escapeKeyDown() {return new KeyboardEvent("keydown", { key: "Escape", keyCode: 27, bubbles: true });}++/** How wide the stand-in for the picker is, which the balloon has to be placed around. */+const PAINTED_PICKER_WIDTH = 260;++/** A host that paints something the picker's size into the element the editor gives it. */+function installPaintingHost() {+ installGlobMock({+ getComponentByEl: () => ({+ showIconPicker({ container }: { container: HTMLElement }) {+ const painted = document.createElement("div");+ painted.style.cssText = `width: ${PAINTED_PICKER_WIDTH}px; height: 400px;`;+ container.appendChild(painted);++ return () => painted.remove();+ }+ })+ });+}++function balloonRect(balloon: ContextualBalloon) {+ const element = balloon.view.element;+ if (!element) {+ throw new Error("the balloon has no element");+ }++ return element.getBoundingClientRect();+}++/** Where the theme draws the arrow: centred for `arrow_n`/`arrow_s`, else 16px in from an edge. */+function arrowX(position: string | undefined, panel: DOMRect) {+ if (position?.endsWith("_nw") || position?.endsWith("_sw")) {+ return panel.left + 16;+ }+ if (position?.endsWith("_ne") || position?.endsWith("_se")) {+ return panel.right - 16;+ }++ return panel.left + panel.width / 2;+}diff --git a/packages/ckeditor5/src/plugins/inline_icon/inline_icon_ui.ts b/packages/ckeditor5/src/plugins/inline_icon/inline_icon_ui.tsindex 6524e302e8..64b1f12d0a 100644--- a/packages/ckeditor5/src/plugins/inline_icon/inline_icon_ui.ts+++ b/packages/ckeditor5/src/plugins/inline_icon/inline_icon_ui.ts@@ -1,6 +1,6 @@import {- BalloonPanelView, ButtonView, clickOutsideHandler, type Command, ContextualBalloon,- type Editor, KeystrokeHandler, type Locale, Plugin, View+ ButtonView, clickOutsideHandler, type Command, ContextualBalloon, type Editor,+ KeystrokeHandler, type Locale, Plugin, View, type ViewRange} from "ckeditor5";import insertIconIcon from "../../icons/insert-icon.svg?raw";@@ -27,6 +27,8 @@ export default class InlineIconUI extends Plugin {private _balloon: ContextualBalloon = this.editor.plugins.get(ContextualBalloon);private _pickerView: IconPickerView | null = null;private _releasePicker: (() => void) | null = null;+ private _pickerResize: ResizeObserver | null = null;+ private _replacePicker = 0;init() {const editor = this.editor;@@ -69,9 +71,9 @@ export default class InlineIconUI extends Plugin {private _show() {const editor = this.editor;const editorEl = editor.editing.view.getDomRoot();- const position = getBalloonPosition(editor);+ const shownAt = editor.editing.view.document.selection.getFirstRange();- if (this._pickerView || !editorEl || !position) {+ if (this._pickerView || !editorEl || !shownAt) {return;}@@ -92,7 +94,7 @@ export default class InlineIconUI extends Plugin {callback: () => this._hide()});- this._balloon.add({ view, position });+ this._balloon.add({ view, position: getBalloonPosition(editor, shownAt) });this._pickerView = view;const container = view.element;@@ -117,12 +119,32 @@ export default class InlineIconUI extends Plugin {}this._releasePicker = release;++ // The host paints into the container only once the call above has returned, and a balloon+ // placed while it is still empty puts its arrow half the picker's width away from the+ // caret. Place it again whenever what it holds changes size, which a narrowed grid needs+ // as much as the first paint does. The placing waits for the next frame: it can itself+ // change the width the container is given, and Chrome reports that as an observer loop.+ this._pickerResize = new ResizeObserver(() => {+ cancelAnimationFrame(this._replacePicker);++ this._replacePicker = requestAnimationFrame(() => {+ /* v8 ignore next -- disconnecting takes the pending frames with it */+ if (this._pickerView) {+ this._balloon.updatePosition();+ }+ });+ });+ this._pickerResize.observe(container);}private _hide() {const view = this._pickerView;this._pickerView = null;+ this._pickerResize?.disconnect();+ this._pickerResize = null;+ cancelAnimationFrame(this._replacePicker);this._releasePicker?.();this._releasePicker = null;@@ -130,6 +152,7 @@ export default class InlineIconUI extends Plugin {return;}+ /* v8 ignore next -- a picker this plugin still holds is one the balloon has */if (this._balloon.hasView(view)) {this._balloon.remove(view);}@@ -178,24 +201,16 @@ class IconPickerView extends View {}-/** Where the balloon points: the text the caret is in, wherever there is room for it. */-function getBalloonPosition(editor: Editor) {+/** Where the balloon points: the caret, read afresh on every placing, as the emoji picker does. */+function getBalloonPosition(editor: Editor, shownAt: ViewRange) {const view = editor.editing.view;- const range = view.document.selection.getFirstRange();-- /* v8 ignore next 3 -- a rendered document always holds a range for the caret */- if (!range) {- return null;- }-- const { southArrowNorth, southArrowNorthWest, southArrowNorthEast, northArrowSouth,- northArrowSouthWest, northArrowSouthEast } = BalloonPanelView.defaultPositions;return {- target: view.domConverter.viewRangeToDom(range),- positions: [- southArrowNorth, southArrowNorthWest, southArrowNorthEast,- northArrowSouth, northArrowSouthWest, northArrowSouthEast- ]+ target: () => {+ /* v8 ignore next -- a rendered document always holds a range for the caret */+ const range = view.document.selection.getFirstRange() ?? shownAt;++ return view.domConverter.viewRangeToDom(range);+ }};}