Skip to content

Build your personal knowledge base with Trilium Notes

feat(ckeditor): GPL format painter, replacing premium FormatPainter

Elian Doran1293212e386a
diff --git a/packages/ckeditor5/src/plugins.spec.ts b/packages/ckeditor5/src/plugins.spec.ts
index 0b95befa76..2d42ea99e1 100644
--- a/packages/ckeditor5/src/plugins.spec.ts
+++ b/packages/ckeditor5/src/plugins.spec.ts
@@ -5,6 +5,7 @@ import { Admonition } from "@triliumnext/ckeditor5-admonition";
import { COMMON_PLUGINS, CORE_PLUGINS, loadPremiumPlugins, POPUP_EDITOR_PLUGINS } from "./plugins.js";
import CutToNotePlugin from "./plugins/cuttonote.js";
import Uploadfileplugin from "./plugins/file_upload/uploadfileplugin.js";
+import TriliumFormatPainter from "./plugins/format_painter/format_painter.js";
import IncludeNote from "./plugins/includenote.js";
import InternalLinkPlugin from "./plugins/internallink.js";
import LinkEmbed from "./plugins/link_embed/link_embed.js";
@@ -73,6 +74,7 @@ describe("plugin lists", () => {
expect(COMMON_PLUGINS).toContain(IncludeNote);
expect(COMMON_PLUGINS).toContain(LinkEmbed);
expect(COMMON_PLUGINS).toContain(Uploadfileplugin);
+ expect(COMMON_PLUGINS).toContain(TriliumFormatPainter);
});
it("COMMON_PLUGINS includes the external widget plugins", () => {
@@ -95,14 +97,16 @@ describe("loadPremiumPlugins", () => {
}
});
- it("includes Template and FormatPainter, but not SlashCommand", async () => {
+ it("includes Template, but not SlashCommand or FormatPainter", async () => {
const { SlashCommand, Template, FormatPainter } = await import("ckeditor5-premium-features");
const plugins = await loadPremiumPlugins();
expect(plugins).toContain(Template);
- expect(plugins).toContain(FormatPainter);
// `SlashCommand` requires the `Mention` façade, which would load upstream's `MentionUI`
// alongside `TriliumMentionUI`; `TriliumSlashCommands` provides `/` instead.
expect(plugins).not.toContain(SlashCommand);
+
+ // `FormatPainter` is replaced by the GPL `TriliumFormatPainter`.
+ expect(plugins).not.toContain(FormatPainter);
});
});
diff --git a/packages/ckeditor5/src/plugins.ts b/packages/ckeditor5/src/plugins.ts
index 135a073d95..b568bfc767 100644
--- a/packages/ckeditor5/src/plugins.ts
+++ b/packages/ckeditor5/src/plugins.ts
@@ -16,6 +16,7 @@ import MentionCustomization from "./plugins/mention_customization.js";
import TriliumEmojiMention from "./plugins/mention/emoji_mention.js";
import TriliumMentionUI from "./plugins/mention/trilium_mention_ui.js";
import TriliumSlashCommands from "./plugins/mention/slash_commands.js";
+import TriliumFormatPainter from "./plugins/format_painter/format_painter.js";
import IncludeNote from "./plugins/includenote.js";
import LinkEmbed from "./plugins/link_embed/link_embed.js";
import Uploadfileplugin from "./plugins/file_upload/uploadfileplugin.js";
@@ -144,10 +145,13 @@ export async function loadPremiumPlugins(): Promise<(typeof Plugin)[]> {
// `SlashCommand` is deliberately not among them: it `requires` the `Mention` façade, which loads
// upstream's `MentionUI` next to `TriliumMentionUI` and leaves the two fighting over the same
// balloon. `TriliumSlashCommands` provides `/` instead, for premium and GPL builds alike.
- const { Template, FormatPainter } = await import('ckeditor5-premium-features');
+ //
+ // `FormatPainter` is likewise gone: the GPL `TriliumFormatPainter` (built on the public
+ // `isFormatting` schema flag) replaces it, so only `Template` still needs the premium licence.
+ const { Template } = await import('ckeditor5-premium-features');
// Also load the CSS when premium features are used
await import('ckeditor5-premium-features/ckeditor5-premium-features.css');
- return [Template, FormatPainter];
+ return [Template];
}
/**
@@ -217,6 +221,10 @@ export const COMMON_PLUGINS: typeof Plugin[] = [
TriliumEmojiMention,
TriliumSlashCommands,
+ // GPL reimplementation of premium `FormatPainter` (the `formatPainter` toolbar button), built on
+ // the public `isFormatting` schema flag, so the commercial plugin can be dropped.
+ TriliumFormatPainter,
+
...TRILIUM_PLUGINS,
...EXTERNAL_PLUGINS
];
diff --git a/packages/ckeditor5/src/plugins/format_painter/constants.ts b/packages/ckeditor5/src/plugins/format_painter/constants.ts
new file mode 100644
index 0000000000..c0e053b851
--- /dev/null
+++ b/packages/ckeditor5/src/plugins/format_painter/constants.ts
@@ -0,0 +1,20 @@
+/**
+ * Shared identifiers for the format painter, kept in their own module so the editing and UI plugins
+ * can both reference them without importing each other (which would cycle through the glue plugin).
+ *
+ * The command, component and CSS-class names are deliberately the ones premium `FormatPainter` used,
+ * so the toolbar entry (`formatPainter`) and any existing overrides keyed on `ck-format-painter-active`
+ * keep working unchanged — the same drop-in approach taken for the `/` palette.
+ */
+
+/** Reads the formatting of the current selection and stores it. */
+export const COPY_FORMAT_COMMAND = "copyFormat";
+
+/** Applies previously copied formatting to the current selection. */
+export const PASTE_FORMAT_COMMAND = "pasteFormat";
+
+/** The `componentFactory` name the toolbar references. */
+export const FORMAT_PAINTER_COMPONENT = "formatPainter";
+
+/** Set on the editing roots while the painter is armed, so the cursor signals it. */
+export const CURSOR_ACTIVE_CSS_CLASS = "ck-format-painter-active";
diff --git a/packages/ckeditor5/src/plugins/format_painter/format_painter.spec.ts b/packages/ckeditor5/src/plugins/format_painter/format_painter.spec.ts
new file mode 100644
index 0000000000..ca08a66044
--- /dev/null
+++ b/packages/ckeditor5/src/plugins/format_painter/format_painter.spec.ts
@@ -0,0 +1,27 @@
+import { Bold, type ClassicEditor, Essentials, Paragraph } from "ckeditor5";
+import { beforeEach, describe, expect, it } from "vitest";
+
+import { createTestEditor } from "../../../test/editor-kit.js";
+import { COPY_FORMAT_COMMAND, FORMAT_PAINTER_COMPONENT, PASTE_FORMAT_COMMAND } from "./constants.js";
+import TriliumFormatPainter from "./format_painter.js";
+import FormatPainterEditing from "./format_painter_editing.js";
+import FormatPainterUI from "./format_painter_ui.js";
+
+describe("TriliumFormatPainter", () => {
+ let editor: ClassicEditor;
+
+ beforeEach(async () => {
+ editor = await createTestEditor([ Essentials, Paragraph, Bold, TriliumFormatPainter ]);
+ });
+
+ it("pulls in the editing and UI halves", () => {
+ expect(TriliumFormatPainter.pluginName).toBe("TriliumFormatPainter");
+ expect(TriliumFormatPainter.requires).toEqual([ FormatPainterEditing, FormatPainterUI ]);
+ });
+
+ it("wires up the commands and the toolbar component", () => {
+ expect(editor.commands.get(COPY_FORMAT_COMMAND)).toBeTruthy();
+ expect(editor.commands.get(PASTE_FORMAT_COMMAND)).toBeTruthy();
+ expect(editor.ui.componentFactory.has(FORMAT_PAINTER_COMPONENT)).toBe(true);
+ });
+});
diff --git a/packages/ckeditor5/src/plugins/format_painter/format_painter.ts b/packages/ckeditor5/src/plugins/format_painter/format_painter.ts
new file mode 100644
index 0000000000..cf0cc140b5
--- /dev/null
+++ b/packages/ckeditor5/src/plugins/format_painter/format_painter.ts
@@ -0,0 +1,24 @@
+import { Plugin } from "ckeditor5";
+
+import FormatPainterEditing from "./format_painter_editing.js";
+import FormatPainterUI from "./format_painter_ui.js";
+
+/**
+ * The format painter — "copy this text's formatting onto that text".
+ *
+ * A GPL reimplementation of premium `FormatPainter`, built entirely on public CKEditor API (the
+ * `isFormatting` schema flag, `Command`, `ButtonView`) so the commercial plugin — the last one still
+ * pulling in the premium licence — can be dropped. Split, as premium was, into an editing half
+ * ({@link FormatPainterEditing}: the `copyFormat`/`pasteFormat` commands) and a UI half
+ * ({@link FormatPainterUI}: the `formatPainter` button and its one-shot painting).
+ */
+export default class TriliumFormatPainter extends Plugin {
+
+ static get requires() {
+ return [ FormatPainterEditing, FormatPainterUI ];
+ }
+
+ static get pluginName() {
+ return "TriliumFormatPainter" as const;
+ }
+}
diff --git a/packages/ckeditor5/src/plugins/format_painter/format_painter_editing.spec.ts b/packages/ckeditor5/src/plugins/format_painter/format_painter_editing.spec.ts
new file mode 100644
index 0000000000..30cb318856
--- /dev/null
+++ b/packages/ckeditor5/src/plugins/format_painter/format_painter_editing.spec.ts
@@ -0,0 +1,190 @@
+import {
+ Bold,
+ type ClassicEditor,
+ Essentials,
+ _getModelData as getModelData,
+ Heading,
+ HorizontalLine,
+ Italic,
+ Paragraph,
+ _setModelData as setModelData,
+ Underline
+} from "ckeditor5";
+import { beforeEach, describe, expect, it } from "vitest";
+
+import { createTestEditor } from "../../../test/editor-kit.js";
+import { COPY_FORMAT_COMMAND, PASTE_FORMAT_COMMAND } from "./constants.js";
+import FormatPainterEditing, { type CopyFormatCommand, type FormattingAttributes, type PasteFormatCommand } from "./format_painter_editing.js";
+
+describe("FormatPainterEditing", () => {
+ let editor: ClassicEditor;
+
+ async function createEditor() {
+ editor = await createTestEditor([ Essentials, Paragraph, Bold, Italic, Underline, Heading, HorizontalLine, FormatPainterEditing ]);
+ // A registered-but-not-formatting attribute, to prove the commands key off `isFormatting`
+ // rather than "any attribute present".
+ editor.model.schema.extend("$text", { allowAttributes: "marker" });
+ }
+
+ function copyCommand() {
+ const command = editor.commands.get(COPY_FORMAT_COMMAND) as CopyFormatCommand | undefined;
+ if (!command) {
+ throw new Error("copyFormat command was not registered");
+ }
+ return command;
+ }
+
+ function pasteCommand() {
+ const command = editor.commands.get(PASTE_FORMAT_COMMAND) as PasteFormatCommand | undefined;
+ if (!command) {
+ throw new Error("pasteFormat command was not registered");
+ }
+ return command;
+ }
+
+ function model() {
+ return getModelData(editor.model, { withoutSelection: true });
+ }
+
+ beforeEach(async () => {
+ await createEditor();
+ });
+
+ it("registers both commands", () => {
+ expect(FormatPainterEditing.pluginName).toBe("FormatPainterEditing");
+ expect(copyCommand()).toBeTruthy();
+ expect(pasteCommand()).toBeTruthy();
+ });
+
+ describe("copyFormat", () => {
+ it("reads the formatting of a ranged selection's first text node, ignoring non-formatting attributes", () => {
+ setModelData(editor.model, "<paragraph>[<$text bold=\"true\" marker=\"x\">foo</$text>]</paragraph>");
+
+ copyCommand().execute();
+
+ // `bold` is a formatting attribute; `marker` is registered but not, so it is dropped.
+ expect(copyCommand().value).toEqual({ bold: true });
+ });
+
+ it("reads the caret's selection attributes when collapsed", () => {
+ setModelData(editor.model, "<paragraph>foo[]</paragraph>");
+ editor.model.change((writer) => writer.setSelectionAttribute("italic", true));
+
+ copyCommand().execute();
+
+ expect(copyCommand().value).toEqual({ italic: true });
+ });
+
+ it("stores an empty set when there is no formatting to copy", () => {
+ setModelData(editor.model, "<paragraph>[foo]</paragraph>");
+
+ copyCommand().execute();
+
+ expect(copyCommand().value).toEqual({});
+ });
+
+ it("stores an empty set for a ranged selection that holds no text", () => {
+ // Ranged, but wrapping only an inline element (a line break) — `getItems()` yields the
+ // element, never a text node, yet the caret still sits where text is allowed (enabled).
+ setModelData(editor.model, "<paragraph>[<softBreak></softBreak>]</paragraph>");
+
+ copyCommand().execute();
+
+ expect(copyCommand().value).toEqual({});
+ });
+
+ it("forgets the stored formatting on reset()", () => {
+ setModelData(editor.model, "<paragraph>[<$text bold=\"true\">foo</$text>]</paragraph>");
+ copyCommand().execute();
+ expect(copyCommand().value).toEqual({ bold: true });
+
+ copyCommand().reset();
+ expect(copyCommand().value).toBeUndefined();
+ });
+
+ it("is enabled inside text content and disabled where text is not allowed", () => {
+ setModelData(editor.model, "<paragraph>foo[]</paragraph>");
+ copyCommand().refresh();
+ expect(copyCommand().isEnabled).toBe(true);
+
+ // A selected block object (a horizontal line) is not a place `$text` may go.
+ setModelData(editor.model, "[<horizontalLine></horizontalLine>]");
+ copyCommand().refresh();
+ expect(copyCommand().isEnabled).toBe(false);
+ });
+ });
+
+ describe("pasteFormat", () => {
+ it("replaces the target's formatting with the stored set over a range", () => {
+ setModelData(editor.model, "<paragraph>[<$text bold=\"true\">foo</$text>]</paragraph>");
+ copyCommand().execute();
+
+ // Target already has different formatting; it must be gone afterwards.
+ setModelData(editor.model, "<paragraph>[<$text italic=\"true\">bar</$text>]</paragraph>");
+ pasteCommand().execute();
+
+ const data = model();
+ expect(data).toContain("bold=\"true\"");
+ expect(data).not.toContain("italic");
+ });
+
+ it("keeps a target's non-formatting attribute while replacing its formatting", () => {
+ copyCommand().value = { bold: true };
+
+ setModelData(editor.model, "<paragraph>[<$text italic=\"true\" marker=\"x\">bar</$text>]</paragraph>");
+ pasteCommand().execute();
+
+ const data = model();
+ expect(data).toContain("bold=\"true\"");
+ expect(data).toContain("marker=\"x\"");
+ expect(data).not.toContain("italic");
+ });
+
+ it("applies stored formatting as selection attributes at a collapsed caret, clearing existing ones", () => {
+ copyCommand().value = { bold: true };
+
+ setModelData(editor.model, "<paragraph>foo[]</paragraph>");
+ editor.model.change((writer) => {
+ writer.setSelectionAttribute("italic", true);
+ writer.setSelectionAttribute("marker", "x");
+ });
+
+ pasteCommand().execute();
+
+ const attributes = [ ...editor.model.document.selection.getAttributeKeys() ].sort();
+ // Formatting `italic` is cleared, `bold` applied; the non-formatting `marker` is untouched.
+ expect(attributes).toEqual([ "bold", "marker" ]);
+ });
+
+ it("spans multiple blocks, skipping the element boundaries between them", () => {
+ copyCommand().value = { bold: true };
+
+ setModelData(editor.model, "<paragraph>[foo</paragraph><paragraph>bar]</paragraph>");
+ pasteCommand().execute();
+
+ const data = model();
+ expect(data).toContain("<paragraph><$text bold=\"true\">foo</$text></paragraph>");
+ expect(data).toContain("<paragraph><$text bold=\"true\">bar</$text></paragraph>");
+ });
+
+ it("prefers an explicit argument over the stored value", () => {
+ copyCommand().value = { bold: true };
+
+ setModelData(editor.model, "<paragraph>[bar]</paragraph>");
+ pasteCommand().execute({ italic: true } satisfies FormattingAttributes);
+
+ const data = model();
+ expect(data).toContain("italic=\"true\"");
+ expect(data).not.toContain("bold");
+ });
+
+ it("does nothing when neither an argument nor a stored value is available", () => {
+ setModelData(editor.model, "<paragraph>[bar]</paragraph>");
+ const before = model();
+
+ pasteCommand().execute();
+
+ expect(model()).toBe(before);
+ });
+ });
+});
diff --git a/packages/ckeditor5/src/plugins/format_painter/format_painter_editing.ts b/packages/ckeditor5/src/plugins/format_painter/format_painter_editing.ts
new file mode 100644
index 0000000000..34a33f8342
--- /dev/null
+++ b/packages/ckeditor5/src/plugins/format_painter/format_painter_editing.ts
@@ -0,0 +1,180 @@
+import { Command, type Editor, Plugin } from "ckeditor5";
+
+import { COPY_FORMAT_COMMAND, PASTE_FORMAT_COMMAND } from "./constants.js";
+
+/** An attribute-name → value map of the model's *formatting* attributes (bold, fontColor, …). */
+export type FormattingAttributes = Record<string, unknown>;
+
+/**
+ * Registers the two commands the format painter is built on:
+ *
+ * - `copyFormat` reads the formatting attributes of the current selection and stores them,
+ * - `pasteFormat` clears the target selection's formatting and applies the stored set.
+ *
+ * "Formatting attribute" is not guessed: an attribute counts when the schema marks it
+ * `isFormatting` — the same public signal `RemoveFormat` uses — so this automatically tracks every
+ * inline mark the editor registers, including Trilium's own (`kbd`, reference links).
+ *
+ * This mirrors the split premium `FormatPainter` uses (`FormatPainterEditing` + `CopyFormatCommand`
+ * + `PasteFormatCommand`), reimplemented on public API so the premium plugin — the last one still
+ * forcing the commercial licence — can be dropped.
+ */
+export default class FormatPainterEditing extends Plugin {
+
+ static get pluginName() {
+ return "FormatPainterEditing" as const;
+ }
+
+ init() {
+ const editor = this.editor;
+ const copyCommand = new CopyFormatCommand(editor);
+
+ editor.commands.add(COPY_FORMAT_COMMAND, copyCommand);
+ // Paste reads from the copy command directly, rather than looking it up by name, so it has no
+ // "command missing" path to guard — the two are always created together, here.
+ editor.commands.add(PASTE_FORMAT_COMMAND, new PasteFormatCommand(editor, copyCommand));
+ }
+}
+
+/**
+ * Copies the formatting of the current selection into {@link #value}, from where `pasteFormat` (or a
+ * direct `pasteFormat` argument) reads it. `reset()` forgets it again.
+ */
+export class CopyFormatCommand extends Command {
+
+ override value: FormattingAttributes | undefined = undefined;
+
+ override refresh() {
+ this.isEnabled = selectionAllowsText(this.editor);
+ }
+
+ override execute() {
+ this.value = readFormatting(this.editor);
+ }
+
+ reset() {
+ this.value = undefined;
+ }
+}
+
+/**
+ * Applies formatting to the current selection: the argument if given, otherwise whatever
+ * `copyFormat` last stored. Existing formatting on the target is cleared first, so the paste
+ * *replaces* rather than *merges* — matching the premium behaviour and what "copy this format onto
+ * that" implies.
+ */
+export class PasteFormatCommand extends Command {
+
+ constructor(editor: Editor, private readonly _source: CopyFormatCommand) {
+ super(editor);
+ }
+
+ override refresh() {
+ this.isEnabled = selectionAllowsText(this.editor);
+ }
+
+ override execute(formatting?: FormattingAttributes) {
+ const toApply = formatting ?? this._source.value;
+
+ if (!toApply) {
+ return;
+ }
+
+ applyFormatting(this.editor, toApply);
+ }
+}
+
+/** Whether text — and therefore inline formatting — is allowed where the selection sits. */
+function selectionAllowsText(editor: Editor): boolean {
+ const position = editor.model.document.selection.getFirstPosition();
+
+ /* v8 ignore next 3 -- a live document selection always has a first position; the guard only narrows the type */
+ if (!position) {
+ return false;
+ }
+
+ return editor.model.schema.checkChild(position, "$text");
+}
+
+/**
+ * The formatting attributes of the current selection. For a collapsed caret these are the selection
+ * attributes (the formatting the next character would take); for a range they are read from its
+ * first text node, matching how the source formatting is "the format at the start of the selection".
+ */
+function readFormatting(editor: Editor): FormattingAttributes {
+ const schema = editor.model.schema;
+ const result: FormattingAttributes = {};
+
+ for (const [ name, value ] of formattingSource(editor)) {
+ if (schema.getAttributeProperties(name).isFormatting) {
+ result[name] = value;
+ }
+ }
+
+ return result;
+}
+
+function formattingSource(editor: Editor): Iterable<[string, unknown]> {
+ const selection = editor.model.document.selection;
+
+ if (selection.isCollapsed) {
+ return selection.getAttributes();
+ }
+
+ for (const range of selection.getRanges()) {
+ for (const item of range.getItems()) {
+ if (item.is("$textProxy")) {
+ return item.getAttributes();
+ }
+ }
+ }
+
+ // A ranged selection over objects only (e.g. an image) carries no text to read formatting from.
+ return selection.getAttributes();
+}
+
+function applyFormatting(editor: Editor, formatting: FormattingAttributes): void {
+ const model = editor.model;
+ const schema = model.schema;
+ const selection = model.document.selection;
+
+ model.change((writer) => {
+ if (selection.isCollapsed) {
+ for (const name of [ ...selection.getAttributeKeys() ]) {
+ if (schema.getAttributeProperties(name).isFormatting) {
+ writer.removeSelectionAttribute(name);
+ }
+ }
+
+ for (const [ name, value ] of Object.entries(formatting)) {
+ writer.setSelectionAttribute(name, value);
+ }
+
+ return;
+ }
+
+ for (const range of [ ...selection.getRanges() ]) {
+ // Clearing first is what makes the paste replace the target's formatting rather than
+ // layer onto it. Attribute edits never shift offsets, so `range` stays valid afterwards.
+ for (const item of [ ...range.getItems() ]) {
+ if (!item.is("$textProxy")) {
+ continue;
+ }
+
+ const itemRange = writer.createRangeOn(item);
+
+ for (const name of [ ...item.getAttributeKeys() ]) {
+ if (schema.getAttributeProperties(name).isFormatting) {
+ writer.removeAttribute(name, itemRange);
+ }
+ }
+ }
+
+ for (const [ name, value ] of Object.entries(formatting)) {
+ for (const validRange of schema.getValidRanges([ range ], name)) {
+ writer.setAttribute(name, value, validRange);
+ }
+ }
+ }
+ });
+}
diff --git a/packages/ckeditor5/src/plugins/format_painter/format_painter_ui.spec.ts b/packages/ckeditor5/src/plugins/format_painter/format_painter_ui.spec.ts
new file mode 100644
index 0000000000..aa698317a7
--- /dev/null
+++ b/packages/ckeditor5/src/plugins/format_painter/format_painter_ui.spec.ts
@@ -0,0 +1,164 @@
+import {
+ Bold,
+ type ButtonView,
+ type ClassicEditor,
+ Essentials,
+ _getModelData as getModelData,
+ HorizontalLine,
+ Italic,
+ keyCodes,
+ Paragraph,
+ _setModelData as setModelData
+} from "ckeditor5";
+import { beforeEach, describe, expect, it } from "vitest";
+
+import { createTestEditor } from "../../../test/editor-kit.js";
+import { COPY_FORMAT_COMMAND, CURSOR_ACTIVE_CSS_CLASS, FORMAT_PAINTER_COMPONENT } from "./constants.js";
+import TriliumFormatPainter from "./format_painter.js";
+import FormatPainterUI from "./format_painter_ui.js";
+
+describe("FormatPainterUI", () => {
+ let editor: ClassicEditor;
+
+ async function createEditor() {
+ editor = await createTestEditor([ Essentials, Paragraph, Bold, Italic, HorizontalLine, TriliumFormatPainter ]);
+ }
+
+ function ui() {
+ return editor.plugins.get(FormatPainterUI);
+ }
+
+ function button() {
+ return editor.ui.componentFactory.create(FORMAT_PAINTER_COMPONENT) as ButtonView;
+ }
+
+ function root() {
+ const domRoot = editor.editing.view.getDomRoot();
+ if (!domRoot) {
+ throw new Error("editing root is not attached");
+ }
+ return domRoot;
+ }
+
+ function paintClick() {
+ root().dispatchEvent(new MouseEvent("mouseup", { bubbles: true }));
+ }
+
+ function pressKey(keyCode: number) {
+ editor.editing.view.document.fire("keydown", {
+ keyCode,
+ preventDefault: () => {},
+ stopPropagation: () => {},
+ domTarget: editor.editing.view.getDomRoot()
+ });
+ }
+
+ function model() {
+ return getModelData(editor.model, { withoutSelection: true });
+ }
+
+ beforeEach(async () => {
+ await createEditor();
+ });
+
+ it("registers the plugin and a labelled, icon-bearing button", () => {
+ expect(FormatPainterUI.pluginName).toBe("FormatPainterUI");
+
+ const view = button();
+ expect(view.label).toBe("Copy formatting");
+ expect(view.icon).toBeTruthy();
+ expect(view.tooltip).toBe(true);
+ });
+
+ it("binds the button's enabled state to whether formatting can be copied", () => {
+ const view = button();
+
+ setModelData(editor.model, "<paragraph>foo[]</paragraph>");
+ expect(view.isEnabled).toBe(true);
+
+ // A selected block object is not a place formatting can be read from.
+ setModelData(editor.model, "[<horizontalLine></horizontalLine>]");
+ expect(view.isEnabled).toBe(false);
+ });
+
+ describe("one-shot painting", () => {
+ it("arms on click: copies the formatting and marks the roots", () => {
+ setModelData(editor.model, "<paragraph>[<$text bold=\"true\">foo</$text>]</paragraph>");
+
+ const view = button();
+ view.fire("execute");
+
+ expect(ui().isActive).toBe(true);
+ expect(view.isOn).toBe(true);
+ expect(root().classList.contains(CURSOR_ACTIVE_CSS_CLASS)).toBe(true);
+ expect(editor.commands.get(COPY_FORMAT_COMMAND)?.value).toEqual({ bold: true });
+ });
+
+ it("pastes onto the next click's selection, then disarms", () => {
+ setModelData(editor.model, "<paragraph>[<$text bold=\"true\">foo</$text>]</paragraph>");
+ button().fire("execute");
+
+ // The user now selects a target elsewhere and releases the mouse over it.
+ setModelData(editor.model, "<paragraph>[bar]</paragraph>");
+ paintClick();
+
+ expect(model()).toContain("<$text bold=\"true\">bar</$text>");
+ expect(ui().isActive).toBe(false);
+ expect(root().classList.contains(CURSOR_ACTIVE_CSS_CLASS)).toBe(false);
+ });
+
+ it("disarms without pasting when the button is clicked again", () => {
+ setModelData(editor.model, "<paragraph>[<$text bold=\"true\">foo</$text>]</paragraph>");
+ const view = button();
+
+ view.fire("execute");
+ expect(ui().isActive).toBe(true);
+
+ view.fire("execute");
+ expect(ui().isActive).toBe(false);
+
+ // A later click must not paste, since the painter is no longer armed.
+ setModelData(editor.model, "<paragraph>[bar]</paragraph>");
+ paintClick();
+ expect(model()).toContain("<paragraph>bar</paragraph>");
+ });
+ });
+
+ describe("cancelling", () => {
+ function arm() {
+ setModelData(editor.model, "<paragraph>[<$text bold=\"true\">foo</$text>]</paragraph>");
+ button().fire("execute");
+ expect(ui().isActive).toBe(true);
+ }
+
+ it("cancels on Escape", () => {
+ arm();
+ pressKey(keyCodes.esc);
+ expect(ui().isActive).toBe(false);
+ });
+
+ it("ignores a non-Escape key while armed", () => {
+ arm();
+ pressKey(keyCodes.arrowdown);
+ expect(ui().isActive).toBe(true);
+ });
+
+ it("does nothing on Escape when not armed", () => {
+ pressKey(keyCodes.esc);
+ expect(ui().isActive).toBe(false);
+ });
+
+ it("cancels when the editor turns read-only", () => {
+ arm();
+ editor.enableReadOnlyMode("test");
+ expect(ui().isActive).toBe(false);
+ editor.disableReadOnlyMode("test");
+ });
+
+ it("tolerates a read-only toggle while not armed", () => {
+ editor.enableReadOnlyMode("test");
+ expect(ui().isActive).toBe(false);
+ editor.disableReadOnlyMode("test");
+ });
+ });
+});
diff --git a/packages/ckeditor5/src/plugins/format_painter/format_painter_ui.ts b/packages/ckeditor5/src/plugins/format_painter/format_painter_ui.ts
new file mode 100644
index 0000000000..3c01c63c61
--- /dev/null
+++ b/packages/ckeditor5/src/plugins/format_painter/format_painter_ui.ts
@@ -0,0 +1,111 @@
+import "../../theme/format_painter.css";
+
+import { IconPaintRoller } from "@ckeditor/ckeditor5-icons";
+import { ButtonView, DomEmitterMixin, keyCodes, Plugin, type ViewDocumentKeyDownEvent } from "ckeditor5";
+
+import { COPY_FORMAT_COMMAND, CURSOR_ACTIVE_CSS_CLASS, FORMAT_PAINTER_COMPONENT, PASTE_FORMAT_COMMAND } from "./constants.js";
+
+const FormatPainterUIBase = DomEmitterMixin(Plugin);
+
+/**
+ * The `formatPainter` toolbar button and its one-shot painting behaviour.
+ *
+ * Clicking the button copies the current selection's formatting and *arms* the painter: the editing
+ * roots take a cursor class and the next click (or drag-release) inside the editor pastes that
+ * formatting onto whatever the click selected, then disarms. Clicking the button again, pressing
+ * Escape, or the editor going read-only cancels an armed painter.
+ *
+ * There is deliberately no keyboard shortcut: the Word/Office pair `Ctrl+Shift+C`/`Ctrl+Shift+V`
+ * collides in the browser with "inspect element" (reserved, not preventable) and "paste as plain
+ * text". The `copyFormat`/`pasteFormat` commands remain available for a non-conflicting binding.
+ */
+export default class FormatPainterUI extends FormatPainterUIBase {
+
+ declare public isActive: boolean;
+
+ static get pluginName() {
+ return "FormatPainterUI" as const;
+ }
+
+ init() {
+ const editor = this.editor;
+
+ this.set("isActive", false);
+
+ editor.ui.componentFactory.add(FORMAT_PAINTER_COMPONENT, (locale) => {
+ const button = new ButtonView(locale);
+ const copyCommand = editor.commands.get(COPY_FORMAT_COMMAND);
+
+ button.set({ label: editor.t("Copy formatting"), icon: IconPaintRoller, tooltip: true });
+
+ /* v8 ignore next 3 -- copyFormat is registered by the required editing plugin before the toolbar builds this button; the guard only narrows the type */
+ if (!copyCommand) {
+ return button;
+ }
+
+ // `isEnabled` follows "can I copy here"; `isOn` shows the button pressed while armed.
+ button.bind("isEnabled").to(copyCommand);
+ button.bind("isOn").to(this, "isActive");
+ this.listenTo(button, "execute", () => this._toggle());
+
+ return button;
+ });
+
+ // A click landing after the editor turned read-only would paste into no-longer-editable
+ // content, so drop an armed painter when that happens.
+ this.listenTo(editor, "change:isReadOnly", () => this._disarm());
+
+ this.listenTo<ViewDocumentKeyDownEvent>(editor.editing.view.document, "keydown", (evt, data) => {
+ if (this.isActive && data.keyCode === keyCodes.esc) {
+ this._disarm();
+ data.preventDefault();
+ evt.stop();
+ }
+ }, { priority: "high" });
+ }
+
+ override destroy() {
+ super.destroy();
+ this._disarm();
+ }
+
+ private _toggle() {
+ if (this.isActive) {
+ this._disarm();
+ return;
+ }
+
+ this._arm();
+ }
+
+ private _arm() {
+ const editor = this.editor;
+
+ editor.execute(COPY_FORMAT_COMMAND);
+ this.isActive = true;
+
+ for (const root of editor.editing.view.domRoots.values()) {
+ root.classList.add(CURSOR_ACTIVE_CSS_CLASS);
+ this.listenTo(root, "mouseup", this._paint);
+ }
+ }
+
+ private readonly _paint = () => {
+ this.editor.execute(PASTE_FORMAT_COMMAND);
+ this.editor.editing.view.focus();
+ this._disarm();
+ };
+
+ private _disarm() {
+ if (!this.isActive) {
+ return;
+ }
+
+ this.isActive = false;
+
+ for (const root of this.editor.editing.view.domRoots.values()) {
+ root.classList.remove(CURSOR_ACTIVE_CSS_CLASS);
+ this.stopListening(root, "mouseup", this._paint);
+ }
+ }
+}
diff --git a/packages/ckeditor5/src/theme/format_painter.css b/packages/ckeditor5/src/theme/format_painter.css
new file mode 100644
index 0000000000..05fafcce2c
--- /dev/null
+++ b/packages/ckeditor5/src/theme/format_painter.css
@@ -0,0 +1,9 @@
+/*
+ * Cursor for an armed format painter. `FormatPainterUI` toggles `ck-format-painter-active` on the
+ * editing root; `cursor` inherits, so the whole editable signals that the next click will paint.
+ * The class name is premium's, so any existing override keyed on it keeps applying.
+ */
+
+.ck.ck-content.ck-editor__editable.ck-format-painter-active {
+ cursor: copy;
+}