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): turn or mirror an inserted icon
Elian Doran9833d7d768ac
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex db8d864d94..5a3bfac526 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -4263,7 +4263,15 @@"working": "Working…","insert-icon": "Insert icon","icon": "Icon",- "insert-an-icon-from-an-installed-icon-pack": "Insert an icon from an installed icon pack"+ "insert-an-icon-from-an-installed-icon-pack": "Insert an icon from an installed icon pack",+ "transform-icon": "Transform icon",+ "icon-toolbar": "Icon toolbar",+ "no-transform": "No transform",+ "rotate-90": "Rotate 90°",+ "rotate-180": "Rotate 180°",+ "rotate-270": "Rotate 270°",+ "flip-horizontally": "Flip horizontally",+ "flip-vertically": "Flip vertically"},"task-state-dropped-title": "Invalid task states","task-state-dropped-message_one": "A custom task state definition is invalid and was ignored.",diff --git a/packages/ckeditor5/src/plugins/inline_icon/inline_icon.ts b/packages/ckeditor5/src/plugins/inline_icon/inline_icon.tsindex 72bcc87b06..02c9eed31a 100644--- a/packages/ckeditor5/src/plugins/inline_icon/inline_icon.ts+++ b/packages/ckeditor5/src/plugins/inline_icon/inline_icon.ts@@ -1,19 +1,20 @@import { Plugin } from "ckeditor5";import InlineIconEditing from "./inline_icon_editing.js";+import InlineIconToolbar from "./inline_icon_toolbar.js";import InlineIconUI from "./inline_icon_ui.js";/*** The icon feature: inserts one icon of an installed icon pack into the text, for writing about the* application's own controls without a screenshot of each one.*- * This is a "glue" plugin which loads the {@link InlineIconEditing} and {@link InlineIconUI}- * plugins.+ * This is a "glue" plugin which loads the {@link InlineIconEditing}, {@link InlineIconUI} and+ * {@link InlineIconToolbar} plugins.*/export default class InlineIcon extends Plugin {public static get requires() {- return [ InlineIconEditing, InlineIconUI ] as const;+ return [ InlineIconEditing, InlineIconUI, InlineIconToolbar ] as const;}public static get pluginName() {@@ -27,5 +28,6 @@ declare module "ckeditor5" {[InlineIcon.pluginName]: InlineIcon;[InlineIconEditing.pluginName]: InlineIconEditing;[InlineIconUI.pluginName]: InlineIconUI;+ [InlineIconToolbar.pluginName]: InlineIconToolbar;}}diff --git a/packages/ckeditor5/src/plugins/inline_icon/inline_icon_editing.ts b/packages/ckeditor5/src/plugins/inline_icon/inline_icon_editing.tsindex 4aecf9d8c8..5c8674bec3 100644--- a/packages/ckeditor5/src/plugins/inline_icon/inline_icon_editing.ts+++ b/packages/ckeditor5/src/plugins/inline_icon/inline_icon_editing.ts@@ -1,9 +1,9 @@import {- Command, ModelElement, type ModelWriter, Plugin, toWidget, type ViewElement, Widget+ Command, type Editor, ModelElement, type ModelWriter, Plugin, toWidget, type ViewElement, Widget} from "ckeditor5";/** The model element an icon is; it draws whatever {@link ICON_CLASS} names. */-const ICON = "inlineIcon";+export const ICON = "inlineIcon";/** The icon pack's own class, such as `bx bx-star`. */const ICON_CLASS = "iconClass";@@ -13,6 +13,27 @@ const MARKER_CLASS = "tn-icon";export const INSERT_ICON_COMMAND = "insertIcon";+export const ICON_TRANSFORM_COMMAND = "iconTransform";++/**+ * The classes that turn or mirror a glyph, which the application already writes by hand — the right+ * pane's icon is `bx bx-sidebar bx-flip-horizontal`. Boxicons names them, but the rules are not+ * scoped to a pack, so they apply to any icon.+ *+ * Each sets `transform`, so two never combine: whichever the stylesheet declares last wins. An icon+ * therefore carries one of these or none, which is why {@link IconTransformCommand} holds a value+ * rather than five independent flags.+ */+export const ICON_TRANSFORMS = [+ "bx-rotate-90",+ "bx-rotate-180",+ "bx-rotate-270",+ "bx-flip-horizontal",+ "bx-flip-vertical"+] as const;++export type IconTransform = typeof ICON_TRANSFORMS[number];+/*** The icon editing feature: an inline widget that stands for one icon of one installed icon pack,* written as `<span class="tn-icon bx bx-star"></span>` — the form icons take everywhere else in@@ -62,15 +83,26 @@ export default class InlineIconEditing extends Plugin {});editor.conversion.for("editingDowncast").elementToElement({- model: ICON,- view: (modelElement, { writer }) => toWidget(- writer.createContainerElement("span", { class: viewClasses(modelElement) }),- writer,- { label: editor.t("Icon") }- )+ // Naming the attribute is what converts the element again when it changes, which is how+ // a transform applied through the toolbar reaches the view.+ model: { name: ICON, attributes: [ ICON_CLASS ] },+ view: (modelElement, { writer }) => {+ const widget = toWidget(+ writer.createContainerElement("span", { class: viewClasses(modelElement) }),+ writer,+ { label: editor.t("Icon") }+ );++ // What InlineIconToolbar recognizes an icon by, since the widget's own element+ // carries only the pack's classes.+ writer.setCustomProperty(ICON, true, widget);++ return widget;+ }});editor.commands.add(INSERT_ICON_COMMAND, new InsertIconCommand(editor));+ editor.commands.add(ICON_TRANSFORM_COMMAND, new IconTransformCommand(editor));}}@@ -106,6 +138,42 @@ class InsertIconCommand extends Command {}+/**+ * Turns or mirrors the selected icon by rewriting the transform among its classes, of which+ * {@link ICON_TRANSFORMS} explains there is at most one. `null` takes the icon back to upright.+ */+class IconTransformCommand extends Command {++ declare public value: IconTransform | null;++ override refresh() {+ const icon = selectedIcon(this.editor);++ this.value = icon ? readTransform(icon) : null;+ this.isEnabled = !this.editor.isReadOnly && !!icon;+ }++ override execute({ transform }: { transform: IconTransform | null }) {+ const icon = selectedIcon(this.editor);++ /* v8 ignore next 3 -- the command is enabled only while an icon is selected */+ if (!icon) {+ return;+ }++ const classNames = readClasses(icon).filter((className) => !isTransform(className));++ if (transform) {+ classNames.push(transform);+ }++ this.editor.model.change((writer: ModelWriter) => {+ writer.setAttribute(ICON_CLASS, classNames.join(" "), icon);+ });+ }++}+/** The pack's classes, which is everything the element wears apart from {@link MARKER_CLASS}. */function readIconClass(viewElement: ViewElement) {return Array.from(viewElement.getClassNames())@@ -119,3 +187,23 @@ function viewClasses(modelElement: ModelElement) {return iconClass ? `${MARKER_CLASS} ${iconClass}` : MARKER_CLASS;}++/** The icon the selection is on, which is the only one a transform applies to. */+function selectedIcon(editor: Editor) {+ const selected = editor.model.document.selection.getSelectedElement();++ return selected?.is("element", ICON) ? selected : null;+}++/** The transform an icon carries, or `null` where it is upright. */+function readTransform(icon: ModelElement): IconTransform | null {+ return readClasses(icon).find(isTransform) ?? null;+}++function isTransform(className: string): className is IconTransform {+ return (ICON_TRANSFORMS as readonly string[]).includes(className);+}++function readClasses(icon: ModelElement) {+ return String(icon.getAttribute(ICON_CLASS) ?? "").split(/\s+/).filter(Boolean);+}diff --git a/packages/ckeditor5/src/plugins/inline_icon/inline_icon_toolbar.spec.ts b/packages/ckeditor5/src/plugins/inline_icon/inline_icon_toolbar.spec.tsnew file mode 100644index 0000000000..1f4716bd77--- /dev/null+++ b/packages/ckeditor5/src/plugins/inline_icon/inline_icon_toolbar.spec.ts@@ -0,0 +1,156 @@+import {+ _getViewData as getViewData, _setModelData as setModelData, type ButtonView, type ClassicEditor,+ type DropdownView, ListItemView, Paragraph, type ViewDocumentSelection, type ViewElement,+ WidgetToolbarRepository+} from "ckeditor5";+import { beforeEach, describe, expect, it, vi } from "vitest";++import { createTestEditor } from "../../../test/editor-kit.js";+import InlineIcon from "./inline_icon.js";+import InlineIconToolbar from "./inline_icon_toolbar.js";++/** The shape of the repository's private register, which is where a definition can be read back. */+interface ToolbarDefinitions {+ _toolbarDefinitions: Map<string, {+ itemsConfig: string[];+ getRelatedElement: (selection: ViewDocumentSelection) => ViewElement | null;+ }>;+}++describe("InlineIconToolbar", () => {+ let editor: ClassicEditor;++ beforeEach(async () => {+ editor = await createTestEditor([ Paragraph, InlineIcon ]);+ });++ /** Puts one icon in the text and selects it, which is what the toolbar answers to. */+ function selectIcon(iconClass: string) {+ setModelData(+ editor.model,+ `<paragraph>Press [<inlineIcon iconClass="${iconClass}"></inlineIcon>]</paragraph>`+ );+ }++ /** What the note holds for that icon, which is where a transform ends up. */+ function storedIcon(iconClass: string) {+ return `<p>Press <span class="tn-icon ${iconClass}"></span></p>`;+ }++ function toolbarDefinition() {+ const repository = editor.plugins+ .get(WidgetToolbarRepository) as unknown as ToolbarDefinitions;++ return repository._toolbarDefinitions.get("inlineIcon");+ }++ /** The dropdown as the toolbar builds it, opened so that its list exists. */+ function openTransformDropdown() {+ const dropdown = editor.ui.componentFactory.create("iconTransform") as DropdownView;++ dropdown.render();+ dropdown.isOpen = true;++ return dropdown;+ }++ /** The list's buttons, which carry the labels and the mark on the transform in force. */+ function transformButtons(dropdown: DropdownView) {+ return Array.from(dropdown.listView?.items ?? [])+ .filter((item): item is ListItemView => item instanceof ListItemView)+ .map((item) => item.children.first as ButtonView);+ }++ it("loads beside the editing and UI parts", () => {+ expect(editor.plugins.get(InlineIconToolbar)).toBeInstanceOf(InlineIconToolbar);+ expect(InlineIconToolbar.pluginName).toBe("InlineIconToolbar");+ expect(InlineIconToolbar.requires).toContain(WidgetToolbarRepository);+ });++ it("registers one toolbar, and claims a selected icon but nothing else", () => {+ const definition = toolbarDefinition();+ const selection = editor.editing.view.document.selection;++ expect(definition?.itemsConfig).toEqual([ "iconTransform" ]);++ selectIcon("bx bx-cog");+ expect(definition?.getRelatedElement(selection)?.hasClass("tn-icon")).toBe(true);++ setModelData(editor.model, "<paragraph>[Press] it</paragraph>");+ expect(definition?.getRelatedElement(selection)).toBeNull();+ });++ it("reports the transform the selected icon carries, and applies only to one", () => {+ const command = editor.commands.get("iconTransform");++ selectIcon("bx bx-cog");+ expect({ value: command?.value, isEnabled: command?.isEnabled })+ .toEqual({ value: null, isEnabled: true });++ selectIcon("bx bx-sidebar bx-flip-horizontal");+ expect(command?.value).toBe("bx-flip-horizontal");++ setModelData(editor.model, "<paragraph>[Press] it</paragraph>");+ expect({ value: command?.value, isEnabled: command?.isEnabled })+ .toEqual({ value: null, isEnabled: false });++ selectIcon("bx bx-cog");+ editor.enableReadOnlyMode("spec");+ expect(command?.isEnabled).toBe(false);+ });++ it("sets, replaces and clears the transform, keeping the pack's own classes", () => {+ selectIcon("bx bx-sidebar");++ editor.execute("iconTransform", { transform: "bx-flip-horizontal" });+ expect(editor.getData()).toBe(storedIcon("bx bx-sidebar bx-flip-horizontal"));++ // One transform replaces another rather than joining it: the two would fight over+ // `transform` in the stylesheet.+ editor.execute("iconTransform", { transform: "bx-rotate-90" });+ expect(editor.getData()).toBe(storedIcon("bx bx-sidebar bx-rotate-90"));++ editor.execute("iconTransform", { transform: null });+ expect(editor.getData()).toBe(storedIcon("bx bx-sidebar"));+ });++ it("redraws the icon being edited, which a plain downcast would not", () => {+ selectIcon("bx bx-sidebar");++ editor.execute("iconTransform", { transform: "bx-flip-vertical" });++ expect(getViewData(editor.editing.view, { withoutSelection: true }))+ .toContain("bx-flip-vertical");+ });++ it("offers upright and every transform, marking the one in force", () => {+ selectIcon("bx bx-sidebar bx-rotate-180");++ const buttons = transformButtons(openTransformDropdown());++ expect(buttons.map((button) => button.label)).toEqual([+ "No transform", "Rotate 90°", "Rotate 180°", "Rotate 270°",+ "Flip horizontally", "Flip vertically"+ ]);+ expect(buttons.filter((button) => button.isOn).map((button) => button.label))+ .toEqual([ "Rotate 180°" ]);+ });++ it("transforms the icon from the list and hands focus back to the text", () => {+ selectIcon("bx bx-sidebar");+ const focus = vi.spyOn(editor.editing.view, "focus");++ const buttons = transformButtons(openTransformDropdown());+ buttons.find((button) => button.label === "Flip horizontally")?.fire("execute");++ expect(editor.getData()).toBe(storedIcon("bx bx-sidebar bx-flip-horizontal"));+ expect(focus).toHaveBeenCalled();+ });++ it("disables the dropdown where no icon is selected", () => {+ setModelData(editor.model, "<paragraph>[]Press it</paragraph>");++ expect(openTransformDropdown().isEnabled).toBe(false);+ });++});diff --git a/packages/ckeditor5/src/plugins/inline_icon/inline_icon_toolbar.ts b/packages/ckeditor5/src/plugins/inline_icon/inline_icon_toolbar.tsnew file mode 100644index 0000000000..02915977ff--- /dev/null+++ b/packages/ckeditor5/src/plugins/inline_icon/inline_icon_toolbar.ts@@ -0,0 +1,120 @@+import bxReflectHorizontal from "boxicons/svg/regular/bx-reflect-horizontal.svg?raw";+import {+ addListToDropdown, Collection, type Command, createDropdown,+ type ListDropdownItemDefinition, type LocaleTranslate, Plugin, UIModel, WidgetToolbarRepository+} from "ckeditor5";++import InlineIconEditing, {+ ICON, ICON_TRANSFORM_COMMAND, ICON_TRANSFORMS, type IconTransform+} from "./inline_icon_editing.js";++/**+ * The balloon shown over a selected icon, and the one control it holds.+ *+ * `WidgetToolbarRepository` owns the balloon — where it points, when it appears and when it goes+ * away — so this plugin only names the items and says which view element they belong to.+ */+export default class InlineIconToolbar extends Plugin {++ public static get pluginName() {+ return "InlineIconToolbar" as const;+ }++ public static get requires() {+ return [ WidgetToolbarRepository, InlineIconEditing ] as const;+ }++ init() {+ const editor = this.editor;+ const t = editor.t;++ editor.ui.componentFactory.add(ICON_TRANSFORM_COMMAND, (locale) => {+ // Always registered: InlineIconEditing is loaded before this plugin.+ const command = editor.commands.get(ICON_TRANSFORM_COMMAND) as Command;+ const dropdown = createDropdown(locale);++ dropdown.buttonView.set({+ label: t("Transform icon"),+ icon: bxReflectHorizontal,+ tooltip: true+ });++ dropdown.bind("isEnabled").to(command, "isEnabled");++ this.listenTo(dropdown, "execute", (evt) => {+ // The list delegates its buttons' `execute` here, so the source is an item's model.+ const { _iconTransform: transform } = evt.source as TransformItemModel;++ editor.execute(ICON_TRANSFORM_COMMAND, { transform });+ editor.editing.view.focus();+ });++ addListToDropdown(dropdown, transformItems(command, t), {+ ariaLabel: t("Transform icon")+ });++ return dropdown;+ });+ }++ afterInit() {+ this.editor.plugins.get(WidgetToolbarRepository).register(ICON, {+ ariaLabel: this.editor.t("Icon toolbar"),+ items: [ ICON_TRANSFORM_COMMAND ],+ getRelatedElement: (selection) => {+ const viewElement = selection.getSelectedElement();++ return viewElement?.getCustomProperty(ICON) ? viewElement : null;+ }+ });+ }++}++/** A list item's model, which carries the transform its button stands for. */+interface TransformItemModel {+ _iconTransform: IconTransform | null;+}++/** What the dropdown offers: upright, then each transform {@link ICON_TRANSFORMS} names. */+function transformItems(command: Command, t: LocaleTranslate) {+ const labels: Record<IconTransform, string> = {+ "bx-rotate-90": t("Rotate 90°"),+ "bx-rotate-180": t("Rotate 180°"),+ "bx-rotate-270": t("Rotate 270°"),+ "bx-flip-horizontal": t("Flip horizontally"),+ "bx-flip-vertical": t("Flip vertically")+ };++ const items = new Collection<ListDropdownItemDefinition>();++ items.add(transformItem(command, null, t("No transform")));+ items.add({ type: "separator" });++ for (const transform of ICON_TRANSFORMS) {+ items.add(transformItem(command, transform, labels[transform]));+ }++ return items;+}++/**+ * One choice, marked while the selected icon carries it. They are radio items rather than+ * checkboxes because the transforms exclude one another (see {@link ICON_TRANSFORMS}).+ */+function transformItem(+ command: Command,+ transform: IconTransform | null,+ label: string+): ListDropdownItemDefinition {+ const model = new UIModel({+ _iconTransform: transform,+ label,+ role: "menuitemradio",+ withText: true+ });++ model.bind("isOn").to(command, "value", (value) => value === transform);++ return { type: "button", model };+}