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): paint a tapped word, and a selection from the button
Elian Dorancd4659f2752d
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex a258649d06..d727711e33 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -4378,6 +4378,7 @@"anchor-widget": "anchor widget","anchors": "Anchors","applies-to-the-current-paragraph": "Applies to the current paragraph.",+ "apply-formatting": "Apply formatting","ask-ai": "Ask AI…","ask-ai-to": "Ask AI to…","ask-ai-to-rewrite-the-selection-or-generate-new-content": "Ask AI to rewrite the selection or generate new content.",diff --git a/docs/User Guide/User Guide/Note Types/Text/Format Painter.md b/docs/User Guide/User Guide/Note Types/Text/Format Painter.mdindex e397a98715..3fcef5a63c 100644--- a/docs/User Guide/User Guide/Note Types/Text/Format Painter.md+++ b/docs/User Guide/User Guide/Note Types/Text/Format Painter.md@@ -5,14 +5,15 @@ The Format Painter is a feature in text notes that allows users to copy the form## Usage Instructions-Click the text that you want to copy the formatting from and use the _Copy formatting_ toolbar button (<span class="tn-icon cke cke-paint-roller"></span>) to copy the style. Then select the target text with your mouse to apply the formatting.+Click the text that you want to copy the formatting from and use the _Copy formatting_ toolbar button (<span class="tn-icon cke cke-paint-roller"></span>) to copy the style. Then select the target text with your mouse, or click a word, to apply the formatting.* **To copy the formatting**: Place the cursor inside text with some formatting and click the _Copy formatting_ toolbar button. The mouse cursor changes to indicate the painter is armed.-* **To paint with the copied formatting**: Select the target text with your mouse. The formatting is applied when you release the button, and the painter disarms — the cursor returns to normal.-* **To cancel without painting**: Click the toolbar button again or press <kbd>Escape</kbd>.+* **To paint with the copied formatting**: Select the target text with your mouse. The formatting is applied when you release the button, and the painter disarms — the cursor returns to normal. Clicking or tapping a word applies it to the whole word.+* **To paint a selection made otherwise**, such as with the keyboard or the selection handles of a touch screen: select the target text, then use the toolbar button again, which reads _Apply formatting_ once the selection has moved. On a phone, the formatting row stays open while the painter is armed, so the button stays in reach.+* **To cancel without painting**: Click the toolbar button again before selecting other text, or press <kbd>Escape</kbd>.## Limitations1. Painting with block-level formatting (like headings or image styles) is not supported yet. This is because, in <a class="reference-link" href="../../Advanced%20Usage/Technologies%20used/CKEditor.md">CKEditor</a>, they are considered a part of the content rather than text formatting.-2. The painter applies to a selection, not to a word: clicking a single word does not format it. A click only primes the caret, so text you type there takes the copied formatting.+2. A click outside a word, such as between two spaces or at the end of a line, only primes the caret, so text you type there takes the copied formatting.3. The painter is one-shot; each paint requires copying the formatting again.\ No newline at end of filediff --git a/packages/ckeditor5/src/plugins/format_painter/format_painter_ui.spec.ts b/packages/ckeditor5/src/plugins/format_painter/format_painter_ui.spec.tsindex c010f41a51..f55757f59e 100644--- a/packages/ckeditor5/src/plugins/format_painter/format_painter_ui.spec.ts+++ b/packages/ckeditor5/src/plugins/format_painter/format_painter_ui.spec.ts@@ -58,6 +58,18 @@ describe("FormatPainterUI", () => {return getModelData(editor.model, { withoutSelection: true });}+ function selectInFirstParagraph(start: number, end: number) {+ editor.model.change((writer) => {+ const paragraph = editor.model.document.getRoot()?.getChild(0);+ if (!paragraph) {+ throw new Error("expected a paragraph");+ }+ writer.setSelection(writer.createRange(+ writer.createPositionAt(paragraph, start), writer.createPositionAt(paragraph, end)+ ));+ });+ }+beforeEach(async () => {await createEditor();});@@ -108,6 +120,58 @@ describe("FormatPainterUI", () => {expect(root().classList.contains(CURSOR_ACTIVE_CSS_CLASS)).toBe(false);});+ it("paints the whole word under a tapped caret, leaving the caret where it was", () => {+ setModelData(editor.model, "<paragraph>[<$text bold=\"true\">foo</$text>] bar baz</paragraph>");+ button().fire("execute");++ setModelData(editor.model, "<paragraph>foo ba[]r baz</paragraph>");+ paintClick();+ expect(getModelData(editor.model)).toBe("<paragraph>foo <$text bold=\"true\">ba[]r</$text> baz</paragraph>");+ expect(ui().isActive).toBe(false);++ // One step to undo.+ editor.execute("undo");+ expect(model()).toBe("<paragraph>foo bar baz</paragraph>");+ });++ it("formats what is typed next at a caret outside any word", () => {+ setModelData(editor.model, "<paragraph>[<$text bold=\"true\">foo</$text>]</paragraph>");+ button().fire("execute");++ setModelData(editor.model, "<paragraph>foo, []</paragraph>");+ paintClick();+ expect(model()).toBe("<paragraph>foo, </paragraph>");+ expect(editor.model.document.selection.getAttribute("bold")).toBe(true);+ });++ it("applies to the text selected since it armed when the button is pressed again", () => {+ setModelData(editor.model, "<paragraph>[<$text bold=\"true\">foo</$text>] bar baz</paragraph>");+ const view = button();+ view.fire("execute");+ expect(view.label).toBe("Copy formatting");++ // A selection made without a mouse, such as with the handles of a touch screen.+ selectInFirstParagraph(4, 7);+ expect(view.label).toBe("Apply formatting");+ view.fire("execute");++ expect(model()).toBe("<paragraph><$text bold=\"true\">foo</$text> <$text bold=\"true\">bar</$text> baz</paragraph>");+ expect(ui().isActive).toBe(false);+ expect(view.label).toBe("Copy formatting");+ });++ it("cancels from the button when the selection moved to a caret", () => {+ setModelData(editor.model, "<paragraph>[<$text bold=\"true\">foo</$text>] bar</paragraph>");+ const view = button();+ view.fire("execute");++ selectInFirstParagraph(5, 5);+ expect(view.label).toBe("Copy formatting");+ view.fire("execute");+ expect(ui().isActive).toBe(false);+ expect(model()).toBe("<paragraph><$text bold=\"true\">foo</$text> bar</paragraph>");+ });+it("disarms without pasting when the button is clicked again", () => {setModelData(editor.model, "<paragraph>[<$text bold=\"true\">foo</$text>]</paragraph>");const view = button();diff --git a/packages/ckeditor5/src/plugins/format_painter/format_painter_ui.ts b/packages/ckeditor5/src/plugins/format_painter/format_painter_ui.tsindex 3c01c63c61..b349a4f0e2 100644--- a/packages/ckeditor5/src/plugins/format_painter/format_painter_ui.ts+++ b/packages/ckeditor5/src/plugins/format_painter/format_painter_ui.ts@@ -1,7 +1,9 @@import "../../theme/format_painter.css";import { IconPaintRoller } from "@ckeditor/ckeditor5-icons";-import { ButtonView, DomEmitterMixin, keyCodes, Plugin, type ViewDocumentKeyDownEvent } from "ckeditor5";+import {+ ButtonView, DomEmitterMixin, keyCodes, type Model, type ModelPosition, Plugin, type ViewDocumentKeyDownEvent+} from "ckeditor5";import { COPY_FORMAT_COMMAND, CURSOR_ACTIVE_CSS_CLASS, FORMAT_PAINTER_COMPONENT, PASTE_FORMAT_COMMAND } from "./constants.js";@@ -12,8 +14,10 @@ const FormatPainterUIBase = DomEmitterMixin(Plugin);** 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.+ * formatting onto whatever the click selected, or onto the whole word under a caret, then disarms.+ * Clicking the button again applies the formatting to text selected since it armed, which is how a+ * selection made without a mouse, such as with the handles of a touch screen, is painted; otherwise+ * it cancels, as do pressing Escape and the editor going read-only.** 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@@ -23,6 +27,9 @@ export default class FormatPainterUI extends FormatPainterUIBase {declare public isActive: boolean;+ /** Whether the button applies the formatting, to text selected since the painter armed. */+ declare public canApply: boolean;+static get pluginName() {return "FormatPainterUI" as const;}@@ -31,12 +38,15 @@ export default class FormatPainterUI extends FormatPainterUIBase {const editor = this.editor;this.set("isActive", false);+ this.set("canApply", 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 });+ button.set({ icon: IconPaintRoller, tooltip: true });+ button.bind("label").to(this, "canApply", (canApply) =>+ (canApply ? editor.t("Apply formatting") : editor.t("Copy formatting")));/* 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) {@@ -70,6 +80,10 @@ export default class FormatPainterUI extends FormatPainterUIBase {}private _toggle() {+ if (this.canApply) {+ this._paint();+ return;+ }if (this.isActive) {this._disarm();return;@@ -83,6 +97,7 @@ export default class FormatPainterUI extends FormatPainterUIBase {editor.execute(COPY_FORMAT_COMMAND);this.isActive = true;+ this.listenTo(editor.model.document.selection, "change:range", this._followSelection);for (const root of editor.editing.view.domRoots.values()) {root.classList.add(CURSOR_ACTIVE_CSS_CLASS);@@ -90,8 +105,26 @@ export default class FormatPainterUI extends FormatPainterUIBase {}}+ private readonly _followSelection = () => {+ this.canApply = !this.editor.model.document.selection.isCollapsed;+ };+private readonly _paint = () => {- this.editor.execute(PASTE_FORMAT_COMMAND);+ const { model } = this.editor;+ const selection = model.document.selection;+ const caret = selection.isCollapsed ? selection.getFirstPosition() : null;+ const word = caret && getWordRange(model, caret);++ if (caret && word) {+ // Painted through a selection of the word, given back in the same step to undo.+ model.change((writer) => {+ writer.setSelection(word);+ this.editor.execute(PASTE_FORMAT_COMMAND);+ writer.setSelection(caret);+ });+ } else {+ this.editor.execute(PASTE_FORMAT_COMMAND);+ }this.editor.editing.view.focus();this._disarm();};@@ -102,6 +135,8 @@ export default class FormatPainterUI extends FormatPainterUIBase {}this.isActive = false;+ this.canApply = false;+ this.stopListening(this.editor.model.document.selection, "change:range", this._followSelection);for (const root of this.editor.editing.view.domRoots.values()) {root.classList.remove(CURSOR_ACTIVE_CSS_CLASS);@@ -109,3 +144,21 @@ export default class FormatPainterUI extends FormatPainterUIBase {}}}++/** The word around `position`, as letters, digits and underscores on either side, or `null` outside one. */+function getWordRange(model: Model, position: ModelPosition) {+ const block = model.createRangeIn(position.parent);+ const reach = (direction: "forward" | "backward") => {+ let end = position;+ for (const { item, nextPosition } of block.getWalker({ startPosition: position, direction, singleCharacters: true })) {+ if (!item.is("$textProxy") || !/^[\p{L}\p{N}_]$/u.test(item.data)) {+ break;+ }+ end = nextPosition;+ }+ return end;+ };++ const range = model.createRange(reach("backward"), reach("forward"));+ return range.isCollapsed ? null : range;+}diff --git a/packages/ckeditor5/src/plugins/text_formatting_toolbar.spec.ts b/packages/ckeditor5/src/plugins/text_formatting_toolbar.spec.tsindex db24acad12..ca24093e7e 100644--- a/packages/ckeditor5/src/plugins/text_formatting_toolbar.spec.ts+++ b/packages/ckeditor5/src/plugins/text_formatting_toolbar.spec.ts@@ -6,6 +6,7 @@ import {import { describe, expect, it, vi } from "vitest";import { createTestEditor } from "../../test/editor-kit.js";+import TriliumFormatPainter from "./format_painter/format_painter.js";import TextFormattingToolbar from "./text_formatting_toolbar.js";import ToolbarGroupMenu, { type ToolbarGroupMenuRequest } from "./toolbar_group_menu.js";@@ -136,6 +137,26 @@ describe("TextFormattingToolbar", () => {expect(plugin.isActive).toBe(true);});+ it("stays while the format painter is armed, so its button can apply or cancel it", async () => {+ const editor = await createTestEditor([Essentials, Paragraph, Bold, TriliumFormatPainter, TextFormattingToolbar], {+ toolbar: ["textFormatting"],+ textFormattingToolbar: ["formatPainter"]+ });+ const plugin = editor.plugins.get(TextFormattingToolbar);+ setModelData(editor.model, "<paragraph>foo bar</paragraph>");+ select(editor, 0, 3);+ expect(plugin.isActive).toBe(true);++ const painter = plugin.toolbarView.items.get(2) as ButtonView;+ painter.fire("execute");+ select(editor, 5, 5);+ expect(plugin.isActive).toBe(true);++ // Painting disarms it, and the caret it leaves takes the toolbar with it.+ editor.editing.view.getDomRoot()?.dispatchEvent(new MouseEvent("mouseup", { bubbles: true }));+ expect(plugin.isActive).toBe(false);+ });+it("does not follow the selection when no items are configured", async () => {const editor = await createTestEditor([Essentials, Paragraph, TextFormattingToolbar], {toolbar: ["textFormatting"]diff --git a/packages/ckeditor5/src/plugins/text_formatting_toolbar.ts b/packages/ckeditor5/src/plugins/text_formatting_toolbar.tsindex 42e0489c06..a76202559a 100644--- a/packages/ckeditor5/src/plugins/text_formatting_toolbar.ts+++ b/packages/ckeditor5/src/plugins/text_formatting_toolbar.ts@@ -3,6 +3,8 @@ import {} from "ckeditor5";import type { Editor, ToolbarConfig } from "ckeditor5";+import FormatPainterUI from "./format_painter/format_painter_ui.js";+/*** A second toolbar of text formatting, which the `textFormatting` button swaps in for the editor's* own toolbar and the back button at its start swaps out again. The items come from the@@ -87,12 +89,20 @@ export default class TextFormattingToolbar extends Plugin {* a selected object, such as an image, which holds no text to format.*/private followSelection() {- const { model } = this.editor;+ const { model, plugins } = this.editor;const selection = model.document.selection;const holdsText = () => {const selected = selection.getSelectedElement();return !selection.isCollapsed && !(selected && model.schema.isObject(selected));};+ // An armed format painter keeps the toolbar, whose painter button applies or cancels it.+ const painter = plugins.has(FormatPainterUI) ? plugins.get(FormatPainterUI) : undefined;+ const swapOut = () => {+ if (this.shownForSelection && !heldText && !painter?.isActive) {+ this.isActive = false;+ this.shownForSelection = false;+ }+ };let heldText = holdsText();this.listenTo(selection, "change:range", () => {@@ -105,11 +115,13 @@ export default class TextFormattingToolbar extends Plugin {if (isHoldingText && !this.isActive) {this.isActive = true;this.shownForSelection = true;- } else if (!isHoldingText && this.shownForSelection) {- this.isActive = false;- this.shownForSelection = false;+ } else {+ swapOut();}});+ if (painter) {+ this.listenTo(painter, "change:isActive", swapOut);+ }}}