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
chore(text): show the inline icon picker through editor config
Elian Doran4186a93e4b64
diff --git a/.claude/skills/ckeditor5-testing/references/patterns.md b/.claude/skills/ckeditor5-testing/references/patterns.mdindex 1ac7973eb9..eb377075f5 100644--- a/.claude/skills/ckeditor5-testing/references/patterns.md+++ b/.claude/skills/ckeditor5-testing/references/patterns.md@@ -41,7 +41,7 @@ Host services that need no component come through the editor config, so a spec p`createLinkEmbedHost()` in `test/link-embed-kit.ts` builds the mocked entry), and `getNoteId` plus`attachmentUpload: { getHeaders, getLocalUpload, getEmbedBoxSize }` (uploads), and the dialogs abutton hands over to the host: `internalLink: { openDialog }`, `markdownImport: { open }`,-`contentEmbed: { pickNote }` and `cutToNote: { cut, saveNow }`. Each falls back to a placeholder or a+`contentEmbed: { pickNote }`, `cutToNote: { cut, saveNow }` and `inlineIcon: { showPicker }`. Each falls back to a placeholder or ano-op when left out (an upload without `getNoteId` is rejected), so a spec that does not assert onit can omit it. A spec sharing one editor across tests can swap an entry with`editor.config.set()`, which the plugins read at call time.diff --git a/apps/client/src/widgets/type_widgets/text/CKEditor.tsx b/apps/client/src/widgets/type_widgets/text/CKEditor.tsxindex d77632fa35..261c948de2 100644--- a/apps/client/src/widgets/type_widgets/text/CKEditor.tsx+++ b/apps/client/src/widgets/type_widgets/text/CKEditor.tsx@@ -1,14 +1,16 @@import {- type CKEditorError, CKTextEditor, ClassicEditor, getLinkAtSelection, onTextEditorError,- PopupEditor, replaceLinkAtSelection, SnippetDefinition+ type CKEditorError, CKTextEditor, ClassicEditor, getLinkAtSelection, type IconPickerRequest,+ onTextEditorError, PopupEditor, replaceLinkAtSelection, SnippetDefinition} from "@triliumnext/ckeditor5";import { DISPLAYABLE_LOCALE_IDS } from "@triliumnext/commons";-import { HTMLAttributes, RefObject } from "preact";+import { createPortal, HTMLAttributes, RefObject } from "preact";import { useEffect, useImperativeHandle, useRef, useState } from "preact/hooks";import froca from "../../../services/froca";import link from "../../../services/link";+import { isMobile } from "../../../services/utils";import { useKeyboardShortcuts, useLegacyImperativeHandlers, useNoteContext, useSyncedRef, useTriliumOption, useTriliumOptionBool } from "../../react/hooks";+import IconPicker from "../../react/IconPicker";import type { AiNoteLocation } from "./ai_assistant_stream";import { useAiMenuFooter, useAiQuickActions } from "./ai_quick_actions";import { buildConfig, BuildEditorOptions } from "./config";@@ -134,6 +136,20 @@ export default function CKEditor({ containerRef: externalContainerRef, contentLanoteLocationRef.current = note ? { title: note.title, notePath } : null;const noteIdRef = useRef<string | undefined>(undefined);noteIdRef.current = note?.noteId;+ /** The open icon picker request and its balloon container, or `null` when none is open. */+ const [ iconPickerRequest, setIconPickerRequest ] = useState<IconPickerRequest | null>(null);++ // CKEditor creates and positions the balloon; `IconPicker` renders into its container.+ // On mobile, `showIconPickerDialog` opens the picker in a modal instead.+ function showIconPicker(request: IconPickerRequest) {+ if (isMobile()) {+ parentComponent?.triggerCommand("showIconPickerDialog", { onSelect: request.onSelect });+ return null;+ }++ setIconPickerRequest(request);+ return () => setIconPickerRequest(null);+ }useKeyboardShortcuts("text-detail", containerRef, parentComponent, ntxId);@@ -287,7 +303,8 @@ export default function CKEditor({ containerRef: externalContainerRef, contentLagetNoteLocation: () => noteLocationRef.current,getNoteId: () => noteIdRef.current,getComponentId: () => parentComponent?.componentId,- triggerHostCommand: (command) => parentComponent?.triggerCommand(command)+ triggerHostCommand: (command) => parentComponent?.triggerCommand(command),+ showIconPicker});if (isStale) {@@ -409,10 +426,23 @@ export default function CKEditor({ containerRef: externalContainerRef, contentLa}, [ editor, onChange ]);return (- <div ref={containerRef} className={className} tabIndex={tabIndex} />+ <>+ <div ref={containerRef} className={className} tabIndex={tabIndex} />+ {iconPickerRequest && createPortal(+ <IconPicker+ columnCount={ICON_PICKER_COLUMNS}+ compact+ onSelect={iconPickerRequest.onSelect}+ />,+ iconPickerRequest.container+ )}+ </>);}+/** The number of icons per row of the picker in the editor's balloon. */+const ICON_PICKER_COLUMNS = 9;+async function buildEditor(element: HTMLElement, isClassicEditor: boolean, opts: BuildEditorOptions) {const editorClass = isClassicEditor ? ClassicEditor : PopupEditor;const config = await buildConfig(opts);diff --git a/apps/client/src/widgets/type_widgets/text/EditableText.tsx b/apps/client/src/widgets/type_widgets/text/EditableText.tsxindex d11b1f3cd9..43f4994ce6 100644--- a/apps/client/src/widgets/type_widgets/text/EditableText.tsx+++ b/apps/client/src/widgets/type_widgets/text/EditableText.tsx@@ -11,7 +11,6 @@ import {SnippetDefinition} from "@triliumnext/ckeditor5";import { deferred, formatBlockRange, parseBlockRange } from "@triliumnext/commons";-import { createPortal } from "preact";import { useEffect, useRef, useState } from "preact/hooks";import appContext from "../../../components/app_context";@@ -31,12 +30,10 @@ import { getNoteShareLink } from "../../../services/share_link";import toast from "../../../services/toast";import utils, { isMobile } from "../../../services/utils";import type { AddLinkOpts } from "../../dialogs/add_link";-import type { IconPickerOpts } from "../../dialogs/icon_picker";import {useEditorSpacedUpdate, useLegacyImperativeHandlers, useNoteLabel, useSameNoteSwitch,useSearchTermsConsumer, useTriliumEvent, useTriliumOption, useTriliumOptionBool} from "../../react/hooks";-import IconPicker from "../../react/IconPicker";import { setEditorNoteId } from "../../react/NoteStore";import { convertImageToDrawing } from "../canvas/image_to_drawing";import { TypeWidgetProps } from "../type_widget";@@ -87,8 +84,6 @@ export default function EditableText({const stopWatchingEmbedsRef = useRef<(() => void) | undefined>(undefined);const stopTodoCheckboxTapsRef = useRef<(() => void) | undefined>(undefined);const editorApiRef = useRef<CKEditorApi>(null);- /** The open icon picker request and its balloon container, or `null` when none is open. */- const [ iconPickerRequest, setIconPickerRequest ] = useState<IconPickerOpts & { container: HTMLElement } | null>(null);const [ language ] = useNoteLabel(note, "language");const [ textNoteEditorType ] = useTriliumOption("textNoteEditorType");const [ codeBlockWordWrap ] = useTriliumOptionBool("codeBlockWordWrap");@@ -253,17 +248,6 @@ export default function EditableText({editorApi: editorApiRef.current,});},- // CKEditor creates and positions the balloon; `IconPicker` renders into its container.- // On mobile, `showIconPickerDialog` opens the picker in a modal instead.- showIconPicker(request: IconPickerOpts & { container: HTMLElement }) {- if (isMobile()) {- parentComponent?.triggerCommand("showIconPickerDialog", { onSelect: request.onSelect });- return null;- }-- setIconPickerRequest(request);- return () => setIconPickerRequest(null);- },// Keyboard shortcutasync insertDateTimeToTextCommand() {const editor = await waitForEditor();@@ -607,14 +591,6 @@ export default function EditableText({}}/>}- {iconPickerRequest && createPortal(- <IconPicker- columnCount={ICON_PICKER_COLUMNS}- compact- onSelect={iconPickerRequest.onSelect}- />,- iconPickerRequest.container- )}</>);}@@ -730,9 +706,6 @@ function getEditorBlocks(editor: CKTextEditor, block: string) {return range ? formatBlockRange(range) : undefined;}-/** The number of icons per row of the picker in the editor's balloon. */-const ICON_PICKER_COLUMNS = 9;-/*** 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/apps/client/src/widgets/type_widgets/text/config.spec.ts b/apps/client/src/widgets/type_widgets/text/config.spec.tsindex f61fdec4e6..ee020f484e 100644--- a/apps/client/src/widgets/type_widgets/text/config.spec.ts+++ b/apps/client/src/widgets/type_widgets/text/config.spec.ts@@ -407,6 +407,16 @@ describe("CK config - tables", () => {expect(triggerHostCommand).toHaveBeenCalledTimes(callbacks.length);});+ it("shows the icon picker the editor asks for, and none without a host for it", async () => {+ const release = vi.fn();+ const showIconPicker = vi.fn(() => release);+ const request = { container: document.createElement("div"), onSelect: vi.fn() };++ expect((await buildConfig(baseOpts({ showIconPicker }))).inlineIcon?.showPicker(request)).toBe(release);+ expect(showIconPicker).toHaveBeenCalledWith(request);+ expect((await buildConfig(baseOpts())).inlineIcon?.showPicker(request)).toBeNull();+ });+it("titles reference links through the link service", async () => {expect((await buildConfig(baseOpts())).referenceLink).toStrictEqual({getTitle: linkService.getReferenceLinkTitle,diff --git a/apps/client/src/widgets/type_widgets/text/config.ts b/apps/client/src/widgets/type_widgets/text/config.tsindex 6b9acc6e9d..a7edd830c8 100644--- a/apps/client/src/widgets/type_widgets/text/config.ts+++ b/apps/client/src/widgets/type_widgets/text/config.ts@@ -1,4 +1,4 @@-import { type AttachmentUploadHost, type EditorConfig, getCkLocale, type LinkEmbedHost, SnippetDefinition, type TextTransformationConfig } from "@triliumnext/ckeditor5";+import { type AttachmentUploadHost, type EditorConfig, getCkLocale, type IconPickerRequest, type LinkEmbedHost, SnippetDefinition, type TextTransformationConfig } from "@triliumnext/ckeditor5";import emojiDefinitionsUrl from "@triliumnext/ckeditor5/src/emoji_definitions/en.json?url";import { ALLOWED_PROTOCOLS, DISPLAYABLE_LOCALE_IDS, formatShortcut, IMAGE_UPLOAD_SUBTYPES, joinShortcut, KATEX_MACROS, MIME_TYPE_AUTO, normalizeMimeTypeForCKEditor } from "@triliumnext/commons";import i18next from "i18next";@@ -57,6 +57,8 @@ export interface BuildEditorOptions {getComponentId?: () => string | undefined;/** Triggers `command` on the component that hosts the editor. */triggerHostCommand?: (command: CommandNames) => Promise<unknown> | undefined | null;+ /** Shows the icon picker the editor asks for, as `inlineIcon.showPicker` does. */+ showIconPicker?: (request: IconPickerRequest) => (() => void) | null;}export async function buildConfig(opts: BuildEditorOptions): Promise<EditorConfig> {@@ -219,6 +221,7 @@ export async function buildConfig(opts: BuildEditorOptions): Promise<EditorConfiattachmentUpload: buildAttachmentUploadHost(opts.getComponentId),internalLink: { openDialog: bindHostCommand(opts, "addLinkToText") },markdownImport: { open: bindHostCommand(opts, "pasteMarkdownIntoText") },+ inlineIcon: { showPicker: (request) => opts.showIconPicker?.(request) ?? null },cutToNote: {cut: bindHostCommand(opts, "cutIntoNote"),saveNow: bindHostCommand(opts, "saveNoteDetailNow")diff --git a/packages/ckeditor5/src/augmentation.ts b/packages/ckeditor5/src/augmentation.tsindex 69c926a804..82dde980ae 100644--- a/packages/ckeditor5/src/augmentation.ts+++ b/packages/ckeditor5/src/augmentation.ts@@ -20,13 +20,6 @@ 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;- }-/** A button that the content of an embed adds to the toolbar of the embed. */interface ContentEmbedTool {id: string;@@ -90,12 +83,6 @@ declare global {}interface EditorComponent {- /**- * 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, storedTitle?: string): Promise<void>;diff --git a/packages/ckeditor5/src/index.ts b/packages/ckeditor5/src/index.tsindex c193e8883c..8e5a764ba1 100644--- a/packages/ckeditor5/src/index.ts+++ b/packages/ckeditor5/src/index.ts@@ -38,6 +38,7 @@ export type { default as ContextToolbar } from "./plugins/context_toolbar.js";export type { default as MobileToolbarItems } from "./plugins/mobile_toolbar_items.js";export type { LinkEmbedHost } from "./plugins/link_embed/link_embed_commands.js";export type { AttachmentUploadHost } from "./plugins/uploadimage.js";+export type { IconPickerRequest } from "./plugins/inline_icon/inline_icon_ui.js";export type { ColorMenuHost, ColorMenuRequest, ColorMenuTarget } from "./plugins/color_menu.js";export { default as TriliumSnippets } from "./plugins/snippets/snippets.js";export type { SnippetDefinition } from "./plugins/snippets/snippetsconfig.js";diff --git a/packages/ckeditor5/src/plugins/inline_icon/inline_icon.spec.ts b/packages/ckeditor5/src/plugins/inline_icon/inline_icon.spec.tsindex 67d37bd63d..bf4845fa8a 100644--- a/packages/ckeditor5/src/plugins/inline_icon/inline_icon.spec.ts+++ b/packages/ckeditor5/src/plugins/inline_icon/inline_icon.spec.ts@@ -11,7 +11,7 @@ import { installGlobMock } from "../../../test/globals-test-kit.js";import ReferenceLink from "../referencelink.js";import InlineIcon from "./inline_icon.js";import InlineIconEditing from "./inline_icon_editing.js";-import InlineIconUI from "./inline_icon_ui.js";+import InlineIconUI, { type IconPickerRequest } from "./inline_icon_ui.js";describe("InlineIcon", () => {let editor: ClassicEditor;@@ -208,9 +208,8 @@ describe("the balloon InlineIcon picks in", () => {beforeEach(async () => {release = vi.fn();showIconPicker = vi.fn(() => release);- installGlobMock({ getComponentByEl: () => ({ showIconPicker }) });- editor = await createTestEditor([ Paragraph, InlineIcon ]);+ editor = await createTestEditor([ Paragraph, InlineIcon ], { inlineIcon: { showPicker: showIconPicker } });setModelData(editor.model, "<paragraph>[]</paragraph>");});@@ -281,6 +280,15 @@ describe("the balloon InlineIcon picks in", () => {expect(editor.plugins.get(ContextualBalloon).visibleView).toBeNull();});+ it("takes the balloon back down without the inlineIcon config entry", async () => {+ const plainEditor = await createTestEditor([ Paragraph, InlineIcon ]);+ setModelData(plainEditor.model, "<paragraph>[]</paragraph>");++ pressInsertIcon(plainEditor);++ expect(plainEditor.plugins.get(ContextualBalloon).visibleView).toBeNull();+ });+it("lets go of the picker when a click lands outside the balloon", () => {pressInsertIcon(editor);@@ -344,10 +352,8 @@ describe("where the balloon holding the picker ends up", () => {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 ]);+ const editor = await createTestEditor([ Paragraph, InlineIcon ], PAINTING_HOST);getEditorElement(editor).style.cssText = "width: 300px; margin: 200px 0 0 20px;";setModelData(editor.model, "<paragraph>Hello[] there</paragraph>");@@ -415,19 +421,17 @@ function escapeKeyDown() {const PAINTED_PICKER_WIDTH = 260;/** A host that renders something the picker's size into the element the editor passes 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();- }- })- });-}+const PAINTING_HOST = {+ inlineIcon: {+ showPicker({ container }: IconPickerRequest) {+ 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;diff --git a/packages/ckeditor5/src/plugins/inline_icon/inline_icon_ui.ts b/packages/ckeditor5/src/plugins/inline_icon/inline_icon_ui.tsindex 0555543fe3..5a02ac4105 100644--- a/packages/ckeditor5/src/plugins/inline_icon/inline_icon_ui.ts+++ b/packages/ckeditor5/src/plugins/inline_icon/inline_icon_ui.ts@@ -16,7 +16,7 @@ export const CHANGE_ICON = "changeIcon";* The buttons that insert or replace an icon, and the balloon the picking happens in.** The editor positions the balloon and takes it down; the application renders its own picker into- * it through `showIconPicker`, the one place every installed icon pack is searchable. A host with+ * it through `inlineIcon.showPicker`, the one place every installed icon pack is searchable. A host with* no room for a balloon shows the picker its own way and returns nothing to release.*/export default class InlineIconUI extends Plugin {@@ -95,14 +95,14 @@ export default class InlineIconUI extends Plugin {return;}- const release = glob.getComponentByEl<EditorComponent>(editorEl).showIconPicker({+ const release = editor.config.get("inlineIcon")?.showPicker({container,onSelect: (iconClass) => {this._hide();editor.execute(INSERT_ICON_COMMAND, { iconClass });editor.editing.view.focus();}- });+ }) ?? null;if (!release) {this._hide();@@ -231,3 +231,24 @@ function getBalloonPosition(editor: Editor, shownAt: ViewRange) {}};}++/** What the editor asks the host's icon picker for. */+export 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;+}++declare module "ckeditor5" {+ interface EditorConfig {+ inlineIcon?: {+ /**+ * Paints the host's icon picker into `request.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 the container alone and answers `null`.+ */+ showPicker(request: IconPickerRequest): (() => void) | null;+ };+ }+}