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
feat(text): pick an icon in a balloon at the caret
Elian Doran5d30920f1f44
diff --git a/apps/client/src/widgets/type_widgets/text/CKEditorWithWatchdog.tsx b/apps/client/src/widgets/type_widgets/text/CKEditorWithWatchdog.tsxindex 0049813261..d06842555d 100644--- a/apps/client/src/widgets/type_widgets/text/CKEditorWithWatchdog.tsx+++ b/apps/client/src/widgets/type_widgets/text/CKEditorWithWatchdog.tsx@@ -21,8 +21,6 @@ export interface CKEditorApi {addHtmlToEditor(html: string): void;addIncludeNote(noteId: string, boxSize?: BoxSize): void;addImage(noteId: string): Promise<void>;- /** Inserts an icon of an installed icon pack, named by its class, e.g. `bx bx-star`. */- insertIcon(iconClass: string): void;}/**@@ -219,13 +217,6 @@ export default function CKEditorWithWatchdog({ containerRef: externalContainerReeditor?.execute("insertImage", { source: src });});},- insertIcon(iconClass) {- const editor = watchdogRef.current?.editor;- if (!editor) return;-- editor.execute("insertIcon", { iconClass });- editor.editing.view.focus();- },}));useLegacyImperativeHandlers({diff --git a/apps/client/src/widgets/type_widgets/text/EditableText.tsx b/apps/client/src/widgets/type_widgets/text/EditableText.tsxindex 29733019a7..37926233a1 100644--- a/apps/client/src/widgets/type_widgets/text/EditableText.tsx+++ b/apps/client/src/widgets/type_widgets/text/EditableText.tsx@@ -3,6 +3,7 @@ import "./LinkEmbed.css";import { CKTextEditor, EditorWatchdog, SnippetDefinition } from "@triliumnext/ckeditor5";import { deferred } from "@triliumnext/commons";+import { createPortal } from "preact/compat";import { useCallback, useEffect, useRef, useState } from "preact/hooks";import appContext from "../../../components/app_context";@@ -16,7 +17,9 @@ import options from "../../../services/options";import { consumeSearchTerms } from "../../../services/search_jump";import toast from "../../../services/toast";import utils, { isMobile } from "../../../services/utils";+import type { IconPickerOpts } from "../../dialogs/icon_picker";import { useEditorSpacedUpdate, useLegacyImperativeHandlers, useNoteLabel, useSearchTermsConsumer, useTriliumEvent, useTriliumOption, useTriliumOptionBool } from "../../react/hooks";+import IconPicker from "../../react/IconPicker";import { setEditorNoteId } from "../../react/NoteStore";import { TypeWidgetProps } from "../type_widget";import CKEditorWithWatchdog, { CKEditorApi, NotificationEventData, NotificationEventInfo } from "./CKEditorWithWatchdog";@@ -38,6 +41,8 @@ export default function EditableText({ note, parentComponent, ntxId, noteContextconst contentNoteIdRef = useRef<string>();const watchdogRef = useRef<EditorWatchdog>(null);const editorApiRef = useRef<CKEditorApi>(null);+ /** The balloon the editor has opened for the icon picker, while one is open. */+ const [ iconPickerRequest, setIconPickerRequest ] = useState<IconPickerOpts & { container: HTMLElement } | null>(null);const [ language ] = useNoteLabel(note, "language");const [ textNoteEditorType ] = useTriliumOption("textNoteEditorType");const [ codeBlockWordWrap ] = useTriliumOptionBool("codeBlockWordWrap");@@ -138,13 +143,16 @@ export default function EditableText({ note, parentComponent, ntxId, noteContexteditorApi: editorApiRef.current,});},- insertIconToTextCommand() {- if (!editorApiRef.current) return;- parentComponent?.triggerCommand("showIconPickerDialog", {- onSelect(iconClass) {- editorApiRef.current?.insertIcon(iconClass);- }- });+ // The editor places the balloon and takes it away; what goes inside it is the picker the+ // application already has over every installed icon pack.+ showIconPicker(request: IconPickerOpts & { container: HTMLElement }) {+ if (isMobile()) {+ parentComponent?.triggerCommand("showIconPickerDialog", { onSelect: request.onSelect });+ return null;+ }++ setIconPickerRequest(request);+ return () => setIconPickerRequest(null);},insertDateTimeToTextCommand() {if (!editorApiRef.current) return;@@ -494,10 +502,21 @@ export default function EditableText({ note, parentComponent, ntxId, noteContext}}/>}++ {iconPickerRequest && createPortal(+ <IconPicker+ columnCount={ICON_PICKER_COLUMNS}+ onSelect={iconPickerRequest.onSelect}+ />,+ iconPickerRequest.container+ )}</>);}+/** How wide the picker stands in the editor's balloon, in icons. */+const ICON_PICKER_COLUMNS = 12;+/*** Inserts an empty paragraph at the very top of the document and places the cursor in it, giving the* Notion-like behavior when pressing Enter in the note title. If the first block is already an emptydiff --git a/packages/ckeditor5/src/augmentation.ts b/packages/ckeditor5/src/augmentation.tsindex 3461787b91..c7f598e81b 100644--- a/packages/ckeditor5/src/augmentation.ts+++ b/packages/ckeditor5/src/augmentation.ts@@ -22,7 +22,20 @@ declare global {unresolved?: boolean;}+ interface IconPickerRequest {+ /** The element to paint the picker into, which the editor owns and places. */+ container: HTMLElement;+ /** Receives the class of the icon picked, e.g. `bx bx-star`. */+ onSelect(iconClass: string): void;+ }+interface EditorComponent extends Component {+ /**+ * Paints the host's icon picker into `container`, and answers with the way to take it down+ * again. A host that shows the picker somewhere of its own — a phone, which has no room for+ * a balloon — leaves `container` alone and answers `null`.+ */+ showIconPicker(request: IconPickerRequest): (() => void) | null;loadReferenceLinkTitle($el: JQuery<HTMLElement>, href: string): Promise<void>;createNoteForReferenceLink(title: string, intoInbox: boolean): Promise<string | undefined>;loadIncludedNote(noteId: string, $el: JQuery<HTMLElement>, boxSize?: string): void;@@ -45,5 +58,5 @@ declare global {getHeaders(): Promise<Record<string, string>>;getReferenceLinkTitle(href: string): Promise<string>;getReferenceLinkTitleSync(href: string): string;- }+ };}diff --git a/packages/ckeditor5/src/plugins/inline_icon/inline_icon.spec.ts b/packages/ckeditor5/src/plugins/inline_icon/inline_icon.spec.tsindex 20876b70ab..82085dfebc 100644--- a/packages/ckeditor5/src/plugins/inline_icon/inline_icon.spec.ts+++ b/packages/ckeditor5/src/plugins/inline_icon/inline_icon.spec.ts@@ -1,8 +1,8 @@import {_getModelData as getModelData, _getViewData as getViewData, _setModelData as setModelData,- type ButtonView, type ClassicEditor, GeneralHtmlSupport, Paragraph+ type ButtonView, type ClassicEditor, ContextualBalloon, GeneralHtmlSupport, Paragraph} from "ckeditor5";-import { beforeEach, describe, expect, it, vi } from "vitest";+import { beforeEach, describe, expect, it, type Mock, vi } from "vitest";import { createTestEditor } from "../../../test/editor-kit.js";import { installGlobMock } from "../../../test/globals-test-kit.js";@@ -55,6 +55,12 @@ describe("InlineIcon", () => {.toBe(`<paragraph>Press <inlineIcon iconClass="bx bx-cog"></inlineIcon>.</paragraph>`);});+ it("keeps a marked span that names no pack as it found it", () => {+ editor.setData(`<p><span class="tn-icon"></span></p>`);++ expect(editor.getData()).toBe(`<p><span class="tn-icon"></span></p>`);+ });+it("ignores an insert that names no icon", () => {setModelData(editor.model, "<paragraph>[]</paragraph>");@@ -71,14 +77,102 @@ describe("InlineIcon", () => {expect(command?.isEnabled).toBe(false);});- it("asks the host to open its icon picker, rather than picking itself", () => {- const triggerCommand = vi.fn();- installGlobMock({ getComponentByEl: () => ({ triggerCommand }) });+});++describe("the balloon InlineIcon picks in", () => {+ let editor: ClassicEditor;+ let showIconPicker: Mock<(request: IconPickerRequest) => (() => void) | null>;+ let release: Mock<() => void>;++ beforeEach(async () => {+ release = vi.fn();+ showIconPicker = vi.fn(() => release);+ installGlobMock({ getComponentByEl: () => ({ showIconPicker }) });++ editor = await createTestEditor([ Paragraph, InlineIcon ]);+ setModelData(editor.model, "<paragraph>[]</paragraph>");+ });++ it("hands the host the balloon's own element to paint into", () => {+ pressInsertIcon(editor);++ const balloon = editor.plugins.get(ContextualBalloon);+ const { container } = showIconPicker.mock.calls[0][0];++ expect(balloon.visibleView).not.toBeNull();+ expect(balloon.view.element?.contains(container)).toBe(true);+ // Everything a balloon shows sits inside the body collection's `ck-reset_all`, which would+ // strip the application's own styling off the picker.+ expect(container.classList.contains("ck-reset_all-excluded")).toBe(true);+ });++ it("inserts what the host reports, and lets go of the picker", () => {+ pressInsertIcon(editor);++ showIconPicker.mock.calls[0][0].onSelect("bx bx-cog");++ expect(editor.getData()).toBe(`<p><span class="tn-icon bx bx-cog"></span></p>`);+ expect(release).toHaveBeenCalledOnce();+ expect(editor.plugins.get(ContextualBalloon).visibleView).toBeNull();+ });++ it("takes the balloon back down for a host that shows the picker its own way", () => {+ showIconPicker.mockReturnValue(null);- const button = editor.ui.componentFactory.create("insertIcon") as unknown as ButtonView;- button.fire("execute");+ pressInsertIcon(editor);- expect(triggerCommand).toHaveBeenCalledWith("insertIconToText");+ expect(showIconPicker).toHaveBeenCalledOnce();+ expect(editor.plugins.get(ContextualBalloon).visibleView).toBeNull();+ });++ it("lets go of the picker when a click lands outside the balloon", () => {+ pressInsertIcon(editor);++ document.body.dispatchEvent(new MouseEvent("mousedown", { bubbles: true }));++ expect(release).toHaveBeenCalledOnce();+ expect(editor.plugins.get(ContextualBalloon).visibleView).toBeNull();+ });++ it("lets go of the picker on Esc, from the text and from the picker alike", () => {+ pressInsertIcon(editor);+ const container = showIconPicker.mock.calls[0][0].container;++ // Esc reaches the editor only while the caret still has focus; once the picker has taken+ // it, the balloon's own element is where the key lands.+ container.dispatchEvent(escapeKeyDown());+ expect(release).toHaveBeenCalledOnce();+ expect(editor.plugins.get(ContextualBalloon).visibleView).toBeNull();++ pressInsertIcon(editor);+ editor.editing.view.getDomRoot()?.dispatchEvent(escapeKeyDown());++ expect(release).toHaveBeenCalledTimes(2);+ expect(editor.plugins.get(ContextualBalloon).visibleView).toBeNull();+ });++ it("leaves the one balloon it has open alone when the button is pressed again", () => {+ pressInsertIcon(editor);+ pressInsertIcon(editor);++ expect(showIconPicker).toHaveBeenCalledOnce();+ expect(release).not.toHaveBeenCalled();+ });++ it("leaves Esc to the rest of the editor while no picker is open", () => {+ const escape = escapeKeyDown();+ editor.editing.view.getDomRoot()?.dispatchEvent(escape);++ expect(escape.defaultPrevented).toBe(false);+ expect(release).not.toHaveBeenCalled();+ });++ it("lets go of the picker when the editor is torn down under it", async () => {+ pressInsertIcon(editor);++ await editor.destroy();++ expect(release).toHaveBeenCalledOnce();});});@@ -102,3 +196,12 @@ describe("InlineIcon under the shipped General HTML Support configuration", () =expect(withoutPlugin.getData()).toBe("<p>Press .</p>");});});++function pressInsertIcon(editor: ClassicEditor) {+ const button = editor.ui.componentFactory.create("insertIcon") as unknown as ButtonView;+ button.fire("execute");+}++function escapeKeyDown() {+ return new KeyboardEvent("keydown", { key: "Escape", keyCode: 27, bubbles: true });+}diff --git a/packages/ckeditor5/src/plugins/inline_icon/inline_icon_ui.ts b/packages/ckeditor5/src/plugins/inline_icon/inline_icon_ui.tsindex 4a9f6cd98e..6524e302e8 100644--- a/packages/ckeditor5/src/plugins/inline_icon/inline_icon_ui.ts+++ b/packages/ckeditor5/src/plugins/inline_icon/inline_icon_ui.ts@@ -1,11 +1,18 @@-import { ButtonView, Plugin } from "ckeditor5";+import {+ BalloonPanelView, ButtonView, clickOutsideHandler, type Command, ContextualBalloon,+ type Editor, KeystrokeHandler, type Locale, Plugin, View+} from "ckeditor5";import insertIconIcon from "../../icons/insert-icon.svg?raw";import { INSERT_ICON_COMMAND } from "./inline_icon_editing.js";/**- * The button an icon is inserted through. Picking the icon is left to the host, which already has- * a picker over every installed icon pack; it answers by running {@link INSERT_ICON_COMMAND}.+ * The button an icon is inserted through, and the balloon the picking happens in.+ *+ * The editor owns the balloon — where it points, when it goes away — and the application paints its+ * own picker into it through `showIconPicker`, which is the one place every installed icon pack is+ * searchable. A host with no room for a balloon shows the picker its own way and answers with+ * nothing to take down.*/export default class InlineIconUI extends Plugin {@@ -13,12 +20,21 @@ export default class InlineIconUI extends Plugin {return "InlineIconUI" as const;}+ public static get requires() {+ return [ ContextualBalloon ] as const;+ }++ private _balloon: ContextualBalloon = this.editor.plugins.get(ContextualBalloon);+ private _pickerView: IconPickerView | null = null;+ private _releasePicker: (() => void) | null = null;+init() {const editor = this.editor;const t = editor.t;editor.ui.componentFactory.add(INSERT_ICON_COMMAND, (locale) => {- const command = editor.commands.get(INSERT_ICON_COMMAND);+ // Always registered: InlineIconEditing is loaded beside this plugin.+ const command = editor.commands.get(INSERT_ICON_COMMAND) as Command;const view = new ButtonView(locale);view.set({@@ -27,21 +43,159 @@ export default class InlineIconUI extends Plugin {tooltip: true});- if (command) {- view.bind("isEnabled").to(command, "isEnabled");+ view.bind("isEnabled").to(command, "isEnabled");++ this.listenTo(view, "execute", () => this._show());++ return view;+ });++ // Esc reaches the editor only while the caret still has focus; the picker takes focus with+ // it, so the view carries a handler of its own (see {@link IconPickerView}).+ editor.keystrokes.set("Esc", (_data, cancel) => {+ if (this._pickerView) {+ this._hide();+ cancel();}+ });+ }- this.listenTo(view, "execute", () => {- const editorEl = editor.editing.view.getDomRoot();- if (!editorEl) {- return;- }+ public override destroy() {+ // Before the base class stops the listeners the balloon is taken down through.+ this._hide();+ super.destroy();+ }- glob.getComponentByEl(editorEl).triggerCommand("insertIconToText");- });+ private _show() {+ const editor = this.editor;+ const editorEl = editor.editing.view.getDomRoot();+ const position = getBalloonPosition(editor);- return view;+ if (this._pickerView || !editorEl || !position) {+ return;+ }++ const view = new IconPickerView(editor.locale);+ view.keystrokes.set("Esc", (_data, cancel) => {+ this._hide();+ editor.editing.view.focus();+ cancel();+ });++ // Wired per picker rather than once: the handler listens through the view, so destroying+ // the view on the way out is what stops it listening.+ clickOutsideHandler({+ emitter: view,+ activator: () => this._pickerView === view,+ /* v8 ignore next -- the balloon renders its panel as the editor starts up */+ contextElements: this._balloon.view.element ? [ this._balloon.view.element ] : [],+ callback: () => this._hide()});++ this._balloon.add({ view, position });+ this._pickerView = view;++ const container = view.element;+ /* v8 ignore next 4 -- the balloon renders the view as it adds it, so it has an element */+ if (!container) {+ this._hide();+ return;+ }++ const release = glob.getComponentByEl<EditorComponent>(editorEl).showIconPicker({+ container,+ onSelect: (iconClass) => {+ this._hide();+ editor.execute(INSERT_ICON_COMMAND, { iconClass });+ editor.editing.view.focus();+ }+ });++ if (!release) {+ this._hide();+ return;+ }++ this._releasePicker = release;}+ private _hide() {+ const view = this._pickerView;++ this._pickerView = null;+ this._releasePicker?.();+ this._releasePicker = null;++ if (!view) {+ return;+ }++ if (this._balloon.hasView(view)) {+ this._balloon.remove(view);+ }++ view.destroy();+ }++}++/**+ * What the balloon holds: an element for the host to paint into, and nothing else.+ *+ * It carries `ck-reset_all-excluded` because everything a balloon shows sits inside the body+ * collection's `ck-reset_all`, which would strip the application's own styling off the picker.+ */+class IconPickerView extends View {++ public readonly keystrokes = new KeystrokeHandler();++ constructor(locale: Locale) {+ super(locale);++ this.setTemplate({+ tag: "div",+ attributes: {+ class: [ "ck-reset_all-excluded", "icon-picker-balloon" ]+ }+ });+ }++ public override render() {+ super.render();++ /* v8 ignore next 3 -- `render()` is what builds the element, so it is never absent here */+ if (!this.element) {+ return;+ }++ this.keystrokes.listenTo(this.element);+ }++ public override destroy() {+ super.destroy();+ this.keystrokes.destroy();+ }++}++/** Where the balloon points: the text the caret is in, wherever there is room for it. */+function getBalloonPosition(editor: Editor) {+ 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+ ]+ };}