Skip to content

Build your own AI office with Univer Office SDK. Bring editing, calculation, collaboration, and file processing into your product for people and AI agents. Built on an extensible open-source core.

feat(docs): unify format painter and preserve formatting through edits (#7733)

Univer727c34513963
diff --git a/packages/core/src/docs/data-model/text-x/__tests__/paragraph-id.spec.ts b/packages/core/src/docs/data-model/text-x/__tests__/paragraph-id.spec.ts
index 0a955bdb42..f6d8f42443 100644
--- a/packages/core/src/docs/data-model/text-x/__tests__/paragraph-id.spec.ts
+++ b/packages/core/src/docs/data-model/text-x/__tests__/paragraph-id.spec.ts
@@ -15,7 +15,7 @@
*/
import type { IDocumentBody } from '../../../../types/interfaces';
-import type { TextXAction } from '../../index';
+import type { TextXAction } from '../action-types';
import { describe, expect, it } from 'vitest';
import { UpdateDocsAttributeType } from '../../../../shared';
import { DataStreamTreeTokenType } from '../../types';
@@ -209,7 +209,7 @@ describe('TextX paragraph ids', () => {
TextX.makeInvertible(actions, body);
TextX.apply(body, actions);
- expect(actions[1].body?.paragraphs?.[0].paragraphId).toBe('para_original');
+ expect(actions[1].body?.paragraphs?.[0].paragraphId).toBe(body.paragraphs?.[1].paragraphId);
expect(body.paragraphs?.[0]).toEqual({ startIndex: 1, paragraphId: 'para_original' });
expect(body.paragraphs?.[1].startIndex).toBe(3);
expect(body.paragraphs?.[1].paragraphId).toMatch(PARAGRAPH_ID_PATTERN);
@@ -328,6 +328,186 @@ describe('TextX paragraph ids', () => {
expect(body.paragraphs).toEqual([{ startIndex: 2, paragraphId: 'para_second' }]);
});
+ it.each([UpdateDocsAttributeType.REPLACE, UpdateDocsAttributeType.COVER])('keeps adjacent paragraph identities during disjoint formatting with cover type %s', (coverType) => {
+ const body: IDocumentBody = {
+ dataStream: 'Before\rAlpha\rBravo\rCharlie\rAfter\r\n',
+ paragraphs: [6, 12, 18, 26, 32].map((startIndex, index) => ({ startIndex, paragraphId: `para_original_${index}` })),
+ };
+ const original = JSON.parse(JSON.stringify(body)) as IDocumentBody;
+ const textX = new TextX();
+ let cursor = 0;
+ for (const startIndex of [12, 18, 26]) {
+ textX.retain(startIndex - cursor);
+ textX.retain(1, {
+ dataStream: '',
+ paragraphs: [{ startIndex: 0, paragraphId: original.paragraphs!.find((paragraph) => paragraph.startIndex === startIndex)!.paragraphId, paragraphStyle: { lineSpacing: 2 } }],
+ }, coverType);
+ cursor = startIndex + 1;
+ }
+ const actions = textX.serialize();
+ TextX.makeInvertible(actions, body);
+ TextX.apply(body, actions);
+
+ expect(body.paragraphs?.map((paragraph) => paragraph.paragraphId)).toEqual(original.paragraphs?.map((paragraph) => paragraph.paragraphId));
+ expect(body.paragraphs?.map((paragraph) => paragraph.startIndex)).toEqual([6, 12, 18, 26, 32]);
+ expect(body.paragraphs?.slice(1, 4).map((paragraph) => paragraph.paragraphStyle?.lineSpacing)).toEqual([2, 2, 2]);
+ TextX.apply(body, TextX.invert(actions));
+ expect(body.paragraphs).toEqual(original.paragraphs);
+ });
+
+ it.each(['typing', 'deletion', 'split', 'join', 'formatting'])('converges multi-paragraph formatting with concurrent %s', (scenario) => {
+ const original: IDocumentBody = {
+ dataStream: 'AA\rBB\rCC\r\n',
+ paragraphs: [2, 5, 8].map((startIndex, index) => ({ startIndex, paragraphId: `para_concurrent_${index}` })),
+ };
+ const clone = <T>(value: T): T => JSON.parse(JSON.stringify(value));
+ const formatting = new TextX();
+ for (const paragraph of original.paragraphs!) {
+ formatting.retain(2);
+ formatting.retain(1, {
+ dataStream: '',
+ paragraphs: [{ ...paragraph, startIndex: 0, paragraphStyle: {}, bullet: { listId: 'list', listType: 'BULLET_LIST', nestingLevel: 0 } }],
+ }, UpdateDocsAttributeType.REPLACE);
+ }
+ const editing = new TextX();
+ editing.retain(scenario === 'join' ? 2 : scenario === 'formatting' ? 5 : 4);
+ if (scenario === 'typing') {
+ editing.insert(1, { dataStream: 'X' });
+ } else if (scenario === 'split') {
+ editing.insert(1, { dataStream: '\r', paragraphs: [{ startIndex: 0, paragraphId: 'para_split' }] });
+ } else if (scenario === 'formatting') {
+ editing.retain(1, { dataStream: '', paragraphs: [{ startIndex: 0, paragraphId: 'para_concurrent_1', paragraphStyle: { lineSpacing: 2 } }] }, UpdateDocsAttributeType.REPLACE);
+ } else {
+ editing.delete(1);
+ }
+ const left = formatting.serialize();
+ const right = editing.serialize();
+ TextX.makeInvertible(left, clone(original));
+ TextX.makeInvertible(right, clone(original));
+ const alice = TextX.apply(TextX.apply(clone(original), clone(left)), TextX.transform(clone(right), clone(left), 'left'));
+ const bob = TextX.apply(TextX.apply(clone(original), clone(right)), TextX.transform(clone(left), clone(right), 'right'));
+ expect(alice).toEqual(bob);
+ const ids = alice.paragraphs?.map((paragraph) => paragraph.paragraphId);
+ expect(new Set(ids).size).toBe(ids?.length);
+ });
+
+ it.each([UpdateDocsAttributeType.COVER, UpdateDocsAttributeType.REPLACE])('keeps formatting undo and redo identities stable across splits (%s)', (coverType) => {
+ const clone = <T>(value: T): T => JSON.parse(JSON.stringify(value));
+ for (const offset of [3, 4, 5]) {
+ for (const priority of ['left', 'right'] as const) {
+ const original: IDocumentBody = {
+ dataStream: 'AA\rBB\rCC\r\n',
+ paragraphs: [2, 5, 8].map((startIndex, index) => ({ startIndex, paragraphId: `para_${index}`, paragraphStyle: {} })),
+ };
+ const formatting = new TextX();
+ for (const paragraph of original.paragraphs!) {
+ formatting.retain(2).retain(1, {
+ dataStream: '',
+ paragraphs: [{ ...paragraph, startIndex: 0, paragraphStyle: { lineSpacing: 2 } }],
+ }, coverType);
+ }
+ const format = formatting.serialize();
+ const split = new TextX().retain(offset).insert(1, {
+ dataStream: '\r',
+ paragraphs: [{ startIndex: 0, paragraphId: 'para_split', paragraphStyle: {} }],
+ }).serialize();
+ TextX.makeInvertible(format, original);
+ TextX.makeInvertible(split, original);
+ const splitOnly = TextX.apply(clone(original), clone(split));
+ const rebasedFormat = TextX.transform(clone(format), clone(split), priority);
+ const rebasedSplit = TextX.transform(clone(split), clone(format), priority === 'left' ? 'right' : 'left');
+ const alice = TextX.apply(TextX.apply(clone(original), clone(format)), rebasedSplit);
+ const bob = TextX.apply(clone(splitOnly), clone(rebasedFormat));
+ expect(alice).toEqual(bob);
+ const identities = splitOnly.paragraphs!.map((paragraph) => paragraph.paragraphId);
+ expect(alice.paragraphs!.map((paragraph) => paragraph.paragraphId)).toEqual(identities);
+ expect(new Set(identities).size).toBe(4);
+
+ const undo = TextX.transform(TextX.invert(clone(format)), clone(split), priority);
+ TextX.apply(alice, undo);
+ expect(alice.paragraphs).toEqual(splitOnly.paragraphs);
+ // History replay captures inverse data again against the rebased model.
+ TextX.makeInvertible(undo, bob);
+ TextX.apply(alice, TextX.invert(undo));
+ expect(alice).toEqual(bob);
+ }
+ }
+ });
+
+ it.each([undefined, 'para_original'])('allocates one shared split identity before replay when the payload id is %s', (paragraphId) => {
+ const clone = <T>(value: T): T => JSON.parse(JSON.stringify(value));
+ const original: IDocumentBody = {
+ dataStream: 'AB\r\n',
+ paragraphs: [{ startIndex: 2, paragraphId: 'para_original' }],
+ };
+ const split = new TextX().retain(1).insert(1, {
+ dataStream: '\r',
+ paragraphs: [{ startIndex: 0, paragraphId } as never],
+ }).serialize();
+ TextX.makeInvertible(split, original);
+ const alice = TextX.apply(clone(original), split);
+ const received = clone(split);
+ // The real mutation captures undo on the receiving client as well.
+ TextX.makeInvertible(received, clone(original));
+ const bob = TextX.apply(clone(original), received);
+ expect(alice).toEqual(bob);
+ expect(alice.paragraphs?.[0].paragraphId).toBe('para_original');
+ expect(alice.paragraphs?.[1].paragraphId).not.toBe('para_original');
+ expect(alice.paragraphs?.[1].paragraphId).toBe(split[1].body?.paragraphs?.[0].paragraphId);
+ expect(original.paragraphs?.[0].paragraphId).toBe('para_original');
+ });
+
+ it('preserves explicit identity replacement through normalization, undo and redo', () => {
+ const original: IDocumentBody = {
+ dataStream: 'A\r\n',
+ paragraphs: [{ startIndex: 1, paragraphId: 'para_original', paragraphStyle: {} }],
+ };
+ const body = JSON.parse(JSON.stringify(original));
+ const actions = new TextX().retain(2, {
+ dataStream: '',
+ paragraphs: [{ startIndex: 1, paragraphId: 'para_replacement', paragraphStyle: { lineSpacing: 2 } }],
+ }, UpdateDocsAttributeType.REPLACE).serialize();
+ TextX.makeInvertible(actions, original);
+ TextX.apply(body, actions);
+ expect(body.paragraphs[0].paragraphId).toBe('para_replacement');
+ TextX.apply(body, TextX.invert(actions));
+ expect(body.paragraphs).toEqual(original.paragraphs);
+ TextX.apply(body, actions);
+ expect(body.paragraphs[0].paragraphId).toBe('para_replacement');
+ });
+
+ it('composes paragraph formatting without restoring stale identities after a split', () => {
+ const clone = <T>(value: T): T => JSON.parse(JSON.stringify(value));
+ const original: IDocumentBody = {
+ dataStream: 'AB\r\n',
+ paragraphs: [{ startIndex: 2, paragraphId: 'para_original', paragraphStyle: {} }],
+ };
+ const format = new TextX().retain(3, {
+ dataStream: '',
+ paragraphs: [{ startIndex: 2, paragraphId: 'para_original', paragraphStyle: { lineSpacing: 2 } }],
+ }, UpdateDocsAttributeType.COVER).serialize();
+ TextX.makeInvertible(format, original);
+ const formatted = TextX.apply(clone(original), format);
+ const second = new TextX().retain(3, {
+ dataStream: '',
+ paragraphs: [{ startIndex: 2, paragraphId: 'para_original', paragraphStyle: { spaceAbove: { v: 8 } } }],
+ }, UpdateDocsAttributeType.COVER).serialize();
+ TextX.makeInvertible(second, formatted);
+ const composed = TextX.compose(format, second);
+ TextX.makeInvertible(composed, original);
+ const split = new TextX().retain(1).insert(1, {
+ dataStream: '\r',
+ paragraphs: [{ startIndex: 0, paragraphId: 'para_split', paragraphStyle: {} }],
+ }).serialize();
+ TextX.makeInvertible(split, original);
+ const alice = TextX.apply(TextX.apply(clone(original), composed), TextX.transform(clone(split), clone(composed), 'left'));
+ const bob = TextX.apply(TextX.apply(clone(original), split), TextX.transform(clone(composed), clone(split), 'right'));
+ expect(alice).toEqual(bob);
+ expect(alice.paragraphs!.map((paragraph) => paragraph.paragraphId)).toEqual(['para_original', 'para_split']);
+ TextX.apply(alice, TextX.transform(TextX.invert(composed), split, 'right'));
+ expect(alice.paragraphs).toEqual(TextX.apply(clone(original), split).paragraphs);
+ });
+
it('preserves target paragraph id when retain metadata omits one', () => {
const body: IDocumentBody = {
dataStream: '\r\n',
diff --git a/packages/core/src/docs/data-model/text-x/__tests__/text-x.spec.ts b/packages/core/src/docs/data-model/text-x/__tests__/text-x.spec.ts
index bff52d04eb..bdba7574ad 100644
--- a/packages/core/src/docs/data-model/text-x/__tests__/text-x.spec.ts
+++ b/packages/core/src/docs/data-model/text-x/__tests__/text-x.spec.ts
@@ -607,6 +607,23 @@ describe('test TextX methods and branches', () => {
});
describe('test TextX static methods', () => {
+ it('keeps paragraph identity when undoing text formatting on its ending character', () => {
+ const body: IDocumentBody = {
+ dataStream: 'G\r\n',
+ paragraphs: [{ startIndex: 1, paragraphId: 'kept', paragraphStyle: { spaceAbove: { v: 12 } } }],
+ textRuns: [{ st: 0, ed: 2, ts: { cl: { rgb: '#ff0000' } } }],
+ };
+ const original = JSON.parse(JSON.stringify(body)) as IDocumentBody;
+ const actions = new TextX().retain(1).retain(1, {
+ dataStream: '',
+ textRuns: [{ st: 0, ed: 1, ts: { cl: { rgb: '#008000' } } }],
+ }).serialize();
+ TextX.makeInvertible(actions, body);
+ TextX.apply(body, actions);
+ TextX.apply(body, TextX.invert(actions));
+ expect(body).toMatchObject(original);
+ });
+
it.each([
{
name: 'column group',
diff --git a/packages/core/src/docs/data-model/text-x/apply-utils/common.ts b/packages/core/src/docs/data-model/text-x/apply-utils/common.ts
index 5ee255db58..aa8cc9e600 100644
--- a/packages/core/src/docs/data-model/text-x/apply-utils/common.ts
+++ b/packages/core/src/docs/data-model/text-x/apply-utils/common.ts
@@ -185,7 +185,7 @@ export function insertParagraphs(
insertBody: IDocumentBody,
textLength: number,
currentIndex: number,
- preserveMissingParagraphIds = false,
+ isUpdate = false,
originalDataStream = body.dataStream
) {
if (!body.paragraphs && !insertBody.paragraphs?.length) {
@@ -196,13 +196,17 @@ export function insertParagraphs(
const { paragraphs } = body;
const { paragraphs: insertParagraphs } = insertBody;
- normalizeInsertedParagraphIdsForDocument(paragraphs, insertParagraphs, currentIndex, {
- freshenSplitParagraph: true,
- preserveMissingParagraphIds,
- preserveExplicitSplitParagraphIds: Boolean((insertBody as unknown as Record<string, unknown>)[RESTORE_INSERTED_PARAGRAPH_IDS]),
- preserveExplicitParagraphIds: Boolean((insertBody as unknown as Record<string, unknown>)[PRESERVE_INSERTED_PARAGRAPH_IDS]),
- dataStream: originalDataStream,
- });
+ // Formatting temporarily removes and reinserts metadata without splitting text.
+ // Its paragraph ids are already resolved by updateParagraphs; insertion would
+ // otherwise transfer the next paragraph's identity to the formatted paragraph.
+ if (!isUpdate) {
+ normalizeInsertedParagraphIdsForDocument(paragraphs, insertParagraphs, currentIndex, {
+ freshenSplitParagraph: true,
+ preserveExplicitSplitParagraphIds: Boolean((insertBody as unknown as Record<string, unknown>)[RESTORE_INSERTED_PARAGRAPH_IDS]),
+ preserveExplicitParagraphIds: Boolean((insertBody as unknown as Record<string, unknown>)[PRESERVE_INSERTED_PARAGRAPH_IDS]),
+ dataStream: originalDataStream,
+ });
+ }
const paragraphIndexList = [];
let firstInsertParagraphNextIndex = -1;
@@ -302,7 +306,10 @@ export function normalizeInsertedParagraphIdsForDocument(
continue;
}
- insertParagraphs[i] = options.freshenSplitParagraph || firstInsertedParagraphId == null || firstInsertedParagraphId === splitParagraphId
+ // Resolve the remainder's fresh identity in the outgoing operation, even
+ // when a replay reuses the current paragraph id. Apply must not allocate
+ // a different remainder id on each collaboration peer.
+ insertParagraphs[i] = options.freshenSplitParagraph
? cloneParagraphWithId({
...insertParagraphs[i],
paragraphId: splitParagraphId,
diff --git a/packages/core/src/docs/data-model/text-x/build-utils/__tests__/text-x-utils.spec.ts b/packages/core/src/docs/data-model/text-x/build-utils/__tests__/text-x-utils.spec.ts
index 2996445c93..920ff13e98 100644
--- a/packages/core/src/docs/data-model/text-x/build-utils/__tests__/text-x-utils.spec.ts
+++ b/packages/core/src/docs/data-model/text-x/build-utils/__tests__/text-x-utils.spec.ts
@@ -16,7 +16,7 @@
import type { IDocumentBody } from '../../../../../types/interfaces/i-document-data';
import { describe, expect, it } from 'vitest';
-import { CustomRangeType } from '../../../../../types/interfaces/i-document-data';
+import { CustomRangeType, DocumentFlavor } from '../../../../../types/interfaces/i-document-data';
import { TextX } from '../../text-x';
import { deleteSelectionTextX } from '../text-x-utils';
@@ -48,3 +48,68 @@ describe('deleteSelectionTextX structural expansion', () => {
expect(body.customRanges).toHaveLength(0);
});
});
+
+describe('empty paragraph formatting', () => {
+ function createListBody(): IDocumentBody {
+ return {
+ dataStream: 'R\rGB\r\n',
+ paragraphs: [
+ { startIndex: 1, paragraphId: 'red' },
+ { startIndex: 4, paragraphId: 'green', bullet: { listId: 'list', listType: 'BULLET_LIST', nestingLevel: 0 } },
+ ],
+ textRuns: [
+ { st: 0, ed: 2, ts: { cl: { rgb: '#ff0000' } } },
+ { st: 2, ed: 3, ts: { cl: { rgb: '#008000' }, fs: 20 } },
+ { st: 3, ed: 4, ts: { cl: { rgb: '#0000ff' }, fs: 16 } },
+ { st: 4, ed: 5, ts: { cl: { rgb: '#ff0000' }, bl: 1 } },
+ ],
+ };
+ }
+
+ it.each([false, true])('keeps the first character format on the surviving modern paragraph mark (list: %s)', (isList) => {
+ const body = createListBody();
+ if (!isList) {
+ delete body.paragraphs![1].bullet;
+ }
+ TextX.apply(body, deleteSelectionTextX([{ startOffset: 2, endOffset: 4, collapsed: false }], body, 0, null, false, DocumentFlavor.MODERN));
+ expect(body.dataStream).toBe('R\r\r\n');
+ expect(body.textRuns?.find((run) => run.st <= 2 && run.ed > 2)?.ts).toEqual({ cl: { rgb: '#008000' }, fs: 20 });
+ expect(body.textRuns?.every((run) => run.ed > run.st)).toBe(true);
+ expect(body.paragraphs?.[1].bullet).toEqual(isList ? { listId: 'list', listType: 'BULLET_LIST', nestingLevel: 0 } : undefined);
+ });
+
+ it.each(['traditional', 'partial deletion', 'replacement'])('preserves the existing mark for %s', (scenario) => {
+ const body = createListBody();
+ const endOffset = scenario === 'partial deletion' ? 3 : 4;
+ const insertBody = scenario === 'replacement' ? { dataStream: 'X' } : null;
+ TextX.apply(body, deleteSelectionTextX(
+ [{ startOffset: 2, endOffset, collapsed: false }],
+ body,
+ 0,
+ insertBody,
+ false,
+ scenario === 'traditional' ? DocumentFlavor.TRADITIONAL : DocumentFlavor.MODERN
+ ));
+ const mark = body.paragraphs![1].startIndex;
+ expect(body.textRuns?.find((run) => run.st <= mark && run.ed > mark)?.ts).toEqual({ cl: { rgb: '#ff0000' }, bl: 1 });
+ });
+
+ it.each([DocumentFlavor.MODERN, DocumentFlavor.TRADITIONAL])('restores paragraph identity when undoing deletion in %s', (flavor) => {
+ const body = createListBody();
+ const before = JSON.parse(JSON.stringify(body));
+ const actions = TextX.makeInvertible(deleteSelectionTextX([{ startOffset: 2, endOffset: 4, collapsed: false }], body, 0, null, true, flavor), body);
+ TextX.apply(body, actions);
+ TextX.apply(body, TextX.invert(actions));
+ expect(body).toMatchObject(before);
+ });
+
+ it('preserves explicit marker and paragraph-mark styles', () => {
+ const body = createListBody();
+ body.paragraphs![1].bullet!.textStyle = { cl: { rgb: '#0000ff' } };
+ body.paragraphs![1].paragraphStyle = { paragraphMarkTextStyle: { cl: { rgb: '#800080' } } };
+ TextX.apply(body, deleteSelectionTextX([{ startOffset: 2, endOffset: 4, collapsed: false }], body, 0, null, true, DocumentFlavor.MODERN));
+ expect(body.paragraphs![1].bullet?.textStyle).toEqual({ cl: { rgb: '#0000ff' } });
+ expect(body.paragraphs![1].paragraphStyle?.paragraphMarkTextStyle).toEqual({ cl: { rgb: '#800080' } });
+ expect(body.textRuns?.find((run) => run.st <= 2 && run.ed > 2)?.ts).toEqual({ cl: { rgb: '#ff0000' }, bl: 1 });
+ });
+});
diff --git a/packages/core/src/docs/data-model/text-x/build-utils/text-x-utils.ts b/packages/core/src/docs/data-model/text-x/build-utils/text-x-utils.ts
index 4c137689ff..37dfd69ae7 100644
--- a/packages/core/src/docs/data-model/text-x/build-utils/text-x-utils.ts
+++ b/packages/core/src/docs/data-model/text-x/build-utils/text-x-utils.ts
@@ -24,11 +24,13 @@ import type { TextXSelection } from '../text-x';
import type { IDocOperationalInterval } from './range-interval';
import fastDiff from 'fast-diff';
import { Tools, UpdateDocsAttributeType } from '../../../../shared';
+import { DocumentFlavor } from '../../../../types/interfaces/i-document-data';
import { DataStreamTreeTokenType } from '../../types';
import { TextXActionType } from '../action-types';
import { TextX } from '../text-x';
import { getBodySlice, getBodySliceForTextXAction, getTextRunSlice } from '../utils';
import { excludePointsFromRange, getIntersectingCustomRanges, getSelectionForAddCustomRange } from './custom-range';
+import { getParagraphContentStartOffset } from './paragraph';
import { getBlockRangeInterval, getColumnGroupRangeInterval, getCustomRangeInterval } from './range-interval';
export interface IDeleteCustomRangeParam {
@@ -581,7 +583,8 @@ export function deleteSelectionTextX(
body: IDocumentBody,
memoryCursor: number = 0,
insertBody: Nullable<IDocumentBody> = null,
- keepBullet: boolean = true
+ keepBullet: boolean = true,
+ documentFlavor?: DocumentFlavor
): Array<TextXAction> {
const normalizedSelections = normalizeSelectionsForStructuralSentinels(
[...selections].sort((a, b) => a.startOffset - b.startOffset),
@@ -612,6 +615,27 @@ export function deleteSelectionTextX(
});
cursor = endOffset;
}
+
+ // Keep an emptied modern paragraph's own formatting on its surviving
+ // mark so input and list markers stay stable after leaving or reopening.
+ const emptiedParagraph = documentFlavor === DocumentFlavor.MODERN && normalizedSelections.length === 1 && !insertBody && startOffset < endOffset
+ ? paragraphs.find((paragraph) => paragraph.startIndex === endOffset &&
+ getParagraphContentStartOffset(body, paragraph) === startOffset)
+ : undefined;
+ // An explicit mark also depends on its existing run for unspecified attributes.
+ if (emptiedParagraph && emptiedParagraph.paragraphStyle?.paragraphMarkTextStyle == null) {
+ const textStyle = body.textRuns?.find((run) => run.st <= startOffset && run.ed > startOffset)?.ts ?? {};
+ dos.push({
+ t: TextXActionType.RETAIN,
+ len: 1,
+ body: {
+ dataStream: '',
+ textRuns: [{ st: 0, ed: 1, ts: { ...textStyle } }],
+ },
+ coverType: UpdateDocsAttributeType.REPLACE,
+ });
+ cursor++;
+ }
});
if (insertBody) {
diff --git a/packages/core/src/docs/data-model/text-x/text-x.ts b/packages/core/src/docs/data-model/text-x/text-x.ts
index a07924e452..f4f9622e10 100644
--- a/packages/core/src/docs/data-model/text-x/text-x.ts
+++ b/packages/core/src/docs/data-model/text-x/text-x.ts
@@ -427,6 +427,26 @@ export class TextX {
}
}
+ // Text-only formatting must not recreate paragraph identities on undo.
+ if (action.body.paragraphs == null) {
+ delete body.paragraphs;
+ } else {
+ const previousParagraphs = new Map(body.paragraphs?.map((paragraph) => [paragraph.startIndex, paragraph]));
+ action.body.paragraphs = action.body.paragraphs.map((paragraph) => {
+ const previous = previousParagraphs.get(paragraph.startIndex);
+ if (!previous || (paragraph.paragraphId != null && paragraph.paragraphId !== previous.paragraphId)) {
+ return paragraph;
+ }
+
+ // Unchanged identities are not formatting intent. Keeping them in
+ // either direction would overwrite a concurrent split's new id.
+ const formatting = { ...paragraph };
+ Reflect.deleteProperty(formatting, 'paragraphId');
+ Reflect.deleteProperty(previous, 'paragraphId');
+ return formatting;
+ });
+ }
+
action.oldBody = {
...body,
dataStream: '',
diff --git a/packages/docs-ui/README.md b/packages/docs-ui/README.md
index 207700866a..0225b30140 100644
--- a/packages/docs-ui/README.md
+++ b/packages/docs-ui/README.md
@@ -34,6 +34,33 @@ univer.registerPlugin(UniverDocsUIPlugin);
// Merge EnUS into your Univer locale map when this package contributes UI text.
```
+## Format painter
+
+Use the shared Start ribbon format painter to copy character formatting. Include a paragraph
+mark in the source selection to also copy paragraph formatting and list formatting. Drag over
+a target selection or click a word to apply. Text, paragraph identities, and embedded entities
+are retained, and each application is undoable. The same text command serves embedded Shape
+text editors. The source format is captured when the brush is activated.
+The clear-formatting icon resets the selected text and paragraphs to default formatting,
+retains their content and identities, and supports undo.
+
+## Typing format at text boundaries
+
+Backspace in ordinary document text retains the removed character's formatting for immediate
+input. Forward Delete and Cut resolve formatting at the surviving caret. Replacing a text
+selection uses its first character's format, regardless of selection direction. In table cells,
+character-by-character Backspace resolves the surviving caret format; selection Backspace retains
+the first selected character's format.
+
+Retained typing format is transient and clears on explicit selection changes or document switches.
+Formatting commands such as Bold update this input format without clearing it.
+It is not serialized as an empty text run. Explicit `paragraphMarkTextStyle` remains authoritative
+after repositioning or reopening; deletion does not overwrite this explicit paragraph style.
+Modern paragraphs, including list items, retain their first character's formatting on the existing
+paragraph-ending character when all text is deleted. This keeps empty-paragraph input and list
+markers stable after editing elsewhere, undo/redo and reopening. Explicit list-marker and
+paragraph-mark style overrides retain their precedence.
+
## Resources
- [Documentation](https://docs.univer.ai)
diff --git a/packages/docs-ui/src/basics/__tests__/paragraph.spec.ts b/packages/docs-ui/src/basics/__tests__/paragraph.spec.ts
index da0988733a..40efe1406f 100644
--- a/packages/docs-ui/src/basics/__tests__/paragraph.spec.ts
+++ b/packages/docs-ui/src/basics/__tests__/paragraph.spec.ts
@@ -16,7 +16,7 @@
import { DataStreamTreeTokenType } from '@univerjs/core';
import { describe, expect, it } from 'vitest';
-import { getTextRunAtInputPosition, getTextRunAtPosition } from '../paragraph';
+import { getTextRunAtInputPosition, getTextRunAtPosition, getTextRunForSelection } from '../paragraph';
describe('getTextRunAtPosition', () => {
it.each(['i', ''])('inherits the first column paragraph style when inserting before %j', (text) => {
@@ -113,3 +113,42 @@ describe('getTextRunAtPosition', () => {
});
});
});
+
+describe('document insertion style boundaries', () => {
+ const red = { cl: { rgb: '#ff0000' }, fs: 14, bl: 1 as const };
+ const blue = { cl: { rgb: '#0000ff' }, fs: 20, it: 1 as const };
+ const green = { cl: { rgb: '#008000' }, fs: 26 };
+
+ it('replaces a mixed selection using its first character without changing caret or sheet editor affinity', () => {
+ const body = {
+ dataStream: '123456789\r\n',
+ textRuns: [{ st: 0, ed: 3, ts: red }, { st: 3, ed: 6, ts: blue }, { st: 6, ed: 9, ts: green }],
+ };
+ expect(getTextRunForSelection(body, { startOffset: 3, endOffset: 7 }, {}, null).ts).toEqual(blue);
+ expect(getTextRunForSelection(body, { startOffset: 2, endOffset: 5 }, {}, null).ts).toEqual(red);
+ expect(getTextRunForSelection(body, { startOffset: 3, endOffset: 3 }, {}, null).ts).toEqual(red);
+ expect(getTextRunForSelection(body, { startOffset: 3, endOffset: 7 }, {}, null, true).ts).toEqual(green);
+ });
+
+ it('uses a persisted empty paragraph mark while allowing a transient input override', () => {
+ const body = {
+ dataStream: 'A\r\rC\r\n',
+ textRuns: [{ st: 0, ed: 2, ts: red }, { st: 3, ed: 4, ts: red }],
+ paragraphs: [{ paragraphId: 'paragraph-1', startIndex: 1 }, { paragraphId: 'paragraph-2', startIndex: 2, paragraphStyle: { paragraphMarkTextStyle: green } }, { paragraphId: 'paragraph-4', startIndex: 4 }],
+ };
+ expect(getTextRunAtPosition(body, 2, {}, null).ts).toEqual(green);
+ expect(getTextRunAtPosition(body, 2, {}, blue).ts).toEqual(blue);
+ expect(getTextRunAtPosition(JSON.parse(JSON.stringify(body)), 2, {}, null).ts).toEqual(green);
+ expect(body.paragraphs[1].paragraphStyle?.paragraphMarkTextStyle).toEqual(green);
+ });
+
+ it('inherits the first character at a paragraph or table cell start instead of the preceding paragraph', () => {
+ const body = {
+ dataStream: 'A\rB\r\n',
+ textRuns: [{ st: 0, ed: 2, ts: red }, { st: 2, ed: 3, ts: blue }],
+ paragraphs: [{ paragraphId: 'paragraph-1', startIndex: 1 }, { paragraphId: 'paragraph-3', startIndex: 3 }],
+ };
+ expect(getTextRunAtPosition(body, 2, {}, null).ts).toEqual(blue);
+ expect(getTextRunAtPosition(body, 2, {}, null, true).ts).toEqual(red);
+ });
+});
diff --git a/packages/docs-ui/src/basics/paragraph.ts b/packages/docs-ui/src/basics/paragraph.ts
index 46c30e78ff..12de6964f4 100644
--- a/packages/docs-ui/src/basics/paragraph.ts
+++ b/packages/docs-ui/src/basics/paragraph.ts
@@ -20,11 +20,12 @@ import type {
ICustomTable,
IDocumentBody,
IParagraph,
+ ITextRange,
ITextRun,
ITextStyle,
Nullable,
} from '@univerjs/core';
-import { DataStreamTreeTokenType } from '@univerjs/core';
+import { DataStreamTreeTokenType, getParagraphContentStartOffset } from '@univerjs/core';
export function isTopLevelStructuralGap(dataStream: string, offset: number): boolean {
const previousToken = dataStream[offset - 1];
@@ -61,11 +62,16 @@ export function getTextRunAtPosition(
return retTextRun;
}
+ const paragraph = !isCellEditor ? body.paragraphs?.find((item) => item.startIndex >= position) : undefined;
+ const atParagraphStart = paragraph && getParagraphContentStartOffset(body, paragraph) === position;
+ // At a paragraph start, inherit its first character/mark instead of the preceding paragraph.
+ const samplePosition = atParagraphStart || position === 0 ? position + 1 : position;
+
for (let i = textRuns.length - 1; i >= 0; i--) {
const textRun = textRuns[i];
const { st, ed } = textRun;
- if (position > st && position <= ed) {
+ if (samplePosition > st && samplePosition <= ed) {
retTextRun.st = st;
retTextRun.ed = ed;
@@ -76,14 +82,13 @@ export function getTextRunAtPosition(
}
}
- if (position === 0) {
- const textRun = textRuns?.[0];
- if (textRun && textRun.st === 0) {
- retTextRun.ts = {
- ...retTextRun.ts,
- ...textRun.ts,
- };
- }
+ if (atParagraphStart && paragraph.startIndex === position) {
+ retTextRun.ts = {
+ ...(!defaultStyle.cl ? {} : { cl: { ...defaultStyle.cl } }),
+ ...paragraph.paragraphStyle?.textStyle,
+ ...textRuns.find((run) => run.st <= position && run.ed > position)?.ts,
+ ...paragraph.paragraphStyle?.paragraphMarkTextStyle,
+ };
}
if (cacheStyle) {
@@ -128,6 +133,19 @@ export function getTextRunAtInputPosition(
};
}
+/** Replacing a selection uses its first character; a caret normally uses its left neighbor. */
+export function getTextRunForSelection(
+ body: IDocumentBody,
+ range: Pick<ITextRange, 'startOffset' | 'endOffset'>,
+ defaultStyle: ITextStyle,
+ cacheStyle: Nullable<ITextStyle>,
+ isCellEditor?: boolean,
+ inheritParagraphStartStyle = false
+): ITextRun {
+ const position = !isCellEditor && range.startOffset !== range.endOffset ? range.startOffset + 1 : range.endOffset;
+ return getTextRunAtInputPosition(body, position, defaultStyle, cacheStyle, isCellEditor, inheritParagraphStartStyle);
+}
+
export function getCustomRangeAtPosition(customRanges: ICustomRange[], position: number, extendRange?: boolean) {
if (extendRange) {
const range = customRanges.find((customRange) => position >= customRange.startIndex && position <= customRange.endIndex + 1);
diff --git a/packages/docs-ui/src/commands/commands/__tests__/format-painter.command.spec.ts b/packages/docs-ui/src/commands/commands/__tests__/format-painter.command.spec.ts
new file mode 100644
index 0000000000..0b7e9619c8
--- /dev/null
+++ b/packages/docs-ui/src/commands/commands/__tests__/format-painter.command.spec.ts
@@ -0,0 +1,205 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { ICommand, IDocumentBody, IDocumentData, IListData } from '@univerjs/core';
+import {
+ BooleanNumber,
+ BulletAlignment,
+ DocStyleType,
+ HorizontalAlign,
+ ICommandService,
+ NamedStyleType,
+ RedoCommand,
+ Tools,
+ UndoCommand,
+} from '@univerjs/core';
+import { RichTextEditingMutation, SetTextSelectionsOperation } from '@univerjs/docs';
+import { describe, expect, it, vi } from 'vitest';
+import { ApplyTextFormatPainterCommand, captureTextFormat } from '../format-painter.command';
+import { createCommandTestBed } from './create-command-test-bed';
+
+const body = {
+ dataStream: 'source\rtarget\r\n',
+ customRanges: [],
+ customDecorations: [],
+ textRuns: [{ st: 0, ed: 6, ts: { fs: 24 } }, { st: 7, ed: 13, ts: { fs: 10, bl: BooleanNumber.TRUE } }],
+ paragraphs: [
+ { startIndex: 6, paragraphId: 'para_source', paragraphStyle: { horizontalAlign: HorizontalAlign.CENTER } },
+ { startIndex: 13, paragraphId: 'para_target', bullet: { listId: 'target-list', listType: 'ORDER_LIST', nestingLevel: 0 }, paragraphStyle: { horizontalAlign: HorizontalAlign.RIGHT } },
+ ],
+};
+
+describe('text format painter', () => {
+ it('takes paragraph formatting only when the paragraph mark is included and detaches the sample', () => {
+ const source = Tools.deepClone(body);
+ const character = captureTextFormat(source, { startOffset: 0, endOffset: 6 });
+ expect(character.paragraphStyle).toBeUndefined();
+ expect(captureTextFormat(source, { startOffset: 0, endOffset: 7 }).paragraphStyle?.horizontalAlign).toBe(HorizontalAlign.CENTER);
+ source.textRuns[0].ts.fs = 99;
+ expect(character.textStyle.fs).toBe(24);
+ });
+
+ it('samples rendered heading and imported paragraph styles, with direct formatting taking precedence', () => {
+ const source: IDocumentBody = Tools.deepClone(body);
+ source.textRuns = [{ st: 0, ed: 6, ts: { it: BooleanNumber.TRUE } }];
+ source.paragraphs![0].paragraphStyle = { namedStyleType: NamedStyleType.HEADING_1 };
+ expect(captureTextFormat(source, { startOffset: 0, endOffset: 6 }).textStyle).toMatchObject({ fs: 20, bl: BooleanNumber.TRUE, it: BooleanNumber.TRUE });
+ source.paragraphs![0].styleId = 'heading';
+ const document: IDocumentData = {
+ id: 'source',
+ documentStyle: { textStyle: { ff: 'Georgia' } },
+ styles: {
+ base: { name: 'Base', type: DocStyleType.paragraph, paragraphStyle: { spaceAbove: { v: 10 } } },
+ heading: { name: 'Heading', type: DocStyleType.paragraph, basedOn: 'base', paragraphStyle: { textStyle: { fs: 30, bl: BooleanNumber.FALSE } } },
+ },
+ };
+ const format = captureTextFormat(source, { startOffset: 0, endOffset: 7 }, {}, {}, document);
+ expect(format.textStyle).toMatchObject({ ff: 'Georgia', fs: 30, bl: BooleanNumber.FALSE, it: BooleanNumber.TRUE });
+ expect(format.paragraphStyle?.spaceAbove).toEqual({ v: 10 });
+ });
+
+ it('clears inherited target emphasis and paragraph style references while retaining identity and undo', async () => {
+ const source: IDocumentBody = Tools.deepClone(body);
+ source.paragraphs![1].styleId = 'heading';
+ const bed = createCommandTestBed({
+ id: 'test-doc',
+ body: source,
+ documentStyle: {},
+ styles: { heading: { name: 'Heading', type: DocStyleType.paragraph, paragraphStyle: { textStyle: { bl: BooleanNumber.TRUE, it: BooleanNumber.TRUE } } } },
+ });
+ const commands = bed.get(ICommandService);
+ [ApplyTextFormatPainterCommand, RichTextEditingMutation, SetTextSelectionsOperation].forEach((command) => commands.registerCommand(command as ICommand));
+ const before = Tools.deepClone(bed.doc.getSnapshot());
+ try {
+ expect(await commands.executeCommand(ApplyTextFormatPainterCommand.id, {
+ unitId: 'test-doc',
+ ranges: [{ startOffset: 7, endOffset: 13 }],
+ format: captureTextFormat(body, { startOffset: 0, endOffset: 6 }),
+ })).toBe(true);
+ const character = captureTextFormat(bed.doc.getBody()!, { startOffset: 7, endOffset: 13 }, {}, {}, bed.doc.getSnapshot());
+ expect(character.textStyle).toMatchObject({ fs: 24, bl: BooleanNumber.FALSE, it: BooleanNumber.FALSE });
+ expect(bed.doc.getBody()?.paragraphs?.[1].styleId).toBe('heading');
+ await commands.executeCommand(UndoCommand.id);
+ expect(bed.doc.getSnapshot()).toEqual(before);
+ expect(await commands.executeCommand(ApplyTextFormatPainterCommand.id, {
+ unitId: 'test-doc',
+ ranges: [{ startOffset: 7, endOffset: 14 }],
+ format: captureTextFormat(body, { startOffset: 0, endOffset: 7 }),
+ })).toBe(true);
+ expect(bed.doc.getBody()?.paragraphs?.[1].styleId).toBeUndefined();
+ expect(bed.doc.getBody()?.paragraphs?.[1].paragraphId).toBe(before.body?.paragraphs?.[1].paragraphId);
+ await commands.executeCommand(UndoCommand.id);
+ expect(bed.doc.getSnapshot()).toEqual(before);
+ } finally {
+ bed.univer.dispose();
+ }
+ });
+
+ it('paints a clicked word on browsers without Intl.Segmenter', async () => {
+ const segmenter = Intl.Segmenter;
+ vi.stubGlobal('Intl', new Proxy(Intl, { get: (target, property) => property === 'Segmenter' ? undefined : Reflect.get(target, property) }));
+ const bed = createCommandTestBed({ id: 'test-doc', body: Tools.deepClone(body), documentStyle: {} });
+ const commands = bed.get(ICommandService);
+ [ApplyTextFormatPainterCommand, RichTextEditingMutation, SetTextSelectionsOperation].forEach((command) => commands.registerCommand(command as ICommand));
+ try {
+ expect(await commands.executeCommand(ApplyTextFormatPainterCommand.id, {
+ unitId: 'test-doc',
+ ranges: [{ startOffset: 9, endOffset: 9 }],
+ format: { textStyle: { fs: 24 } },
+ })).toBe(true);
+ expect(bed.doc.getBody()?.textRuns?.find((run) => run.st === 7)).toMatchObject({ st: 7, ed: 13, ts: { fs: 24 } });
+ expect(bed.doc.getBody()?.dataStream).toBe(body.dataStream);
+ } finally {
+ bed.univer.dispose();
+ vi.unstubAllGlobals();
+ }
+ expect(Intl.Segmenter).toBe(segmenter);
+ });
+
+ it('clears character and paragraph formatting while retaining content and supporting undo', async () => {
+ const bed = createCommandTestBed({ id: 'test-doc', body: Tools.deepClone(body), documentStyle: {} });
+ const commands = bed.get(ICommandService);
+ [ApplyTextFormatPainterCommand, RichTextEditingMutation, SetTextSelectionsOperation].forEach((command) => commands.registerCommand(command as ICommand));
+ const before = Tools.deepClone(bed.doc.getSnapshot());
+ try {
+ const format = captureTextFormat({ dataStream: '' }, { startOffset: 0, endOffset: 0 });
+ expect(await commands.executeCommand(ApplyTextFormatPainterCommand.id, {
+ unitId: 'test-doc',
+ ranges: [{ startOffset: 7, endOffset: 14 }],
+ format: { ...format, paragraphStyle: {} },
+ })).toBe(true);
+ expect(bed.doc.getBody()?.dataStream).toBe(body.dataStream);
+ expect(bed.doc.getBody()?.textRuns?.find((run) => run.st === 7)?.ts).toMatchObject({ fs: 11, bl: BooleanNumber.FALSE });
+ expect(bed.doc.getBody()?.paragraphs?.[1].paragraphStyle).toEqual({});
+ expect(bed.doc.getBody()?.paragraphs?.[1].bullet).toBeUndefined();
+ await commands.executeCommand(UndoCommand.id);
+ expect(bed.doc.getSnapshot()).toEqual(before);
+ } finally {
+ bed.univer.dispose();
+ }
+ });
+
+ it('copies a custom list definition without overwriting an existing definition and undoes both changes', async () => {
+ const originalList: IListData = { listType: 'custom', nestingLevel: [{ bulletAlignment: BulletAlignment.START, glyphFormat: 'old', startNumber: 0 }] };
+ const copiedList: IListData = { listType: 'custom', nestingLevel: [{ bulletAlignment: BulletAlignment.START, glyphFormat: 'new', startNumber: 0 }] };
+ const bed = createCommandTestBed({ id: 'test-doc', body: Tools.deepClone(body), lists: { custom: originalList }, documentStyle: {} });
+ const commands = bed.get(ICommandService);
+ [ApplyTextFormatPainterCommand, RichTextEditingMutation, SetTextSelectionsOperation].forEach((command) => commands.registerCommand(command as ICommand));
+ const before = Tools.deepClone(bed.doc.getSnapshot());
+ try {
+ expect(await commands.executeCommand(ApplyTextFormatPainterCommand.id, {
+ unitId: 'test-doc',
+ ranges: [{ startOffset: 7, endOffset: 14 }],
+ format: { textStyle: { fs: 24 }, paragraphStyle: {}, bullet: { listId: 'source-list', listType: 'custom', nestingLevel: 0 }, listDefinition: copiedList },
+ })).toBe(true);
+ const listType = bed.doc.getBody()?.paragraphs?.[1].bullet?.listType;
+ expect(listType).not.toBe('custom');
+ expect(bed.doc.getSnapshot().lists?.custom).toEqual(originalList);
+ expect(bed.doc.getSnapshot().lists?.[listType!].nestingLevel[0].glyphFormat).toBe('new');
+ await commands.executeCommand(UndoCommand.id);
+ expect(bed.doc.getSnapshot()).toEqual(before);
+ } finally {
+ bed.univer.dispose();
+ }
+ });
+
+ it('replaces formatting without changing text or paragraph identity, and supports undo/redo', async () => {
+ const bed = createCommandTestBed({ id: 'test-doc', body: Tools.deepClone(body), documentStyle: {} });
+ const commands = bed.get(ICommandService);
+ [ApplyTextFormatPainterCommand, RichTextEditingMutation, SetTextSelectionsOperation].forEach((command) => commands.registerCommand(command as ICommand));
+ const before = Tools.deepClone(bed.doc.getSnapshot());
+ try {
+ expect(await commands.executeCommand(ApplyTextFormatPainterCommand.id, {
+ unitId: 'test-doc',
+ ranges: [{ startOffset: 7, endOffset: 14 }],
+ format: captureTextFormat(body, { startOffset: 0, endOffset: 7 }),
+ })).toBe(true);
+ expect(bed.doc.getBody()?.dataStream).toBe(body.dataStream);
+ const run = bed.doc.getBody()?.textRuns?.find((item) => item.st <= 7 && item.ed > 7);
+ expect(run?.ts?.fs).toBe(24);
+ expect(run?.ts?.bl).toBe(BooleanNumber.FALSE);
+ expect(bed.doc.getBody()?.paragraphs?.[1]).toMatchObject({ paragraphId: before.body?.paragraphs?.[1].paragraphId, paragraphStyle: { horizontalAlign: HorizontalAlign.CENTER } });
+ expect(bed.doc.getBody()?.paragraphs?.[1].bullet).toBeUndefined();
+ const after = Tools.deepClone(bed.doc.getSnapshot());
+ await commands.executeCommand(UndoCommand.id);
+ expect(bed.doc.getSnapshot()).toEqual(before);
+ await commands.executeCommand(RedoCommand.id);
+ expect(bed.doc.getSnapshot()).toEqual(after);
+ } finally {
+ bed.univer.dispose();
+ }
+ });
+});
diff --git a/packages/docs-ui/src/commands/commands/__tests__/ime-input.command.spec.ts b/packages/docs-ui/src/commands/commands/__tests__/ime-input.command.spec.ts
index e90f1f9cf2..3beb7e35bc 100644
--- a/packages/docs-ui/src/commands/commands/__tests__/ime-input.command.spec.ts
+++ b/packages/docs-ui/src/commands/commands/__tests__/ime-input.command.spec.ts
@@ -90,3 +90,43 @@ describe('IME composition range preservation', () => {
}
});
});
+
+describe('IME selection typing style', () => {
+ it('uses the first selected style throughout a mixed-style composition', async () => {
+ const bed = createCommandTestBed({
+ id: 'ime-style',
+ documentStyle: {},
+ body: {
+ dataStream: '123456789\r\n',
+ paragraphs: [{ paragraphId: 'paragraph-9', startIndex: 9 }],
+ textRuns: [
+ { st: 0, ed: 3, ts: { cl: { rgb: '#ff0000' }, bl: 1 } },
+ { st: 3, ed: 6, ts: { cl: { rgb: '#0000ff' }, fs: 20, it: 1 } },
+ { st: 6, ed: 9, ts: { cl: { rgb: '#008000' }, st: { s: 1 } } },
+ ],
+ },
+ });
+ try {
+ const commands = bed.get(ICommandService);
+ commands.registerCommand(IMEInputCommand);
+ commands.registerCommand(RichTextEditingMutation);
+ const ime = bed.get(DocIMEInputManagerService);
+ ime.setActiveRange({ startOffset: 3, endOffset: 7, collapsed: false, segmentId: '' });
+ for (const [index, newText] of ['中', '中文'].entries()) {
+ expect(await commands.executeCommand(IMEInputCommand.id, {
+ unitId: bed.doc.getUnitId(),
+ newText,
+ oldTextLen: index,
+ isCompositionStart: index === 0,
+ isCompositionEnd: index === 1,
+ })).toBe(true);
+ const body = bed.doc.getBody()!;
+ expect(body.dataStream).toBe(`123${newText}89\r\n`);
+ expect(body.textRuns?.find((run) => run.st <= 3 && run.ed > 3)?.ts)
+ .toEqual({ cl: { rgb: '#0000ff' }, fs: 20, it: 1 });
+ }
+ } finally {
+ bed.univer.dispose();
+ }
+ });
+});
diff --git a/packages/docs-ui/src/commands/commands/__tests__/inline-format.command.spec.ts b/packages/docs-ui/src/commands/commands/__tests__/inline-format.command.spec.ts
index 956464a6dd..01c608e039 100644
--- a/packages/docs-ui/src/commands/commands/__tests__/inline-format.command.spec.ts
+++ b/packages/docs-ui/src/commands/commands/__tests__/inline-format.command.spec.ts
@@ -30,6 +30,7 @@ import {
} from '@univerjs/core';
import { DocSelectionManagerService, RichTextEditingMutation, SetTextSelectionsOperation } from '@univerjs/docs';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { DocMenuStyleService } from '../../../services/doc-menu-style.service';
import {
getStyleInTextRange,
ResetInlineFormatTextBackgroundColorCommand,
@@ -50,6 +51,19 @@ import {
import { createCommandTestBed } from './create-command-test-bed';
describe('getStyleInTextRange', () => {
+ it('reports the empty paragraph mark style instead of the preceding paragraph in the toolbar', () => {
+ const body: IDocumentBody = {
+ dataStream: 'A\r\r\n',
+ textRuns: [{ st: 0, ed: 2, ts: { cl: { rgb: '#ff0000' }, fs: 14, bl: 1 } }],
+ paragraphs: [
+ { paragraphId: 'first', startIndex: 1 },
+ { paragraphId: 'empty', startIndex: 2, paragraphStyle: { paragraphMarkTextStyle: { cl: { rgb: '#008000' }, fs: 26 } } },
+ ],
+ };
+ expect(getStyleInTextRange(body, { startOffset: 2, endOffset: 2, collapsed: true }, {}))
+ .toEqual({ cl: { rgb: '#008000' }, fs: 26 });
+ });
+
it('reads an expanded selection without cloning unrelated text runs', () => {
const body = {
dataStream: 'x'.repeat(10_000),
@@ -220,6 +234,32 @@ describe('Test inline format commands', () => {
});
});
+ it('keeps retained typing style when toggling bold at a collapsed caret without a document mutation', async () => {
+ const selections = get(DocSelectionManagerService);
+ selections.replaceSelectionInfoWithoutRefresh({
+ ...selections.getSelectionInfo()!,
+ textRanges: [{ startOffset: 3, endOffset: 3, collapsed: true, isActive: true }],
+ rectRanges: [],
+ });
+ const menuStyle = get(DocMenuStyleService);
+ const retainedStyle = { cl: { rgb: '#0000ff' }, fs: 20, bl: 0 as const, it: 1 as const, ul: { s: 1 as const } };
+ menuStyle.setStyleCache(retainedStyle);
+ const mutations: string[] = [];
+ const listener = commandService.onCommandExecuted((command) => {
+ if (command.id === RichTextEditingMutation.id) mutations.push(command.id);
+ });
+
+ try {
+ expect(await commandService.executeCommand(SetInlineFormatBoldCommand.id)).toBe(true);
+ expect(menuStyle.getStyleCache()).toEqual({ ...retainedStyle, bl: 1 });
+ expect(await commandService.executeCommand(SetInlineFormatBoldCommand.id)).toBe(true);
+ expect(menuStyle.getStyleCache()).toEqual(retainedStyle);
+ expect(mutations).toEqual([]);
+ } finally {
+ listener.dispose();
+ }
+ });
+
describe('Set Bold by SetInlineFormatCommand', () => {
it('Should change text in range(0, 5) to bold', async () => {
expect(getFormatValueAt('bl', 1)).toBe(BooleanNumber.FALSE);
diff --git a/packages/docs-ui/src/commands/commands/clipboard.inner.command.ts b/packages/docs-ui/src/commands/commands/clipboard.inner.command.ts
index bbbb82058b..013e28abb7 100644
--- a/packages/docs-ui/src/commands/commands/clipboard.inner.command.ts
+++ b/packages/docs-ui/src/commands/commands/clipboard.inner.command.ts
@@ -478,7 +478,14 @@ function getCutActionsFromTextRanges(
const { tables = [] } = originBody;
const adjustedSelections = selections.map((selection) => adjustSelectionByTable(selection, tables));
- textX.push(...BuildTextUtils.selection.delete(adjustedSelections, originBody, 0, null, false));
+ textX.push(...BuildTextUtils.selection.delete(
+ adjustedSelections,
+ originBody,
+ 0,
+ null,
+ false,
+ docDataModel.getDocumentStyle().documentFlavor
+ ));
const path = getRichTextEditPath(docDataModel, segmentId);
rawActions.push(jsonX.editOp(textX.serialize(), path)!);
diff --git a/packages/docs-ui/src/commands/commands/doc-delete.command.ts b/packages/docs-ui/src/commands/commands/doc-delete.command.ts
index 193b1bae42..18bf000205 100644
--- a/packages/docs-ui/src/commands/commands/doc-delete.command.ts
+++ b/packages/docs-ui/src/commands/commands/doc-delete.command.ts
@@ -14,8 +14,25 @@
* limitations under the License.
*/
-import type { DocumentDataModel, IAccessor, ICommand, IDocumentBlockRange, IDocumentBody, IMultiCommand, IMutationInfo, IParagraph, ITextRange, JSONXActions, Nullable } from '@univerjs/core';
-import type { IDeleteTextCommandParams, IRichTextEditingMutationParams, IUpdateTextCommandParams } from '@univerjs/docs';
+import type {
+ DocumentDataModel,
+ IAccessor,
+ ICommand,
+ IDocumentBlockRange,
+ IDocumentBody,
+ IMultiCommand,
+ IMutationInfo,
+ IParagraph,
+ ITextRange,
+ ITextStyle,
+ JSONXActions,
+ Nullable,
+} from '@univerjs/core';
+import type {
+ IDeleteTextCommandParams,
+ IRichTextEditingMutationParams,
+ IUpdateTextCommandParams,
+} from '@univerjs/docs';
import type { IRectRangeWithStyle, ITextRangeWithStyle } from '@univerjs/engine-render';
import {
BlockType,
@@ -48,10 +65,12 @@ import {
} from '@univerjs/docs';
import { getParagraphByGlyph, hasListGlyph, isFirstGlyph, isIndentByGlyph } from '@univerjs/engine-render';
import { DocAutoFormatService } from '../../services/doc-auto-format.service';
+import { DocMenuStyleService } from '../../services/doc-menu-style.service';
import { IEditorService } from '../../services/editor/editor-manager.service';
import { isHorizontalLineParagraph } from '../../utils/horizontal-line';
import { getCommandSkeleton } from '../util';
import { CutContentCommand } from './clipboard.inner.command';
+import { captureTextFormat } from './format-painter.command';
import { getCurrentParagraph } from './util';
export interface IDeleteCustomBlockParams {
@@ -483,6 +502,8 @@ export const DeleteLeftCommand: ICommand = {
return false;
}
+ const originalLength = body.dataStream.length;
+ const typingStyle = captureDeletedTypingStyle(accessor, docDataModel, body, activeRange);
const actualRange = activeRange;
const { startOffset, collapsed } = actualRange;
if (collapsed && shouldResetEmptyCenteredParagraphAlignment(accessor, docDataModel)) {
@@ -653,6 +674,9 @@ export const DeleteLeftCommand: ICommand = {
}
}
+ if (result && typingStyle && docDataModel.getSelfOrHeaderFooterModel(segmentId)?.getBody()?.dataStream.length !== originalLength) {
+ accessor.get(DocMenuStyleService).setStyleCache(typingStyle);
+ }
return result;
},
};
@@ -798,6 +822,35 @@ export const DeleteRightCommand: ICommand = {
},
};
+/** Preserve input formatting when deleting the final character of a run or paragraph. */
+function captureDeletedTypingStyle(
+ accessor: IAccessor,
+ document: DocumentDataModel,
+ body: IDocumentBody,
+ range: ITextRangeWithStyle
+): ITextStyle | undefined {
+ if (!accessor.has(DocMenuStyleService) || SHEET_EDITOR_UNITS.includes(document.getUnitId())) {
+ return;
+ }
+ // Word resolves the surviving caret style for character-by-character deletion in tables.
+ // Selection Backspace still retains the first selected character's style.
+ if (range.collapsed && body.tables?.some((table) => range.startOffset > table.startIndex && range.startOffset <= table.endIndex)) {
+ return;
+ }
+ const offset = range.collapsed ? range.startOffset - 1 : range.startOffset;
+ // Paragraph merging, drawing removal and structural tokens have their own semantics.
+ if (offset < 0 || !body.dataStream[offset] || body.dataStream.charCodeAt(offset) < 32) {
+ return;
+ }
+ const service = accessor.get(DocMenuStyleService);
+ const snapshot = document.getSnapshot();
+ const style = captureTextFormat(body, { startOffset: offset, endOffset: offset + 1 }, service.getDefaultStyle(), snapshot.lists, snapshot).textStyle;
+ const previousStyle = body.textRuns?.find((run) => run.st < offset && run.ed >= offset)?.ts;
+ // Undefined properties deliberately mask formatting inherited from the surviving left run.
+ const resetStyle = Object.fromEntries(Object.keys(previousStyle ?? {}).map((key) => [key, undefined]));
+ return { ...resetStyle, ...style };
+}
+
async function executeDeleteAutoFormat(accessor: IAccessor, commandId: string): Promise<boolean | null> {
if (!accessor.has(DocAutoFormatService)) {
return null;
diff --git a/packages/docs-ui/src/commands/commands/format-painter.command.ts b/packages/docs-ui/src/commands/commands/format-painter.command.ts
new file mode 100644
index 0000000000..23c79ebe07
--- /dev/null
+++ b/packages/docs-ui/src/commands/commands/format-painter.command.ts
@@ -0,0 +1,236 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type {
+ DocumentDataModel,
+ IBullet,
+ ICommand,
+ IDocumentBody,
+ IDocumentData,
+ IListData,
+ IParagraph,
+ IParagraphStyle,
+ ITextRangeParam,
+ ITextStyle,
+} from '@univerjs/core';
+import type { IRichTextEditingMutationParams } from '@univerjs/docs';
+import {
+ BaselineOffset,
+ BooleanNumber,
+ CommandType,
+ DEFAULT_STYLES,
+ generateRandomId,
+ getRichTextEditPath,
+ ICommandService,
+ IUniverInstanceService,
+ JSONX,
+ NAMED_STYLE_MAP,
+ resolveDocumentParagraphStyle,
+ TextX,
+ TextXActionType,
+ Tools,
+ UniverInstanceType,
+ UpdateDocsAttributeType,
+} from '@univerjs/core';
+import { RichTextEditingMutation } from '@univerjs/docs';
+import { getWordBoundaryByIndex } from '../../services/selection/word-boundary';
+
+export interface ITextFormatPainterSnapshot {
+ textStyle: ITextStyle;
+ paragraphStyle?: IParagraphStyle;
+ bullet?: IBullet;
+ listDefinition?: IListData;
+}
+
+export function captureTextFormat(
+ body: IDocumentBody,
+ range: Pick<ITextRangeParam, 'startOffset' | 'endOffset'>,
+ defaultStyle: ITextStyle = {},
+ lists: Record<string, IListData> = {},
+ document: Pick<IDocumentData, 'documentStyle' | 'styles'> = { documentStyle: {} }
+): ITextFormatPainterSnapshot {
+ const offset = range.startOffset === range.endOffset ? Math.max(0, range.startOffset - 1) : range.startOffset;
+ const paragraph = body.paragraphs?.find((item) => item.startIndex >= offset);
+ const paragraphStyle = resolveDocumentParagraphStyle(document.documentStyle, paragraph?.paragraphStyle, {
+ styles: document.styles,
+ paragraphStyleId: paragraph?.styleId,
+ });
+ const includesParagraphMark = paragraph && paragraph.startIndex >= range.startOffset && paragraph.startIndex < range.endOffset;
+ return Tools.deepClone({
+ // Explicit normal values prevent the target paragraph's inherited emphasis from leaking through.
+ textStyle: {
+ ff: DEFAULT_STYLES.ff,
+ fs: DEFAULT_STYLES.fs,
+ cl: DEFAULT_STYLES.cl,
+ bl: BooleanNumber.FALSE,
+ it: BooleanNumber.FALSE,
+ ul: { s: BooleanNumber.FALSE },
+ st: { s: BooleanNumber.FALSE },
+ ol: { s: BooleanNumber.FALSE },
+ va: BaselineOffset.NORMAL,
+ bg: null,
+ caps: false,
+ smallCaps: false,
+ ...document.documentStyle?.textStyle,
+ ...defaultStyle,
+ ...getParagraphTextFormat(body, paragraph, paragraphStyle, offset, lists),
+ },
+ ...(includesParagraphMark ? { paragraphStyle, bullet: paragraph.bullet, listDefinition: paragraph.bullet ? lists[paragraph.bullet.listType] : undefined } : {}),
+ });
+}
+
+function getParagraphTextFormat(
+ body: IDocumentBody,
+ paragraph: IParagraph | undefined,
+ paragraphStyle: IParagraphStyle,
+ offset: number,
+ lists: Record<string, IListData>
+): ITextStyle {
+ const run = body.textRuns?.find((item) => item.st <= offset && item.ed > offset);
+ const namedStyle = paragraphStyle.namedStyleType && !paragraph?.styleId ? NAMED_STYLE_MAP[paragraphStyle.namedStyleType] : null;
+ return {
+ ...namedStyle,
+ ...paragraphStyle.textStyle,
+ ...run?.ts,
+ ...(offset === paragraph?.startIndex ? paragraphStyle.paragraphMarkTextStyle : undefined),
+ ...(paragraph?.bullet ? lists[paragraph.bullet.listType]?.nestingLevel?.[0]?.paragraphProperties?.textStyle : undefined),
+ };
+}
+
+/** Replace formatting only, preserving text, entity markers and paragraph identities. */
+export function buildTextFormatActions(body: IDocumentBody, ranges: ITextRangeParam[], format: ITextFormatPainterSnapshot): TextX {
+ const textX = new TextX();
+ let cursor = 0;
+ for (const range of [...ranges].sort((a, b) => a.startOffset - b.startOffset)) {
+ const start = Math.max(cursor, range.startOffset);
+ const end = Math.min(body.dataStream.length - 1, range.endOffset);
+ if (start >= end) {
+ continue;
+ }
+ if (start > cursor) {
+ textX.push({ t: TextXActionType.RETAIN, len: start - cursor });
+ }
+ textX.push({
+ t: TextXActionType.RETAIN,
+ len: end - start,
+ coverType: UpdateDocsAttributeType.REPLACE,
+ body: {
+ dataStream: '',
+ textRuns: [{ st: 0, ed: end - start, ts: Tools.deepClone(format.textStyle) }],
+
+ },
+ });
+ cursor = end;
+ }
+ if (format.paragraphStyle === undefined) {
+ return textX;
+ }
+ const paragraphs = new TextX();
+ let paragraphStart = 0;
+ let paragraphCursor = 0;
+ for (const paragraph of body.paragraphs ?? []) {
+ const end = paragraph.startIndex + 1;
+ if (ranges.some((range) => range.startOffset < end && range.endOffset > paragraphStart)) {
+ if (paragraph.startIndex > paragraphCursor) {
+ paragraphs.push({ t: TextXActionType.RETAIN, len: paragraph.startIndex - paragraphCursor });
+ }
+ paragraphs.push({
+ t: TextXActionType.RETAIN,
+ len: 1,
+ coverType: UpdateDocsAttributeType.REPLACE,
+ body: { dataStream: '', paragraphs: [{
+ ...Tools.deepClone(paragraph),
+ startIndex: 0,
+ styleId: undefined,
+ paragraphStyle: Tools.deepClone(format.paragraphStyle),
+ bullet: Tools.deepClone(format.bullet),
+ }] },
+ });
+ paragraphCursor = end;
+ }
+ paragraphStart = end;
+ }
+ const result = new TextX();
+ const composed = TextX.compose(textX.serialize(), paragraphs.serialize());
+ if (composed.length) {
+ result.push(...composed);
+ }
+ return result;
+}
+
+function getPainterWordRange(content: string, offset: number): Pick<ITextRangeParam, 'startOffset' | 'endOffset'> | null {
+ if (typeof Intl.Segmenter === 'function') {
+ return getWordBoundaryByIndex(content, offset, 0) ?? getWordBoundaryByIndex(content, offset - 1, 0);
+ }
+ // Safari 14.1 and Firefox 90 do not provide Intl.Segmenter.
+ for (const match of content.matchAll(/[\p{L}\p{N}\p{M}_]+/gu)) {
+ const startOffset = match.index!;
+ const endOffset = startOffset + match[0].length;
+ if (offset >= startOffset && offset <= endOffset) {
+ return { startOffset, endOffset };
+ }
+ }
+ return null;
+}
+
+interface IApplyTextFormatPainterCommandParams {
+ unitId: string;
+ ranges: ITextRangeParam[];
+ format: ITextFormatPainterSnapshot;
+}
+
+export const ApplyTextFormatPainterCommand: ICommand<IApplyTextFormatPainterCommandParams> = {
+ id: 'doc.command.apply-format-painter',
+ type: CommandType.COMMAND,
+ handler: (accessor, params) => {
+ if (!params || params.ranges.length === 0) {
+ return false;
+ }
+ const model = accessor.get(IUniverInstanceService).getUnit<DocumentDataModel>(params.unitId, UniverInstanceType.UNIVER_DOC);
+ const segmentId = params.ranges[0].segmentId;
+ const body = model?.getSelfOrHeaderFooterModel(segmentId)?.getBody();
+ if (!model || !body || params.ranges.some((range) => range.segmentId !== segmentId)) {
+ return false;
+ }
+ const ranges = params.ranges.map((range) => {
+ if (range.startOffset !== range.endOffset) {
+ return range;
+ }
+ const word = getPainterWordRange(body.dataStream, range.startOffset);
+ return word ? { ...range, ...word, collapsed: false } : range;
+ });
+ const format = Tools.deepClone(params.format);
+ const jsonX = JSONX.getInstance();
+ const previousLists = model.getSnapshot().lists;
+ let listAction = null;
+ if (format.bullet && format.listDefinition && !Tools.diffValue(previousLists?.[format.bullet.listType], format.listDefinition)) {
+ const listType = `format-painter-${generateRandomId(8)}`;
+ format.bullet.listType = listType;
+ const lists = { ...previousLists, [listType]: { ...format.listDefinition, listType } };
+ listAction = previousLists ? jsonX.replaceOp(['lists'], previousLists, lists) : jsonX.insertOp(['lists'], lists);
+ }
+ const actions = buildTextFormatActions(body, ranges, format).serialize();
+ if (!actions.length) {
+ return false;
+ }
+ const textAction = jsonX.editOp(actions, getRichTextEditPath(model, segmentId));
+ return Boolean(accessor.get(ICommandService).syncExecuteCommand<IRichTextEditingMutationParams>(RichTextEditingMutation.id, {
+ unitId: params.unitId,
+ actions: listAction ? JSONX.compose(listAction, textAction) : textAction,
+ textRanges: ranges,
+ }));
+ },
+};
diff --git a/packages/docs-ui/src/commands/commands/ime-input.command.ts b/packages/docs-ui/src/commands/commands/ime-input.command.ts
index ac297c1a6a..7377d527ed 100644
--- a/packages/docs-ui/src/commands/commands/ime-input.command.ts
+++ b/packages/docs-ui/src/commands/commands/ime-input.command.ts
@@ -35,6 +35,7 @@ import {
getCustomDecorationAtPosition,
getCustomRangeAtPosition,
getTextRunAtInputPosition,
+ getTextRunForSelection,
} from '../../basics/paragraph';
import { DocIMEInputManagerService } from '../../services/doc-ime-input-manager.service';
import { DocMenuStyleService } from '../../services/doc-menu-style.service';
@@ -160,14 +161,16 @@ export const IMEInputCommand: ICommand<IIMEInputCommandParams> = {
const range = getCustomRangeAtPosition(body.customRanges ?? [], styleOffset, SHEET_EDITOR_UNITS.includes(unitId));
inheritedRanges = range ? [range] : [];
}
- const curTextRun = getTextRunAtInputPosition(
- body,
- replacesComplexSelection ? replacementOffset : isCompositionStart ? endOffset : startOffset + oldTextLen,
- defaultTextStyle,
- styleCache,
- SHEET_EDITOR_UNITS.includes(unitId),
- getEditorRuntimeConfig(docDataModel)?.inheritParagraphStartStyle === true
- );
+ const curTextRun = isCompositionStart && !replacesComplexSelection
+ ? getTextRunForSelection(body, { startOffset, endOffset }, defaultTextStyle, styleCache, SHEET_EDITOR_UNITS.includes(unitId), getEditorRuntimeConfig(docDataModel)?.inheritParagraphStartStyle === true)
+ : getTextRunAtInputPosition(
+ body,
+ replacesComplexSelection ? replacementOffset : startOffset + oldTextLen,
+ defaultTextStyle,
+ styleCache,
+ SHEET_EDITOR_UNITS.includes(unitId),
+ getEditorRuntimeConfig(docDataModel)?.inheritParagraphStartStyle === true
+ );
const customDecorations = getCustomDecorationAtPosition(body.customDecorations ?? [], styleOffset);
const insertBody = {
diff --git a/packages/docs-ui/src/commands/commands/inline-format.command.ts b/packages/docs-ui/src/commands/commands/inline-format.command.ts
index 77ef429c2a..3813cf7eae 100644
--- a/packages/docs-ui/src/commands/commands/inline-format.command.ts
+++ b/packages/docs-ui/src/commands/commands/inline-format.command.ts
@@ -14,7 +14,16 @@
* limitations under the License.
*/
-import type { DocumentDataModel, ICommand, IDocumentBody, IMutationInfo, IStyleBase, ITextDecoration, ITextRun, ITextStyle, Nullable } from '@univerjs/core';
+import type {
+ DocumentDataModel,
+ ICommand,
+ IDocumentBody,
+ IMutationInfo,
+ IStyleBase,
+ ITextDecoration,
+ ITextStyle,
+ Nullable,
+} from '@univerjs/core';
import type { IRichTextEditingMutationParams } from '@univerjs/docs';
import type { ITextRangeWithStyle } from '@univerjs/engine-render';
import {
@@ -36,6 +45,7 @@ import {
UpdateDocsAttributeType,
} from '@univerjs/core';
import { DocSelectionManagerService, RichTextEditingMutation } from '@univerjs/docs';
+import { getTextRunAtPosition } from '../../basics/paragraph';
import { DocMenuStyleService } from '../../services/doc-menu-style.service';
import { IEditorService } from '../../services/editor/editor-manager.service';
@@ -481,6 +491,12 @@ export const SetInlineFormatCommand: ICommand<ISetInlineFormatCommandParams> = {
memoryCursor.moveCursor(endOffset);
}
+ // A collapsed selection only changes input formatting. An empty document
+ // mutation can refresh the selection and discard that transient style.
+ if (textX.serialize().length === 0) {
+ return true;
+ }
+
const path = getRichTextEditPath(docDataModel, segmentId);
doMutation.params.actions = jsonX.editOp(textX.serialize(), path);
@@ -538,18 +554,7 @@ export function getStyleInTextRange(
const { startOffset, endOffset, collapsed } = textRange;
if (collapsed) {
- const textRuns = body.textRuns ?? [];
- let textRun: Nullable<ITextRun> = null;
-
- for (let i = textRuns.length - 1; i >= 0; i--) {
- const curTextRun = textRuns[i];
- if (curTextRun.st < startOffset && startOffset <= curTextRun.ed) {
- textRun = curTextRun;
- break;
- }
- }
-
- return textRun?.ts ? { ...defaultStyle, ...textRun.ts } : defaultStyle;
+ return { ...defaultStyle, ...getTextRunAtPosition(body, startOffset, defaultStyle, null).ts };
}
// Menu state only reads text style. Building a full body slice also scans and
diff --git a/packages/docs-ui/src/commands/commands/insert-special-character.command.ts b/packages/docs-ui/src/commands/commands/insert-special-character.command.ts
index 1b84becaa4..beda2f8d0b 100644
--- a/packages/docs-ui/src/commands/commands/insert-special-character.command.ts
+++ b/packages/docs-ui/src/commands/commands/insert-special-character.command.ts
@@ -21,7 +21,7 @@ import { DocSelectionManagerService, InsertTextCommand } from '@univerjs/docs';
import {
getCustomDecorationAtPosition,
getCustomRangeAtPosition,
- getTextRunAtInputPosition,
+ getTextRunForSelection,
} from '../../basics/paragraph';
import { DocMenuStyleService } from '../../services/doc-menu-style.service';
import { getEditorRuntimeConfig } from '../../services/editor/editor-runtime-config';
@@ -54,9 +54,9 @@ export const InsertSpecialCharacterCommand: ICommand<{
}
const { value } = params;
- const curTextRun = getTextRunAtInputPosition(
+ const curTextRun = getTextRunForSelection(
originBody,
- activeRange.endOffset,
+ activeRange,
docMenuStyleService.getDefaultStyle(),
docMenuStyleService.getStyleCache(),
false,
diff --git a/packages/docs-ui/src/controllers/__tests__/doc-render-controller.spec.ts b/packages/docs-ui/src/controllers/__tests__/doc-render-controller.spec.ts
index 229e17e504..d97b2aad2f 100644
--- a/packages/docs-ui/src/controllers/__tests__/doc-render-controller.spec.ts
+++ b/packages/docs-ui/src/controllers/__tests__/doc-render-controller.spec.ts
@@ -1806,6 +1806,43 @@ describe('doc render controller', () => {
expect(backScrollController.scrollToRange).not.toHaveBeenCalled();
});
+ it.each([
+ { useWorker: false, remoteCaret: undefined },
+ { useWorker: true, remoteCaret: undefined },
+ { useWorker: true, remoteCaret: 18 },
+ { useWorker: true, remoteCaret: 9_000 },
+ ])('invalidates disjoint paragraph formats with $useWorker Worker and remote caret $remoteCaret', ({ useWorker, remoteCaret }) => {
+ const { commandCallbacks, controller, skeletonManager } = createControllerFixture({
+ useWorker,
+ activeRange: remoteCaret == null ? undefined : { startOffset: remoteCaret, endOffset: remoteCaret, isActive: true },
+ });
+ commandCallbacks[0]({
+ id: RichTextEditingMutation.id,
+ params: {
+ unitId: 'doc-unit',
+ textRanges: [{ startOffset: 7, endOffset: 26, collapsed: false, isActive: true }],
+ actions: ['body', {
+ et: 'text-x',
+ e: [
+ { t: 'r', len: 12 },
+ { t: 'r', len: 1, body: { dataStream: '', paragraphs: [{ startIndex: 0, bullet: { listId: 'list', listType: 'BULLET_LIST', nestingLevel: 0 } }] } },
+ { t: 'r', len: 5 },
+ { t: 'r', len: 1, body: { dataStream: '', paragraphs: [{ startIndex: 0, bullet: { listId: 'list', listType: 'BULLET_LIST', nestingLevel: 0 } }] } },
+ { t: 'r', len: 7 },
+ { t: 'r', len: 1, body: { dataStream: '', paragraphs: [{ startIndex: 0, bullet: { listId: 'list', listType: 'BULLET_LIST', nestingLevel: 0 } }] } },
+ { t: 'r', len: 6 },
+ ],
+ }],
+ },
+ } satisfies ICommandInfo, remoteCaret == null ? undefined : { fromCollab: true });
+
+ expect(skeletonManager.getSkeleton().startIncrementalLayout).toHaveBeenCalledWith(expect.objectContaining({
+ anchor: remoteCaret != null && remoteCaret > 27 ? remoteCaret : 12,
+ invalidation: { oldStart: 12, oldEnd: 27, newEnd: 27 },
+ }));
+ controller.dispose();
+ });
+
it('derives the incremental invalidation from a body TextX edit composed with table metadata', () => {
const { commandCallbacks, skeletonManager } = createControllerFixture({
snapshot: {
diff --git a/packages/docs-ui/src/controllers/format-painter.controller.ts b/packages/docs-ui/src/controllers/format-painter.controller.ts
new file mode 100644
index 0000000000..25151898df
--- /dev/null
+++ b/packages/docs-ui/src/controllers/format-painter.controller.ts
@@ -0,0 +1,94 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { DocumentDataModel } from '@univerjs/core';
+import {
+ Disposable,
+ FOCUSING_SHAPE_TEXT_EDITOR,
+ ICommandService,
+ IContextService,
+ Inject,
+ IPermissionService,
+ IUniverInstanceService,
+ UniverInstanceType,
+} from '@univerjs/core';
+import { canEditDocumentTargets, DocSelectionManagerService } from '@univerjs/docs';
+import { FormatPainterSessionService } from '@univerjs/ui';
+import { merge } from 'rxjs';
+import { ApplyTextFormatPainterCommand, captureTextFormat } from '../commands/commands/format-painter.command';
+import { DocMenuStyleService } from '../services/doc-menu-style.service';
+import { IEditorService } from '../services/editor/editor-manager.service';
+
+export class DocFormatPainterController extends Disposable {
+ constructor(
+ @Inject(FormatPainterSessionService) session: FormatPainterSessionService,
+ @Inject(DocSelectionManagerService) selections: DocSelectionManagerService,
+ @Inject(DocMenuStyleService) styles: DocMenuStyleService,
+ @IUniverInstanceService instances: IUniverInstanceService,
+ @IContextService context: IContextService,
+ @IPermissionService permissions: IPermissionService,
+ @IEditorService editors: IEditorService,
+ @ICommandService commands: ICommandService
+ ) {
+ super();
+ this.disposeWithMe(commands.registerCommand(ApplyTextFormatPainterCommand));
+ const model = () => instances.getCurrentUnitOfType<DocumentDataModel>(UniverInstanceType.UNIVER_DOC);
+ const isActive = () => !!model() && (
+ context.getContextValue(FOCUSING_SHAPE_TEXT_EDITOR) ||
+ (instances.getFocusedUnit()?.getUnitId() === model()?.getUnitId() && !editors.isEditor(model()!.getUnitId()))
+ );
+ const canStart = () => {
+ const doc = model();
+ return !!doc && !!selections.getActiveTextRange() && canEditDocumentTargets(permissions, doc.getUnitId(), []);
+ };
+ this.disposeWithMe(session.register({
+ id: 'doc-text',
+ priority: 10,
+ changes$: merge(selections.textSelection$, instances.focused$, permissions.permissionPointUpdate$),
+ isActive,
+ canStart,
+ clear: () => {
+ const doc = model();
+ if (!doc) {
+ return false;
+ }
+ const format = captureTextFormat({ dataStream: '' }, { startOffset: 0, endOffset: 0 }, styles.getDefaultStyle());
+ return commands.executeCommand(ApplyTextFormatPainterCommand.id, {
+ unitId: doc.getUnitId(),
+ ranges: selections.getDocRanges(),
+ format: { ...format, paragraphStyle: {} },
+ });
+ },
+ capture: () => {
+ const doc = model();
+ const range = selections.getActiveTextRange();
+ const body = doc?.getSelfOrHeaderFooterModel(range?.segmentId)?.getBody();
+ if (!doc || !body || !range) {
+ return null;
+ }
+ const format = captureTextFormat(body, range, styles.getDefaultStyle(), doc.getSnapshot().lists, doc.getSnapshot());
+ return {
+ unitId: instances.getFocusedUnit()?.getUnitId() ?? doc.getUnitId(),
+ apply: (target) => commands.executeCommand(ApplyTextFormatPainterCommand.id, {
+ unitId: target.subUnitId ?? target.unitId,
+ ranges: selections.getDocRanges(),
+ format,
+ }),
+ };
+ },
+ }));
+ }
+}
diff --git a/packages/docs-ui/src/controllers/render-controllers/doc-input.controller.ts b/packages/docs-ui/src/controllers/render-controllers/doc-input.controller.ts
index a49f929292..5db211f248 100644
--- a/packages/docs-ui/src/controllers/render-controllers/doc-input.controller.ts
+++ b/packages/docs-ui/src/controllers/render-controllers/doc-input.controller.ts
@@ -23,7 +23,7 @@ import { DocSkeletonManagerService, InsertTextCommand } from '@univerjs/docs';
import {
getCustomDecorationAtPosition,
getCustomRangeAtPosition,
- getTextRunAtInputPosition,
+ getTextRunForSelection,
} from '../../basics/paragraph';
import { AfterSpaceCommand } from '../../commands/commands/auto-format.command';
import { ReplaceSelectionCommand } from '../../commands/commands/replace-content.command';
@@ -99,7 +99,7 @@ export class DocInputController extends Disposable implements IRenderModule {
const defaultTextStyle = this._docMenuStyleService.getDefaultStyle();
const cacheStyle = this._docMenuStyleService.getStyleCache();
const curCustomRange = getCustomRangeAtPosition(originBody?.customRanges ?? [], activeRange.endOffset, SHEET_EDITOR_UNITS.includes(unitId));
- const curTextRun = getTextRunAtInputPosition(originBody, activeRange.endOffset, defaultTextStyle, cacheStyle, SHEET_EDITOR_UNITS.includes(unitId), getEditorRuntimeConfig(docDataModel)?.inheritParagraphStartStyle === true);
+ const curTextRun = getTextRunForSelection(originBody, activeRange, defaultTextStyle, cacheStyle, SHEET_EDITOR_UNITS.includes(unitId), getEditorRuntimeConfig(docDataModel)?.inheritParagraphStartStyle === true);
const curCustomDecorations = getCustomDecorationAtPosition(originBody?.customDecorations ?? [], activeRange.endOffset);
const insertBody = {
diff --git a/packages/docs-ui/src/controllers/render-controllers/doc-paragraph-placeholder.render-controller.ts b/packages/docs-ui/src/controllers/render-controllers/doc-paragraph-placeholder.render-controller.ts
index 982ca94da8..5505cefa1e 100644
--- a/packages/docs-ui/src/controllers/render-controllers/doc-paragraph-placeholder.render-controller.ts
+++ b/packages/docs-ui/src/controllers/render-controllers/doc-paragraph-placeholder.render-controller.ts
@@ -38,12 +38,13 @@ import {
LocaleService,
NAMED_STYLE_MAP,
NamedStyleType,
+ ThemeService,
} from '@univerjs/core';
import { DocSelectionManagerService } from '@univerjs/docs';
import { getDocsTableRenderViewport, getDocsTableViewportLeft, getTableIdAndSliceIndex } from '@univerjs/engine-render';
import { DOCS_UI_PLUGIN_CONFIG_KEY } from '../../config/config';
-const PLACEHOLDER_COLOR = 'gray.400';
+const PLACEHOLDER_COLOR = 'gray.300';
const DEFAULT_PLACEHOLDER_FONT_SIZE = 12;
const MIN_BODY_TEXT_PLACEHOLDER_FONT_SIZE = 16;
const DEFAULT_PLACEHOLDER_FONT_FAMILY = 'Arial';
@@ -88,7 +89,8 @@ export class DocParagraphPlaceholderRenderController extends Disposable implemen
private readonly _context: IRenderContext<DocumentDataModel>,
@Inject(LocaleService) private readonly _localeService: LocaleService,
@Inject(DocSelectionManagerService) private readonly _docSelectionManagerService: DocSelectionManagerService,
- @IConfigService private readonly _configService: IConfigService
+ @IConfigService private readonly _configService: IConfigService,
+ @Inject(ThemeService) private readonly _themeService: ThemeService
) {
super();
@@ -148,7 +150,8 @@ export class DocParagraphPlaceholderRenderController extends Disposable implemen
return;
}
- drawParagraphPlaceholders(ctx, placeholders);
+ // The canvas inverts theme colors in dark mode; keep its existing contrast.
+ drawParagraphPlaceholders(ctx, placeholders, this._themeService.darkMode ? 'gray.400' : PLACEHOLDER_COLOR);
}
private _getLocale(): IParagraphPlaceholderLocale {
@@ -412,9 +415,13 @@ function getLineFontFamily(line: IDocumentSkeletonLine): Nullable<string> {
return null;
}
-export function drawParagraphPlaceholders(ctx: UniverRenderingContext, placeholders: IParagraphPlaceholderLayout[]): void {
+export function drawParagraphPlaceholders(
+ ctx: UniverRenderingContext,
+ placeholders: IParagraphPlaceholderLayout[],
+ color = PLACEHOLDER_COLOR
+): void {
ctx.save();
- ctx.fillStyle = PLACEHOLDER_COLOR;
+ ctx.fillStyle = color;
ctx.textBaseline = 'alphabetic';
for (const placeholder of placeholders) {
diff --git a/packages/docs-ui/src/controllers/render-controllers/doc.render-controller.ts b/packages/docs-ui/src/controllers/render-controllers/doc.render-controller.ts
index bd1b6f572d..395a7288ca 100644
--- a/packages/docs-ui/src/controllers/render-controllers/doc.render-controller.ts
+++ b/packages/docs-ui/src/controllers/render-controllers/doc.render-controller.ts
@@ -187,6 +187,9 @@ function getBodyMutationInvalidation(
let oldOffset = 0;
let newOffset = 0;
let invalidation: IDocumentLayoutInvalidation | undefined;
+ const preservesOffsets = textActions.every((action) =>
+ typeof action === 'object' && action != null && 't' in action && action.t === TextXActionType.RETAIN
+ );
let sawTrailingRetain = false;
for (const action of textActions) {
const length = getTextXActionLength(action);
@@ -200,8 +203,10 @@ function getBodyMutationInvalidation(
sawTrailingRetain ||= invalidation != null;
continue;
}
- if (sawTrailingRetain) {
- // Multiple disjoint edits need more than one offset transform. Fall
+ if (sawTrailingRetain && !preservesOffsets) {
+ // Disjoint formatting retains preserve offsets, so one enclosing range
+ // safely invalidates every changed paragraph, including the gaps.
+ // Multiple disjoint text edits need more than one offset transform. Fall
// back to ordinary suffix pagination instead of reusing a wrong tail.
return undefined;
}
diff --git a/packages/docs-ui/src/controllers/render-controllers/format-painter.render-controller.ts b/packages/docs-ui/src/controllers/render-controllers/format-painter.render-controller.ts
new file mode 100644
index 0000000000..89258ac34e
--- /dev/null
+++ b/packages/docs-ui/src/controllers/render-controllers/format-painter.render-controller.ts
@@ -0,0 +1,50 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { DocumentDataModel } from '@univerjs/core';
+import type { IRenderContext, IRenderModule } from '@univerjs/engine-render';
+import { Disposable, Inject, IUniverInstanceService } from '@univerjs/core';
+import { DocSelectionManagerService } from '@univerjs/docs';
+import { Vector2 } from '@univerjs/engine-render';
+import { bindFormatPainterCanvas, FormatPainterSessionService } from '@univerjs/ui';
+
+export class DocFormatPainterRenderController extends Disposable implements IRenderModule {
+ constructor(
+ context: IRenderContext<DocumentDataModel>,
+ @Inject(FormatPainterSessionService) session: FormatPainterSessionService,
+ @Inject(DocSelectionManagerService) selections: DocSelectionManagerService,
+ @IUniverInstanceService instances: IUniverInstanceService
+ ) {
+ super();
+ const canvas = context.engine.getCanvasElement();
+ this.disposeWithMe(bindFormatPainterCanvas(canvas, session, {
+ adapterId: 'doc-text',
+ // Embedded shape editors preserve focus on their host Unit.
+ unitId: context.unitId,
+ getUnitId: () => instances.getFocusedUnit()?.getUnitId() ?? context.unitId,
+ intercept: false,
+ getTarget: (event) => {
+ const picked = context.scene.pick(new Vector2(event.offsetX, event.offsetY));
+ if (picked && picked !== context.mainComponent) {
+ return null;
+ }
+ return selections.getDocRanges().length > 0
+ ? { unitId: instances.getFocusedUnit()?.getUnitId() ?? context.unitId, subUnitId: context.unitId }
+ : null;
+ },
+ }));
+ }
+}
diff --git a/packages/docs-ui/src/index.ts b/packages/docs-ui/src/index.ts
index fb54554ea7..e850baa8b8 100644
--- a/packages/docs-ui/src/index.ts
+++ b/packages/docs-ui/src/index.ts
@@ -60,6 +60,7 @@ export type {
export { getCursorWhenDelete } from './commands/commands/doc-delete.command';
export { HorizontalLineCommand } from './commands/commands/doc-horizontal-line.command';
export { DocSelectAllCommand } from './commands/commands/doc-select-all.command';
+export { captureTextFormat } from './commands/commands/format-painter.command';
export { IMEInputCommand } from './commands/commands/ime-input.command';
export type { IIMEInputCommandParams } from './commands/commands/ime-input.command';
export {
diff --git a/packages/docs-ui/src/plugin.ts b/packages/docs-ui/src/plugin.ts
index 338976399f..35d9ecd7d1 100644
--- a/packages/docs-ui/src/plugin.ts
+++ b/packages/docs-ui/src/plugin.ts
@@ -158,6 +158,7 @@ import { DocMoveCursorController } from './controllers/doc-move-cursor.controlle
import { DocParagraphSettingController } from './controllers/doc-paragraph-setting.controller';
import { DocSectionSettingController } from './controllers/doc-section-setting.controller';
import { DocTableController } from './controllers/doc-table.controller';
+import { DocFormatPainterController } from './controllers/format-painter.controller';
import { DocBackScrollRenderController } from './controllers/render-controllers/back-scroll.render-controller';
import {
DocCanvasPopupLayoutInteractionController,
@@ -181,6 +182,7 @@ import { DocPasteOptionsRenderController } from './controllers/render-controller
import { DocResizeRenderController } from './controllers/render-controllers/doc-resize.render-controller';
import { DocSelectionRenderController } from './controllers/render-controllers/doc-selection-render.controller';
import { DocRenderController } from './controllers/render-controllers/doc.render-controller';
+import { DocFormatPainterRenderController } from './controllers/render-controllers/format-painter.render-controller';
import { DocZoomRenderController } from './controllers/render-controllers/zoom.render-controller';
import { DocUIController } from './controllers/ui.controller';
import { DocClipboardService, IDocClipboardService } from './services/clipboard/clipboard.service';
@@ -479,6 +481,7 @@ export class UniverDocsUIPlugin extends Plugin {
[IDocStateChangeInterceptorService, { useClass: DocIMEStateChangeInterceptorService }],
[DocAutoFormatService],
[DocMenuStyleService],
+ [DocFormatPainterController],
[DocContextualRibbonService],
], this._config.override);
@@ -501,6 +504,7 @@ export class UniverDocsUIPlugin extends Plugin {
}
private _initRenderBasics() {
+ this._injector.get(DocFormatPainterController);
([
[DocSkeletonManagerService],
[DocSelectionRenderService],
@@ -515,6 +519,7 @@ export class UniverDocsUIPlugin extends Plugin {
[DocZoomRenderController],
[DocBackScrollRenderController],
[DocSelectionRenderController],
+ [DocFormatPainterRenderController],
] as Dependency[]).forEach((m) => {
this._renderManagerSrv.registerRenderModule(UniverInstanceType.UNIVER_DOC, m);
});
diff --git a/packages/docs-ui/src/services/__tests__/doc-menu-style.service.spec.ts b/packages/docs-ui/src/services/__tests__/doc-menu-style.service.spec.ts
index 8b0b96ea21..443c789183 100644
--- a/packages/docs-ui/src/services/__tests__/doc-menu-style.service.spec.ts
+++ b/packages/docs-ui/src/services/__tests__/doc-menu-style.service.spec.ts
@@ -198,4 +198,15 @@ describe('DocMenuStyleService', () => {
expect(service.getStyleCache()).toBeNull();
});
+ it('clears transient input formatting when switching documents', () => {
+ const { injector, service } = createStyleTestBed();
+ const instances = injector.get(IUniverInstanceService) as UniverInstanceService;
+ instances.__addUnit(new DocumentDataModel({ id: 'other-doc', body: { dataStream: '\r\n' } }));
+ instances.setCurrentUnitForType('doc-menu-style');
+ service.setStyleCache({ cl: { rgb: '#0000ff' }, it: 1 });
+ instances.setCurrentUnitForType('other-doc');
+ expect(service.getStyleCache()).toBeNull();
+ instances.setCurrentUnitForType('doc-menu-style');
+ expect(service.getStyleCache()).toBeNull();
+ });
});
diff --git a/packages/docs-ui/src/services/clipboard/clipboard.service.ts b/packages/docs-ui/src/services/clipboard/clipboard.service.ts
index 9aa2715be7..ba28d20fed 100644
--- a/packages/docs-ui/src/services/clipboard/clipboard.service.ts
+++ b/packages/docs-ui/src/services/clipboard/clipboard.service.ts
@@ -196,6 +196,8 @@ export interface IDocClipboardPasteContext {
}
export interface IDocClipboardHook {
+ /** Supply a rich fragment for selections owned by a plugin rather than native text ranges. */
+ onCopySelection?(unitId: string): { documentData: IDocumentData; plainText: string } | undefined;
onCopyDocData?(doc: Partial<IDocumentData>, context: IDocClipboardCopyDocDataContext): Partial<IDocumentData>;
onCopyProperty?(start: number, end: number): IClipboardPropertyItem;
onCopyContent?(start: number, end: number, context: IDocClipboardCopyContentContext): string;
@@ -355,6 +357,20 @@ export class DocClipboardService extends Disposable implements IDocClipboardServ
)) {
return false;
}
+ if (sliceType === SliceBodyType.copy && ranges == null) {
+ try {
+ for (const hook of this._clipboardHooks) {
+ const selection = hook.onCopySelection?.(document.getUnitId());
+ if (selection) {
+ await this._setClipboardData([selection.documentData], true, [selection.plainText]);
+ return true;
+ }
+ }
+ } catch (error) {
+ this._logService.error('[DocClipboardService] copy selection failed', error);
+ return false;
+ }
+ }
const {
newSnapshotList = [],
needCache = false,
diff --git a/packages/docs-ui/src/services/doc-menu-style.service.ts b/packages/docs-ui/src/services/doc-menu-style.service.ts
index 84653c581e..85a3165ebc 100644
--- a/packages/docs-ui/src/services/doc-menu-style.service.ts
+++ b/packages/docs-ui/src/services/doc-menu-style.service.ts
@@ -50,6 +50,11 @@ export class DocMenuStyleService extends Disposable {
private _init() {
this._listenDocRangeChange();
+ this.disposeWithMe(
+ this._univerInstanceService.getCurrentTypeOfUnit$(UniverInstanceType.UNIVER_DOC).subscribe(() => {
+ this._clearStyleCache();
+ })
+ );
}
private _listenDocRangeChange() {
diff --git a/packages/docs/src/commands/commands/core-editing.command.ts b/packages/docs/src/commands/commands/core-editing.command.ts
index b7d00f16f4..05d074f1f6 100644
--- a/packages/docs/src/commands/commands/core-editing.command.ts
+++ b/packages/docs/src/commands/commands/core-editing.command.ts
@@ -214,7 +214,7 @@ export const DeleteTextCommand: ICommand<IDeleteTextCommandParams> = {
startOffset: start,
endOffset: end + 1,
collapsed: false,
- }], body));
+ }], body, 0, null, true, docDataModel.getDocumentStyle().documentFlavor));
const path = getRichTextEditPath(docDataModel, segmentId);
doMutation.params.actions = appendRemovedDrawingActions(
diff --git a/packages/sheets-drawing-ui/src/controllers/__tests__/sheet-drawing-copy-paste.controller.spec.ts b/packages/sheets-drawing-ui/src/controllers/__tests__/sheet-drawing-copy-paste.controller.spec.ts
index 08bcb0f514..026083c546 100644
--- a/packages/sheets-drawing-ui/src/controllers/__tests__/sheet-drawing-copy-paste.controller.spec.ts
+++ b/packages/sheets-drawing-ui/src/controllers/__tests__/sheet-drawing-copy-paste.controller.spec.ts
@@ -101,10 +101,12 @@ function createController(options?: { focusedDrawings?: IImageDrawing[]; drawing
const commandService = {
executeCommand: vi.fn(),
};
+ const clipboardInterfaceService = { writeText: vi.fn() };
+ const hookDisposable = { dispose: vi.fn() };
const sheetClipboardService = {
addClipboardHook: vi.fn((config: ISheetClipboardHook) => {
hook = config;
- return { dispose: vi.fn() };
+ return hookDisposable;
}),
};
@@ -113,16 +115,87 @@ function createController(options?: { focusedDrawings?: IImageDrawing[]; drawing
[IRenderManagerService, { useValue: {} }],
[SheetSkeletonService, { useValue: { getSkeleton: vi.fn(() => skeleton) } }],
[IDrawingManagerService, { useValue: drawingService }],
- [IClipboardInterfaceService, { useValue: { writeText: vi.fn() } }],
+ [IClipboardInterfaceService, { useValue: clipboardInterfaceService }],
[ICommandService, { useValue: commandService }],
[SheetsDrawingCopyPasteController],
]);
const controller = injector.get(SheetsDrawingCopyPasteController);
- return { controller, hook: hook as ITestClipboardHook, skeleton, drawingService, commandService };
+ return {
+ controller,
+ hook: hook as ITestClipboardHook,
+ skeleton,
+ drawingService,
+ commandService,
+ clipboardInterfaceService,
+ hookDisposable,
+ };
}
describe('SheetsDrawingCopyPasteController', () => {
+ it('cancels all pending clipboard writes when disposed', () => {
+ vi.useFakeTimers();
+ const { controller, hook, clipboardInterfaceService } = createController({
+ focusedDrawings: [createImageDrawing({ imageSourceType: ImageSourceType.URL })],
+ });
+ const activeElement = document.activeElement;
+ const childCount = document.body.childElementCount;
+
+ try {
+ expect(hook.onBeforeCopyFocusedObject?.('unit-1', 'sheet-1', COPY_TYPE.COPY)).toBe(true);
+ expect(hook.onBeforeCopyFocusedObject?.('unit-1', 'sheet-1', COPY_TYPE.CUT)).toBe(true);
+ controller.dispose();
+ vi.runAllTimers();
+
+ expect(clipboardInterfaceService.writeText).not.toHaveBeenCalled();
+ expect(document.activeElement).toBe(activeElement);
+ expect(document.body.childElementCount).toBe(childCount);
+ } finally {
+ controller.dispose();
+ vi.clearAllTimers();
+ vi.useRealTimers();
+ }
+ });
+
+ it('releases the clipboard hook exactly once when disposed', () => {
+ const { controller, hookDisposable } = createController();
+
+ controller.dispose();
+ controller.dispose();
+
+ expect(hookDisposable.dispose).toHaveBeenCalledTimes(1);
+ });
+
+ it('rewrites the clipboard while active and restores document focus', () => {
+ vi.useFakeTimers();
+ const { controller, hook, clipboardInterfaceService } = createController({
+ focusedDrawings: [createImageDrawing({ imageSourceType: ImageSourceType.URL })],
+ });
+ const input = document.createElement('input');
+ document.body.appendChild(input);
+ input.focus();
+ const childCount = document.body.childElementCount;
+
+ try {
+ hook.onBeforeCopyFocusedObject?.('unit-1', 'sheet-1', COPY_TYPE.COPY);
+ expect(clipboardInterfaceService.writeText).not.toHaveBeenCalled();
+ vi.advanceTimersByTime(200);
+
+ expect(clipboardInterfaceService.writeText).toHaveBeenCalledExactlyOnceWith('');
+ expect(document.activeElement).toBe(input);
+ expect(document.body.childElementCount).toBe(childCount);
+
+ controller.dispose();
+ vi.runAllTimers();
+ expect(clipboardInterfaceService.writeText).toHaveBeenCalledTimes(1);
+ } finally {
+ controller.dispose();
+ input.remove();
+ vi.clearAllTimers();
+ vi.useRealTimers();
+ }
+ });
+
it('copies default position-anchored images contained in a cell range', () => {
const positionOnlyDrawing = createImageDrawing({
drawingId: 'position-only',
diff --git a/packages/sheets-drawing-ui/src/controllers/sheet-drawing-copy-paste.controller.ts b/packages/sheets-drawing-ui/src/controllers/sheet-drawing-copy-paste.controller.ts
index c7e1733ccf..5d9f44aa28 100644
--- a/packages/sheets-drawing-ui/src/controllers/sheet-drawing-copy-paste.controller.ts
+++ b/packages/sheets-drawing-ui/src/controllers/sheet-drawing-copy-paste.controller.ts
@@ -19,11 +19,18 @@ import type { IDrawingJsonUndo1 } from '@univerjs/drawing';
import type { IDiscreteRange } from '@univerjs/sheets';
import type { IRemoveSheetDrawingCommandParams, ISheetDrawing, ISheetImage } from '@univerjs/sheets-drawing';
import type { IPasteHookValueType, ISheetDiscreteRangeLocation } from '@univerjs/sheets-ui';
-import { Disposable, DrawingTypeEnum, generateRandomId, ICommandService, ImageSourceType, Inject } from '@univerjs/core';
+import { DrawingTypeEnum, generateRandomId, ICommandService, ImageSourceType, Inject, RxDisposable } from '@univerjs/core';
import { IDrawingManagerService } from '@univerjs/drawing';
import { IRenderManagerService } from '@univerjs/engine-render';
import { attachRangeWithCoord, discreteRangeToRange, SheetSkeletonService } from '@univerjs/sheets';
-import { DrawingApplyType, RemoveSheetDrawingCommand, SetDrawingApplyMutation, SheetDrawingAnchorType, transformToAxisAlignPosition, transformToDrawingPosition } from '@univerjs/sheets-drawing';
+import {
+ DrawingApplyType,
+ RemoveSheetDrawingCommand,
+ SetDrawingApplyMutation,
+ SheetDrawingAnchorType,
+ transformToAxisAlignPosition,
+ transformToDrawingPosition,
+} from '@univerjs/sheets-drawing';
import {
COPY_TYPE,
ISheetClipboardService,
@@ -31,6 +38,7 @@ import {
virtualizeDiscreteRanges,
} from '@univerjs/sheets-ui';
import { IClipboardInterfaceService } from '@univerjs/ui';
+import { takeUntil, timer } from 'rxjs';
import { InsertFloatImageCommand } from '../commands/commands/insert-image.command';
const IMAGE_PNG_MIME_TYPE = 'image/png';
@@ -87,7 +95,7 @@ const specialPastes: IPasteHookValueType[] = [
PREDEFINED_HOOK_NAME_PASTE.SPECIAL_PASTE_FORMULA,
];
-export class SheetsDrawingCopyPasteController extends Disposable {
+export class SheetsDrawingCopyPasteController extends RxDisposable {
private _copyInfo: Nullable<{
drawings: ISheetDrawing[];
copyRange?: IRange;
@@ -111,9 +119,8 @@ export class SheetsDrawingCopyPasteController extends Disposable {
return this._drawingService.getFocusDrawings() as ISheetDrawing[];
}
- // eslint-disable-next-line max-lines-per-function
private _initCopyPaste() {
- this._sheetClipboardService.addClipboardHook({
+ this.disposeWithMe(this._sheetClipboardService.addClipboardHook({
id: 'SHEET_IMAGE_UI_PLUGIN',
onBeforeCopyFocusedObject: (unitId, _subUnitId, copyType) => {
@@ -135,7 +142,7 @@ export class SheetsDrawingCopyPasteController extends Disposable {
this._commandService.executeCommand<IRemoveSheetDrawingCommandParams>(RemoveSheetDrawingCommand.id, params);
}
- setTimeout(() => {
+ timer(200).pipe(takeUntil(this.dispose$)).subscribe(() => {
// Rewrite the clipboard content to prevent the default copy behavior, prevent to call the 'onPasteCells'
const dispose = focusDocument();
if (drawing.drawingType === DrawingTypeEnum.DRAWING_IMAGE
@@ -145,7 +152,7 @@ export class SheetsDrawingCopyPasteController extends Disposable {
this._clipboardInterfaceService.writeText('');
}
dispose();
- }, 200);
+ });
this._copyInfo = {
unitId: drawing.unitId,
@@ -221,7 +228,7 @@ export class SheetsDrawingCopyPasteController extends Disposable {
return { undos: [], redos: [] };
},
- });
+ }));
}
private _createDrawingsCopyInfoByRange(unitId: string, subUnitId: string, range: IRange) {
diff --git a/packages/sheets-ui/src/commands/commands/__tests__/set-format-painter.command.spec.ts b/packages/sheets-ui/src/commands/commands/__tests__/set-format-painter.command.spec.ts
index d284cfc149..22b493042b 100644
--- a/packages/sheets-ui/src/commands/commands/__tests__/set-format-painter.command.spec.ts
+++ b/packages/sheets-ui/src/commands/commands/__tests__/set-format-painter.command.spec.ts
@@ -36,6 +36,7 @@ import {
SetRangeValuesMutation,
SetSelectionsOperation,
} from '@univerjs/sheets';
+import { FormatPainterSessionService } from '@univerjs/ui';
import { BehaviorSubject } from 'rxjs';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import { FormatPainterController } from '../../../controllers/format-painter/format-painter.controller';
@@ -215,6 +216,7 @@ describe('Test format painter rules in controller', () => {
[ISheetSelectionRenderService, { useClass: SheetSelectionRenderService }],
[IRenderManagerService, { useClass: RenderManagerService }],
[FormatPainterController],
+ [FormatPainterSessionService],
]);
univer = testBed.univer;
@@ -259,6 +261,13 @@ describe('Test format painter rules in controller', () => {
expect(formatPainterService.getStatus()).toBe(FormatPainterStatus.OFF);
});
+ it('upgrades a single-use legacy brush when the ribbon double-click arrives', async () => {
+ const service = get(IFormatPainterService);
+ await commandService.executeCommand(SetOnceFormatPainterCommand.id);
+ await commandService.executeCommand(SetInfiniteFormatPainterCommand.id);
+ expect(service.getStatus()).toBe(FormatPainterStatus.INFINITE);
+ });
+
describe('format painter the numbers', async () => {
it('correct situation', async () => {
const workbook = get(IUniverInstanceService).getCurrentUnitOfType<Workbook>(UniverInstanceType.UNIVER_SHEET)!;
diff --git a/packages/sheets-ui/src/commands/commands/set-format-painter.command.ts b/packages/sheets-ui/src/commands/commands/set-format-painter.command.ts
index bd5b1fb04f..fac40fe87d 100644
--- a/packages/sheets-ui/src/commands/commands/set-format-painter.command.ts
+++ b/packages/sheets-ui/src/commands/commands/set-format-painter.command.ts
@@ -34,7 +34,7 @@ export const SetInfiniteFormatPainterCommand: ICommand = {
const formatPainterService = accessor.get(IFormatPainterService);
const status = formatPainterService.getStatus();
let newStatus: FormatPainterStatus;
- if (status !== FormatPainterStatus.OFF) {
+ if (status === FormatPainterStatus.INFINITE) {
newStatus = FormatPainterStatus.OFF;
} else {
newStatus = FormatPainterStatus.INFINITE;
diff --git a/packages/sheets-ui/src/controllers/format-painter/format-painter.controller.ts b/packages/sheets-ui/src/controllers/format-painter/format-painter.controller.ts
index 23ccceade4..f83adfda74 100644
--- a/packages/sheets-ui/src/controllers/format-painter/format-painter.controller.ts
+++ b/packages/sheets-ui/src/controllers/format-painter/format-painter.controller.ts
@@ -33,6 +33,7 @@ import { IRenderManagerService } from '@univerjs/engine-render';
import {
AddMergeUndoMutationFactory,
AddWorksheetMergeMutation,
+ ClearSelectionFormatCommand,
getAddMergeMutationRangeByType,
getClearContentMutationParamsForRanges,
RemoveMergeUndoMutationFactory,
@@ -46,6 +47,8 @@ import {
SheetInterceptorService,
SheetsSelectionsService,
} from '@univerjs/sheets';
+import { FormatPainterSessionService } from '@univerjs/ui';
+import { ApplyFormatPainterCommand } from '../../commands/commands/set-format-painter.command';
import { checkCellContentInRanges } from '../../common/utils';
import { FormatPainterStatus, IFormatPainterService } from '../../services/format-painter/format-painter.service';
@@ -66,6 +69,40 @@ export class FormatPainterController extends Disposable {
private _initialize() {
this._addDefaultHook();
+ const session = this._injector.get(FormatPainterSessionService);
+ this.disposeWithMe(session.register({
+ id: 'sheet-cells',
+ priority: 0,
+ clear: () => this._commandService.executeCommand(ClearSelectionFormatCommand.id),
+ changes$: this._selectionManagerService.selectionMoveEnd$,
+ isActive: () => this._univerInstanceService.getFocusedUnit()?.type === UniverInstanceType.UNIVER_SHEET,
+ canStart: () => !!this._selectionManagerService.getCurrentLastSelection(),
+ capture: () => {
+ const workbook = this._univerInstanceService.getCurrentUnitOfType<Workbook>(UniverInstanceType.UNIVER_SHEET);
+ const format = this._collectSelectionRangeFormat();
+ if (!workbook || !format) {
+ return null;
+ }
+ this._formatPainterService.setSelectionFormat(format);
+ return {
+ unitId: workbook.getUnitId(),
+ apply: (target) => !!target.subUnitId && !!target.range && this._commandService.executeCommand(
+ ApplyFormatPainterCommand.id,
+ target
+ ),
+ onModeChange: (mode) => this._formatPainterService.setStatus({
+ off: FormatPainterStatus.OFF,
+ once: FormatPainterStatus.ONCE,
+ continuous: FormatPainterStatus.INFINITE,
+ }[mode]),
+ };
+ },
+ }));
+ this.disposeWithMe(this._formatPainterService.status$.subscribe((status) => {
+ if (status === FormatPainterStatus.OFF && session.isActive('sheet-cells')) {
+ session.cancel();
+ }
+ }));
}
private _addDefaultHook() {
@@ -74,7 +111,7 @@ export class FormatPainterController extends Disposable {
priority: 0,
isDefaultHook: true,
onStatusChange: (status: FormatPainterStatus) => {
- if (status !== FormatPainterStatus.OFF) {
+ if (status !== FormatPainterStatus.OFF && !this._injector.get(FormatPainterSessionService).isActive('sheet-cells')) {
const format = this._collectSelectionRangeFormat();
if (format) {
this._formatPainterService.setSelectionFormat(format);
@@ -104,7 +141,7 @@ export class FormatPainterController extends Disposable {
for (let r = startRow; r <= endRow; r++) {
for (let c = startColumn; c <= endColumn; c++) {
const cell = cellData.getValue(r, c) as ICellData;
- stylesMatrix.setValue(r, c, styles.getStyleByCell(cell) || {});
+ stylesMatrix.setValue(r, c, Tools.deepClone(styles.getStyleByCell(cell) || {}));
const { isMergedMainCell, ...mergeInfo } = worksheet.getCellInfoInMergeData(r, c);
if (isMergedMainCell) {
merges.push({
diff --git a/packages/sheets-ui/src/controllers/render-controllers/format-painter.render-controller.ts b/packages/sheets-ui/src/controllers/render-controllers/format-painter.render-controller.ts
index 458a997ac6..b388a95808 100644
--- a/packages/sheets-ui/src/controllers/render-controllers/format-painter.render-controller.ts
+++ b/packages/sheets-ui/src/controllers/render-controllers/format-painter.render-controller.ts
@@ -19,9 +19,12 @@ import type { IRenderContext, IRenderModule } from '@univerjs/engine-render';
import {
Disposable,
ICommandService,
+ Inject,
toDisposable,
} from '@univerjs/core';
-import { CURSOR_TYPE } from '@univerjs/engine-render';
+import { CURSOR_TYPE, Vector2 } from '@univerjs/engine-render';
+import { SheetsSelectionsService } from '@univerjs/sheets';
+import { bindFormatPainterCanvas, FormatPainterSessionService } from '@univerjs/ui';
import { ApplyFormatPainterCommand, SetOnceFormatPainterCommand } from '../../commands/commands/set-format-painter.command';
import { FormatPainterStatus, IFormatPainterService } from '../../services/format-painter/format-painter.service';
@@ -32,10 +35,25 @@ export class FormatPainterRenderController extends Disposable implements IRender
private readonly _context: IRenderContext<Workbook>,
@IFormatPainterService private readonly _formatPainterService: IFormatPainterService,
@ISheetSelectionRenderService private readonly _selectionRenderService: ISheetSelectionRenderService,
+ @Inject(FormatPainterSessionService) private readonly _session: FormatPainterSessionService,
+ @Inject(SheetsSelectionsService) private readonly _selections: SheetsSelectionsService,
@ICommandService private readonly _commandService: ICommandService
) {
super();
this._initialize();
+ this.disposeWithMe(bindFormatPainterCanvas(this._context.engine.getCanvasElement(), this._session, {
+ adapterId: 'sheet-cells',
+ unitId: this._context.unitId,
+ intercept: false,
+ getTarget: (event) => {
+ const picked = this._context.scene.pick(new Vector2(event.offsetX, event.offsetY));
+ if (picked && picked !== this._context.mainComponent) {
+ return null;
+ }
+ const range = this._selections.getCurrentLastSelection()?.range;
+ return range ? { unitId: this._context.unitId, subUnitId: this._context.unit.getActiveSheet()?.getSheetId(), range } : null;
+ },
+ }));
}
private _initialize() {
@@ -45,6 +63,9 @@ export class FormatPainterRenderController extends Disposable implements IRender
private _commandExecutedListener() {
this.disposeWithMe(this._selectionRenderService.selectionMoveEnd$.subscribe((selections) => {
+ if (this._session.isActive('sheet-cells')) {
+ return;
+ }
if (this._formatPainterService.getStatus() !== FormatPainterStatus.OFF) {
const { rangeWithCoord } = selections[selections.length - 1];
this._commandService.executeCommand(ApplyFormatPainterCommand.id, {
diff --git a/packages/sheets-ui/src/menu/schema.ts b/packages/sheets-ui/src/menu/schema.ts
index b22967d4b5..592983a021 100644
--- a/packages/sheets-ui/src/menu/schema.ts
+++ b/packages/sheets-ui/src/menu/schema.ts
@@ -94,7 +94,6 @@ import {
} from '../commands/commands/range-protection.command';
import { RemoveColConfirmCommand, RemoveRowConfirmCommand } from '../commands/commands/remove-row-col-confirm.command';
import { RemoveSheetConfirmCommand } from '../commands/commands/remove-sheet-confirm.command';
-import { SetOnceFormatPainterCommand } from '../commands/commands/set-format-painter.command';
import {
SetColumnFrozenCommand,
SetFirstColumnFrozenCommand,
@@ -113,7 +112,6 @@ import { CellBorderSelectorMenuItemFactory } from './border.menu';
import {
CLEAR_SELECTION_MENU_ID,
ClearSelectionAllMenuItemFactory,
- ClearSelectionAllToolbarMenuItemFactory,
ClearSelectionContentMenuItemFactory,
ClearSelectionFormatMenuItemFactory,
ClearSelectionMenuItemFactory,
@@ -171,7 +169,6 @@ import {
CutMenuItemFactory,
FitContentMenuItemFactory,
FontFamilySelectorMenuItemFactory,
- FormatPainterMenuItemFactory,
HideColMenuItemFactory,
HideRowMenuItemFactory,
HorizontalAlignMenuItemFactory,
@@ -230,18 +227,6 @@ import { ZOOM_RATIO_MENU_ID, ZoomRatioMenuItemFactory } from './zoom.menu';
export const menuSchema: MenuSchemaType = {
[RibbonPosition.START]: {
- [RibbonStartGroup.HISTORY]: {
- [SetOnceFormatPainterCommand.id]: {
- order: 2,
- gridLayout: { row: 1, column: 2, showLabel: true },
- menuItemFactory: FormatPainterMenuItemFactory,
- },
- [ClearSelectionAllCommand.id]: {
- order: 3,
- gridLayout: { row: 2, column: 2, showLabel: true },
- menuItemFactory: ClearSelectionAllToolbarMenuItemFactory,
- },
- },
[RibbonStartGroup.FORMAT]: {
[SetRangeFontFamilyCommand.id]: {
order: 1,
diff --git a/packages/ui/README.md b/packages/ui/README.md
index df24a611a9..035b55c5d8 100644
--- a/packages/ui/README.md
+++ b/packages/ui/README.md
@@ -39,6 +39,22 @@ Exported plugin classes:
- `UniverUIPlugin`
- `UniverMobileUIPlugin`
+## Format painter
+
+The desktop Start ribbon has one format painter entry. A single click captures a detached
+format snapshot for one application; a double click keeps it active until Escape or another
+click on the entry. Unsupported targets do not consume the snapshot. The canvas displays a
+brush cursor on supported targets and an unavailable cursor elsewhere.
+
+`FormatPainterSessionService` coordinates the local session. Host adapters claim the active
+editing context and apply formatting through their domain commands. A higher-priority shape
+selection prevents a stale cell selection from becoming the source. Changing the focused
+Unit or disposing the source Unit cancels the session. The session itself is not persisted.
+
+The icon-only clear-formatting button below the format painter resets the active domain's
+formatting without removing content. Clearing cancels an active brush; each domain applies
+the change through its undoable commands.
+
## Resources
- [Documentation](https://docs.univer.ai)
diff --git a/packages/ui/src/controllers/components.controller.ts b/packages/ui/src/controllers/components.controller.ts
index ea4e5ffb68..3c7ebff08f 100644
--- a/packages/ui/src/controllers/components.controller.ts
+++ b/packages/ui/src/controllers/components.controller.ts
@@ -17,6 +17,8 @@
import { Disposable, Inject } from '@univerjs/core';
import { ColorPicker } from '@univerjs/design';
import {
+ BrushIcon,
+ ClearFormatDoubleIcon,
ExpandIcon,
FeatureSearchIcon,
IncreaseIcon,
@@ -63,6 +65,8 @@ export class ComponentsController extends Disposable {
private _registerIcons(): void {
this.disposeWithMe(this._iconManager.register({
+ BrushIcon,
+ ClearFormatDoubleIcon,
ExpandIcon,
IncreaseIcon,
KeyboardIcon,
diff --git a/packages/ui/src/controllers/format-painter.controller.ts b/packages/ui/src/controllers/format-painter.controller.ts
new file mode 100644
index 0000000000..156026e705
--- /dev/null
+++ b/packages/ui/src/controllers/format-painter.controller.ts
@@ -0,0 +1,91 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { ICommand, IOperation } from '@univerjs/core';
+import { CommandType, Disposable, ICommandService, Inject, IUniverInstanceService } from '@univerjs/core';
+import { fromGlobalEvent } from '../common/lifecycle';
+import { FORMAT_PAINTER_CURSOR_CSS } from '../services/format-painter/format-painter-canvas';
+import { FormatPainterSessionService } from '../services/format-painter/format-painter-session.service';
+import { KeyCode } from '../services/shortcut/keycode';
+import { IShortcutService } from '../services/shortcut/shortcut.service';
+
+export const ActivateFormatPainterOperation: IOperation = {
+ id: 'ui.operation.activate-format-painter',
+ type: CommandType.OPERATION,
+ handler: (accessor) => accessor.get(FormatPainterSessionService).activate(),
+};
+export const ContinuousFormatPainterOperation: IOperation = {
+ id: 'ui.operation.continuous-format-painter',
+ type: CommandType.OPERATION,
+ handler: (accessor) => accessor.get(FormatPainterSessionService).activate(true),
+};
+export const ClearFormattingCommand: ICommand = {
+ id: 'ui.command.clear-formatting',
+ type: CommandType.COMMAND,
+ handler: (accessor) => accessor.get(FormatPainterSessionService).clearFormatting(),
+};
+const CancelFormatPainterOperation: IOperation = {
+ id: 'ui.operation.cancel-format-painter',
+ type: CommandType.OPERATION,
+ handler: (accessor) => {
+ accessor.get(FormatPainterSessionService).cancel();
+ return true;
+ },
+};
+
+export class FormatPainterController extends Disposable {
+ constructor(
+ @Inject(FormatPainterSessionService) session: FormatPainterSessionService,
+ @ICommandService commandService: ICommandService,
+ @IShortcutService shortcutService: IShortcutService,
+ @IUniverInstanceService instanceService: IUniverInstanceService
+ ) {
+ super();
+ const cursorStyle = document.createElement('style');
+ cursorStyle.textContent = FORMAT_PAINTER_CURSOR_CSS;
+ document.head.appendChild(cursorStyle);
+ this.disposeWithMe({ dispose: () => cursorStyle.remove() });
+ for (const command of [ActivateFormatPainterOperation, ContinuousFormatPainterOperation, CancelFormatPainterOperation, ClearFormattingCommand]) {
+ this.disposeWithMe(commandService.registerCommand(command));
+ }
+ this.disposeWithMe(shortcutService.registerShortcut({
+ id: CancelFormatPainterOperation.id,
+ binding: KeyCode.ESC,
+ priority: 1000,
+ preconditions: () => session.mode !== 'off',
+ }));
+ // Ribbon buttons intentionally bypass the canvas shortcut router.
+ this.disposeWithMe(fromGlobalEvent('keydown', (event: KeyboardEvent) => {
+ if (event.key === 'Escape' && session.mode !== 'off' && event.target instanceof HTMLElement &&
+ event.target.closest(`[data-u-command="${ActivateFormatPainterOperation.id}"]`)) {
+ commandService.syncExecuteCommand(CancelFormatPainterOperation.id);
+ event.preventDefault();
+ event.stopPropagation();
+ }
+ }, { capture: true }));
+ this.disposeWithMe(instanceService.unitDisposed$.subscribe((unit) => {
+ if (unit.getUnitId() === session.unitId) {
+ session.cancel();
+ }
+ }));
+ this.disposeWithMe(instanceService.focused$.subscribe((unitId) => {
+ if (unitId && session.unitId && unitId !== session.unitId) {
+ session.cancel();
+ }
+ session.refresh();
+ }));
+ }
+}
diff --git a/packages/ui/src/index.ts b/packages/ui/src/index.ts
index 849a3d2ca5..309fe6cc65 100644
--- a/packages/ui/src/index.ts
+++ b/packages/ui/src/index.ts
@@ -77,6 +77,9 @@ export type {
} from './services/dom/canvas-dom-layer.service';
export { FontService, IFontService } from './services/font.service';
export type { IFontConfig } from './services/font.service';
+export { bindFormatPainterCanvas } from './services/format-painter/format-painter-canvas';
+export { FormatPainterSessionService } from './services/format-painter/format-painter-session.service';
+export type { IFormatPainterTarget } from './services/format-painter/format-painter-session.service';
export { DesktopGalleryService } from './services/gallery/desktop-gallery.service';
export { IGalleryService } from './services/gallery/gallery.service';
export { DesktopLayoutService, ILayoutService } from './services/layout/layout.service';
diff --git a/packages/ui/src/locale/ar-SA.ts b/packages/ui/src/locale/ar-SA.ts
index 62d9187f83..624a325538 100644
--- a/packages/ui/src/locale/ar-SA.ts
+++ b/packages/ui/src/locale/ar-SA.ts
@@ -19,6 +19,8 @@ import emojiLocale from './emoji-locale/ar-SA.generated';
const locale: typeof enUS = {
ui: {
+ clearFormatting: 'مسح التنسيق',
+ formatPainter: 'نسخ التنسيق',
accessibility: {
menu: 'القائمة',
zoom: 'التكبير والتصغير',
diff --git a/packages/ui/src/locale/ca-ES.ts b/packages/ui/src/locale/ca-ES.ts
index ecbec08ebf..284a6b360f 100644
--- a/packages/ui/src/locale/ca-ES.ts
+++ b/packages/ui/src/locale/ca-ES.ts
@@ -19,6 +19,8 @@ import emojiLocale from './emoji-locale/ca-ES.generated';
const locale: typeof enUS = {
ui: {
+ clearFormatting: 'Esborra el format',
+ formatPainter: 'Copia el format',
accessibility: {
menu: 'Menú',
zoom: 'Zoom',
diff --git a/packages/ui/src/locale/de-DE.ts b/packages/ui/src/locale/de-DE.ts
index 98565856e3..f32cf7d3c7 100644
--- a/packages/ui/src/locale/de-DE.ts
+++ b/packages/ui/src/locale/de-DE.ts
@@ -19,6 +19,8 @@ import emojiLocale from './emoji-locale/de-DE.generated';
const locale: typeof enUS = {
ui: {
+ clearFormatting: 'Formatierung löschen',
+ formatPainter: 'Format übertragen',
accessibility: {
menu: 'Menü',
zoom: 'Zoom',
diff --git a/packages/ui/src/locale/en-US.ts b/packages/ui/src/locale/en-US.ts
index 6e9de1eac5..a153f76b2d 100644
--- a/packages/ui/src/locale/en-US.ts
+++ b/packages/ui/src/locale/en-US.ts
@@ -18,6 +18,8 @@ import emojiLocale from './emoji-locale/en-US.generated';
const locale = {
ui: {
+ clearFormatting: 'Clear formatting',
+ formatPainter: 'Format Painter',
accessibility: {
menu: 'Menu',
zoom: 'Zoom',
diff --git a/packages/ui/src/locale/es-ES.ts b/packages/ui/src/locale/es-ES.ts
index 38485236c5..679436c193 100644
--- a/packages/ui/src/locale/es-ES.ts
+++ b/packages/ui/src/locale/es-ES.ts
@@ -19,6 +19,8 @@ import emojiLocale from './emoji-locale/es-ES.generated';
const locale: typeof enUS = {
ui: {
+ clearFormatting: 'Borrar formato',
+ formatPainter: 'Copiar formato',
accessibility: {
menu: 'Menú',
zoom: 'Zoom',
diff --git a/packages/ui/src/locale/fa-IR.ts b/packages/ui/src/locale/fa-IR.ts
index ad2a4e32ae..0f5244436e 100644
--- a/packages/ui/src/locale/fa-IR.ts
+++ b/packages/ui/src/locale/fa-IR.ts
@@ -19,6 +19,8 @@ import emojiLocale from './emoji-locale/fa-IR.generated';
const locale: typeof enUS = {
ui: {
+ clearFormatting: 'پاک کردن قالب\u200Cبندی',
+ formatPainter: 'کپی قالب‌بندی',
accessibility: {
menu: 'منو',
zoom: 'بزرگ‌نمایی',
diff --git a/packages/ui/src/locale/fr-FR.ts b/packages/ui/src/locale/fr-FR.ts
index 905fa30d52..7664fad225 100644
--- a/packages/ui/src/locale/fr-FR.ts
+++ b/packages/ui/src/locale/fr-FR.ts
@@ -19,6 +19,8 @@ import emojiLocale from './emoji-locale/fr-FR.generated';
const locale: typeof enUS = {
ui: {
+ clearFormatting: 'Effacer la mise en forme',
+ formatPainter: 'Reproduire la mise en forme',
accessibility: {
menu: 'Menu',
zoom: 'Zoom',
diff --git a/packages/ui/src/locale/id-ID.ts b/packages/ui/src/locale/id-ID.ts
index 8bf7e1439f..c311837ba2 100644
--- a/packages/ui/src/locale/id-ID.ts
+++ b/packages/ui/src/locale/id-ID.ts
@@ -19,6 +19,8 @@ import emojiLocale from './emoji-locale/id-ID.generated';
const locale: typeof enUS = {
ui: {
+ clearFormatting: 'Hapus pemformatan',
+ formatPainter: 'Salin Format',
accessibility: {
menu: 'Menu',
zoom: 'Zoom',
diff --git a/packages/ui/src/locale/it-IT.ts b/packages/ui/src/locale/it-IT.ts
index 119dc4d51f..829619c9a7 100644
--- a/packages/ui/src/locale/it-IT.ts
+++ b/packages/ui/src/locale/it-IT.ts
@@ -19,6 +19,8 @@ import emojiLocale from './emoji-locale/it-IT.generated';
const locale: typeof enUS = {
ui: {
+ clearFormatting: 'Cancella formattazione',
+ formatPainter: 'Copia formato',
accessibility: {
menu: 'Menu',
zoom: 'Zoom',
diff --git a/packages/ui/src/locale/ja-JP.ts b/packages/ui/src/locale/ja-JP.ts
index d59dbfeecf..0d9de50653 100644
--- a/packages/ui/src/locale/ja-JP.ts
+++ b/packages/ui/src/locale/ja-JP.ts
@@ -19,6 +19,8 @@ import emojiLocale from './emoji-locale/ja-JP.generated';
const locale: typeof enUS = {
ui: {
+ clearFormatting: '書式をクリア',
+ formatPainter: '書式のコピー',
accessibility: {
menu: 'メニュー',
zoom: 'ズーム',
diff --git a/packages/ui/src/locale/ko-KR.ts b/packages/ui/src/locale/ko-KR.ts
index a2f593cfde..06b335a203 100644
--- a/packages/ui/src/locale/ko-KR.ts
+++ b/packages/ui/src/locale/ko-KR.ts
@@ -19,6 +19,8 @@ import emojiLocale from './emoji-locale/ko-KR.generated';
const locale: typeof enUS = {
ui: {
+ clearFormatting: '서식 지우기',
+ formatPainter: '서식 복사',
accessibility: {
menu: '메뉴',
zoom: '확대/축소',
diff --git a/packages/ui/src/locale/pl-PL.ts b/packages/ui/src/locale/pl-PL.ts
index c84e6411d8..93996b9206 100644
--- a/packages/ui/src/locale/pl-PL.ts
+++ b/packages/ui/src/locale/pl-PL.ts
@@ -19,6 +19,8 @@ import emojiLocale from './emoji-locale/pl-PL.generated';
const locale: typeof enUS = {
ui: {
+ clearFormatting: 'Wyczyść formatowanie',
+ formatPainter: 'Malarz formatów',
accessibility: {
menu: 'Menu',
zoom: 'Powiększenie',
diff --git a/packages/ui/src/locale/pt-BR.ts b/packages/ui/src/locale/pt-BR.ts
index 81044a4ca5..cd8ce6d5e4 100644
--- a/packages/ui/src/locale/pt-BR.ts
+++ b/packages/ui/src/locale/pt-BR.ts
@@ -19,6 +19,8 @@ import emojiLocale from './emoji-locale/pt-BR.generated';
const locale: typeof enUS = {
ui: {
+ clearFormatting: 'Limpar formatação',
+ formatPainter: 'Pincel de Formatação',
accessibility: {
menu: 'Menu',
zoom: 'Zoom',
diff --git a/packages/ui/src/locale/ru-RU.ts b/packages/ui/src/locale/ru-RU.ts
index 9666e3f9c8..3b2bc04a47 100644
--- a/packages/ui/src/locale/ru-RU.ts
+++ b/packages/ui/src/locale/ru-RU.ts
@@ -19,6 +19,8 @@ import emojiLocale from './emoji-locale/ru-RU.generated';
const locale: typeof enUS = {
ui: {
+ clearFormatting: 'Очистить форматирование',
+ formatPainter: 'Формат по образцу',
accessibility: {
menu: 'Меню',
zoom: 'Масштаб',
diff --git a/packages/ui/src/locale/sk-SK.ts b/packages/ui/src/locale/sk-SK.ts
index 99c819cb85..6518aba29f 100644
--- a/packages/ui/src/locale/sk-SK.ts
+++ b/packages/ui/src/locale/sk-SK.ts
@@ -19,6 +19,8 @@ import emojiLocale from './emoji-locale/sk-SK.generated';
const locale: typeof enUS = {
ui: {
+ clearFormatting: 'Vymazať formátovanie',
+ formatPainter: 'Kopírovať formát',
accessibility: {
menu: 'Ponuka',
zoom: 'Priblíženie',
diff --git a/packages/ui/src/locale/vi-VN.ts b/packages/ui/src/locale/vi-VN.ts
index 147872d2ab..129bef4d32 100644
--- a/packages/ui/src/locale/vi-VN.ts
+++ b/packages/ui/src/locale/vi-VN.ts
@@ -19,6 +19,8 @@ import emojiLocale from './emoji-locale/vi-VN.generated';
const locale: typeof enUS = {
ui: {
+ clearFormatting: 'Xóa định dạng',
+ formatPainter: 'Sao chép định dạng',
accessibility: {
menu: 'Trình đơn',
zoom: 'Thu phóng',
diff --git a/packages/ui/src/locale/zh-CN.ts b/packages/ui/src/locale/zh-CN.ts
index 54e84f33f0..b00ba46477 100644
--- a/packages/ui/src/locale/zh-CN.ts
+++ b/packages/ui/src/locale/zh-CN.ts
@@ -19,6 +19,8 @@ import emojiLocale from './emoji-locale/zh-CN.generated';
const locale: typeof enUS = {
ui: {
+ clearFormatting: '清除格式',
+ formatPainter: '格式刷',
accessibility: {
menu: '菜单',
zoom: '缩放',
diff --git a/packages/ui/src/locale/zh-HK.ts b/packages/ui/src/locale/zh-HK.ts
index eea7bc5d32..2f688d8594 100644
--- a/packages/ui/src/locale/zh-HK.ts
+++ b/packages/ui/src/locale/zh-HK.ts
@@ -19,6 +19,8 @@ import emojiLocale from './emoji-locale/zh-HK.generated';
const locale: typeof enUS = {
ui: {
+ clearFormatting: '清除格式',
+ formatPainter: '複製格式',
accessibility: {
menu: '選單',
zoom: '縮放',
diff --git a/packages/ui/src/locale/zh-TW.ts b/packages/ui/src/locale/zh-TW.ts
index 2e974c2296..4f2fc4fa9f 100644
--- a/packages/ui/src/locale/zh-TW.ts
+++ b/packages/ui/src/locale/zh-TW.ts
@@ -19,6 +19,8 @@ import emojiLocale from './emoji-locale/zh-TW.generated';
const locale: typeof enUS = {
ui: {
+ clearFormatting: '清除格式',
+ formatPainter: '複製格式',
accessibility: {
menu: '選單',
zoom: '縮放',
diff --git a/packages/ui/src/menu/format-painter.menu.ts b/packages/ui/src/menu/format-painter.menu.ts
new file mode 100644
index 0000000000..4141eaeed0
--- /dev/null
+++ b/packages/ui/src/menu/format-painter.menu.ts
@@ -0,0 +1,52 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { IAccessor } from '@univerjs/core';
+import type { IMenuButtonItem } from '../services/menu/menu';
+import { map } from 'rxjs';
+import {
+ ActivateFormatPainterOperation,
+ ClearFormattingCommand,
+ ContinuousFormatPainterOperation,
+} from '../controllers/format-painter.controller';
+import { FormatPainterSessionService } from '../services/format-painter/format-painter-session.service';
+import { MenuItemType } from '../services/menu/menu';
+
+export function FormatPainterMenuItemFactory(accessor: IAccessor): IMenuButtonItem {
+ const session = accessor.get(FormatPainterSessionService);
+ return {
+ id: ActivateFormatPainterOperation.id,
+ subId: ContinuousFormatPainterOperation.id,
+ type: MenuItemType.BUTTON,
+ icon: 'BrushIcon',
+ title: 'ui.formatPainter',
+ tooltip: 'ui.formatPainter',
+ activated$: session.state$.pipe(map((mode) => mode !== 'off')),
+ disabled$: session.state$.pipe(map((mode) => mode === 'off' && !session.canStart())),
+ };
+}
+
+export function ClearFormattingMenuItemFactory(accessor: IAccessor): IMenuButtonItem {
+ const session = accessor.get(FormatPainterSessionService);
+ return {
+ id: ClearFormattingCommand.id,
+ type: MenuItemType.BUTTON,
+ icon: 'ClearFormatDoubleIcon',
+ title: 'ui.clearFormatting',
+ tooltip: 'ui.clearFormatting',
+ disabled$: session.state$.pipe(map(() => !session.canClear())),
+ };
+}
diff --git a/packages/ui/src/menu/schema.ts b/packages/ui/src/menu/schema.ts
index 25145ff1ff..f1290e835c 100644
--- a/packages/ui/src/menu/schema.ts
+++ b/packages/ui/src/menu/schema.ts
@@ -18,13 +18,25 @@ import type { MenuSchemaType } from '../services/menu/menu-manager.service';
import { RedoCommand, UndoCommand } from '@univerjs/core';
import { OpenFeatureSearchOperation } from '../commands/operations/open-feature-search.operation';
import { ToggleShortcutPanelOperation } from '../commands/operations/toggle-shortcut-panel.operation';
+import { ActivateFormatPainterOperation, ClearFormattingCommand } from '../controllers/format-painter.controller';
import { RibbonStartGroup } from '../services/menu/types';
import { FeatureSearchMenuItemFactory } from './feature-search.menu';
+import { ClearFormattingMenuItemFactory, FormatPainterMenuItemFactory } from './format-painter.menu';
import { RedoMenuItemFactory, UndoMenuItemFactory } from './history.menu';
import { ShortcutPanelMenuItemFactory } from './shortcut-panel.menu';
export const menuSchema: MenuSchemaType = {
[RibbonStartGroup.HISTORY]: {
+ [ActivateFormatPainterOperation.id]: {
+ order: 2,
+ gridLayout: { row: 1, column: 2, showLabel: false },
+ menuItemFactory: FormatPainterMenuItemFactory,
+ },
+ [ClearFormattingCommand.id]: {
+ order: 3,
+ gridLayout: { row: 2, column: 2, showLabel: false },
+ menuItemFactory: ClearFormattingMenuItemFactory,
+ },
[UndoCommand.id]: {
order: 0,
gridLayout: { row: 1, column: 1, iconSize: 18 },
diff --git a/packages/ui/src/mobile-plugin.ts b/packages/ui/src/mobile-plugin.ts
index 8a3dfd30d4..f789d6b33a 100644
--- a/packages/ui/src/mobile-plugin.ts
+++ b/packages/ui/src/mobile-plugin.ts
@@ -38,6 +38,7 @@ import { ZIndexManager } from './common/z-index-manager';
import { defaultPluginConfig, UI_PLUGIN_CONFIG_KEY } from './config/config';
import { MOBILE_UI_MODE } from './const';
import { ErrorController } from './controllers/error/error.controller';
+import { FormatPainterController } from './controllers/format-painter.controller';
import { MobileComponentsController } from './controllers/mobile/components.controller';
import { SharedController } from './controllers/shared-shortcut.controller';
import { MobileUIController } from './controllers/ui/ui-mobile.controller';
@@ -51,6 +52,7 @@ import { IDialogService } from './services/dialog/dialog.service';
import { MobileDialogService } from './services/dialog/mobile-dialog.service';
import { CanvasFloatDomPreviewService, CanvasFloatDomService } from './services/dom/canvas-dom-layer.service';
import { FontService, IFontService } from './services/font.service';
+import { FormatPainterSessionService } from './services/format-painter/format-painter-session.service';
import { DesktopGalleryService } from './services/gallery/desktop-gallery.service';
import { IGalleryService } from './services/gallery/gallery.service';
import { DesktopLayoutService, ILayoutService } from './services/layout/layout.service';
@@ -159,6 +161,8 @@ export class UniverMobileUIPlugin extends Plugin {
deps: [Injector],
},
],
+ [FormatPainterSessionService],
+ [FormatPainterController],
[SharedController],
[ErrorController],
], this._config.override));
@@ -173,6 +177,7 @@ export class UniverMobileUIPlugin extends Plugin {
override onReady(): void {
touchDependencies(this._injector, [
[SharedController],
+ [FormatPainterController],
]);
}
}
diff --git a/packages/ui/src/plugin.ts b/packages/ui/src/plugin.ts
index 5b612cb1d6..c78144e813 100644
--- a/packages/ui/src/plugin.ts
+++ b/packages/ui/src/plugin.ts
@@ -39,6 +39,7 @@ import { defaultPluginConfig, UI_PLUGIN_CONFIG_KEY } from './config/config';
import { ComponentsController } from './controllers/components.controller';
import { ErrorController } from './controllers/error/error.controller';
import { FeatureSearchController } from './controllers/feature-search/feature-search.controller';
+import { FormatPainterController } from './controllers/format-painter.controller';
import { SharedController } from './controllers/shared-shortcut.controller';
import { ShortcutPanelController } from './controllers/shortcut-display/shortcut-panel.controller';
import { DesktopUIController } from './controllers/ui/ui-desktop.controller';
@@ -52,6 +53,7 @@ import { DesktopDialogService } from './services/dialog/desktop-dialog.service';
import { IDialogService } from './services/dialog/dialog.service';
import { CanvasFloatDomPreviewService, CanvasFloatDomService } from './services/dom/canvas-dom-layer.service';
import { FontService, IFontService } from './services/font.service';
+import { FormatPainterSessionService } from './services/format-painter/format-painter-session.service';
import { DesktopGalleryService } from './services/gallery/desktop-gallery.service';
import { IGalleryService } from './services/gallery/gallery.service';
import { DesktopLayoutService, ILayoutService } from './services/layout/layout.service';
@@ -158,6 +160,8 @@ export class UniverUIPlugin extends Plugin {
useFactory: (injector: Injector) => injector.createInstance(DesktopUIController, this._config),
deps: [Injector],
}],
+ [FormatPainterSessionService],
+ [FormatPainterController],
[SharedController],
[ErrorController],
[FeatureSearchController],
@@ -174,6 +178,7 @@ export class UniverUIPlugin extends Plugin {
override onReady(): void {
touchDependencies(this._injector, [
[SharedController],
+ [FormatPainterController],
[FeatureSearchController],
]);
}
diff --git a/packages/ui/src/services/format-painter/__tests__/format-painter-canvas.spec.ts b/packages/ui/src/services/format-painter/__tests__/format-painter-canvas.spec.ts
new file mode 100644
index 0000000000..a75311bed8
--- /dev/null
+++ b/packages/ui/src/services/format-painter/__tests__/format-painter-canvas.spec.ts
@@ -0,0 +1,120 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { Injector } from '@univerjs/core';
+import { Subject } from 'rxjs';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { bindFormatPainterCanvas } from '../format-painter-canvas';
+import { FormatPainterSessionService } from '../format-painter-session.service';
+
+const cleanups: Array<() => void> = [];
+afterEach(() => {
+ cleanups.splice(0).reverse().forEach((dispose) => dispose());
+ vi.useRealTimers();
+});
+
+function setup(intercept = false) {
+ vi.useFakeTimers();
+ const injector = new Injector([[FormatPainterSessionService]]);
+ cleanups.push(() => injector.dispose());
+ const session = injector.get(FormatPainterSessionService);
+ const canvas = document.createElement('canvas');
+ document.body.appendChild(canvas);
+ cleanups.push(() => canvas.remove());
+ const applied: string[] = [];
+ let selection = 'source';
+ let compatible = true;
+ session.register({
+ id: 'text',
+ priority: 0,
+ changes$: new Subject(),
+ isActive: () => true,
+ canStart: () => true,
+ capture: () => ({ unitId: 'doc', apply: (target) => {
+ applied.push(target.shapeId!);
+ return true;
+ } }),
+ });
+ const binding = bindFormatPainterCanvas(canvas, session, {
+ adapterId: 'text',
+ unitId: 'doc',
+ intercept,
+ getTarget: () => compatible ? { unitId: 'doc', shapeId: selection } : null,
+ });
+ cleanups.push(() => binding.dispose());
+ const gesture = () => {
+ canvas.dispatchEvent(new MouseEvent('pointerdown', { bubbles: true, button: 0 }));
+ canvas.dispatchEvent(new MouseEvent('pointerup', { bubbles: true, button: 0 }));
+ };
+ return {
+ session,
+ canvas,
+ applied,
+ gesture,
+ binding,
+ setSelection: (value: string) => {
+ selection = value;
+ },
+ setCompatible: (value: boolean) => {
+ compatible = value;
+ },
+ };
+}
+
+describe('format painter canvas gestures', () => {
+ it('waits for native selection handlers before applying and restores the cursor after one use', async () => {
+ const bed = setup();
+ bed.canvas.addEventListener('pointerup', () => bed.setSelection('target'));
+ bed.session.activate();
+ expect(bed.canvas.dataset.formatPainter).toBe('available');
+ bed.gesture();
+ expect(bed.applied).toEqual([]);
+ await vi.runAllTimersAsync();
+ expect(bed.applied).toEqual(['target']);
+ expect(bed.session.mode).toBe('off');
+ expect(bed.canvas.dataset.formatPainter).toBeUndefined();
+ });
+
+ it('does not consume a continuous brush or select an incompatible object', async () => {
+ const bed = setup(true);
+ let selected = false;
+ bed.canvas.addEventListener('pointerdown', () => {
+ selected = true;
+ });
+ bed.session.activate(true);
+ bed.setCompatible(false);
+ bed.canvas.dispatchEvent(new MouseEvent('pointermove', { bubbles: true }));
+ expect(bed.canvas.dataset.formatPainter).toBe('unavailable');
+ bed.gesture();
+ await vi.runAllTimersAsync();
+ expect(bed.applied).toEqual([]);
+ expect(selected).toBe(false);
+ expect(bed.session.mode).toBe('continuous');
+ });
+
+ it('cancels deferred work and releases the cursor and listeners on disposal', async () => {
+ const bed = setup();
+ bed.session.activate();
+ bed.gesture();
+ bed.binding.dispose();
+ await vi.runAllTimersAsync();
+ expect(bed.applied).toEqual([]);
+ expect(bed.canvas.dataset.formatPainter).toBeUndefined();
+ bed.gesture();
+ await vi.runAllTimersAsync();
+ expect(bed.applied).toEqual([]);
+ });
+});
diff --git a/packages/ui/src/services/format-painter/__tests__/format-painter-session.service.spec.ts b/packages/ui/src/services/format-painter/__tests__/format-painter-session.service.spec.ts
new file mode 100644
index 0000000000..d2ff3494ee
--- /dev/null
+++ b/packages/ui/src/services/format-painter/__tests__/format-painter-session.service.spec.ts
@@ -0,0 +1,148 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { Injector } from '@univerjs/core';
+import { Subject } from 'rxjs';
+import { afterEach, describe, expect, it } from 'vitest';
+import { FormatPainterSessionService } from '../format-painter-session.service';
+
+const injectors: Injector[] = [];
+function setup() {
+ const injector = new Injector([[FormatPainterSessionService]]);
+ injectors.push(injector);
+ return injector.get(FormatPainterSessionService);
+}
+afterEach(() => {
+ injectors.splice(0).forEach((injector) => injector.dispose());
+});
+
+describe('format painter sessions', () => {
+ it('upgrades single-click to continuous without sampling again, and retains its snapshot', async () => {
+ const session = setup();
+ let style = 'red';
+ let samples = 0;
+ const applied: string[] = [];
+ session.register({
+ id: 'shape',
+ priority: 10,
+ changes$: new Subject(),
+ isActive: () => true,
+ canStart: () => true,
+ capture: () => {
+ samples++;
+ const snapshot = style;
+ return { unitId: 'unit', apply: () => {
+ applied.push(snapshot);
+ return true;
+ } };
+ },
+ });
+ expect(session.activate()).toBe(true);
+ style = 'blue';
+ session.activate(true);
+ await session.apply('shape', { unitId: 'unit' });
+ await session.apply('shape', { unitId: 'unit' });
+ expect(applied).toEqual(['red', 'red']);
+ expect(samples).toBe(1);
+ expect(session.mode).toBe('continuous');
+ session.activate();
+ expect(session.mode).toBe('off');
+ });
+
+ it('exits once only after successful application and rejects other domains or units', async () => {
+ const session = setup();
+ let success = false;
+ session.register({
+ id: 'text',
+ priority: 1,
+ changes$: new Subject(),
+ isActive: () => true,
+ canStart: () => true,
+ capture: () => ({ unitId: 'unit', apply: () => success }),
+ });
+ session.activate();
+ expect(await session.apply('cell', { unitId: 'unit' })).toBe(false);
+ expect(await session.apply('text', { unitId: 'other' })).toBe(false);
+ expect(await session.apply('text', { unitId: 'unit' })).toBe(false);
+ expect(session.mode).toBe('once');
+ success = true;
+ expect(await session.apply('text', { unitId: 'unit' })).toBe(true);
+ expect(session.mode).toBe('off');
+ });
+
+ it('does not fall through to a stale cell selection when a shape selection cannot be sampled', () => {
+ const session = setup();
+ const changes$ = new Subject();
+ session.register({ id: 'cell', priority: 0, changes$, isActive: () => true, canStart: () => true, capture: () => ({ unitId: 'u', apply: () => true }) });
+ session.register({ id: 'shape', priority: 100, changes$, isActive: () => true, canStart: () => false, capture: () => null });
+ expect(session.canStart()).toBe(false);
+ expect(session.activate()).toBe(false);
+ });
+
+ it('clears the active editing domain, cancels the brush and never falls through to stale cells', async () => {
+ const session = setup();
+ let cellsCleared = 0;
+ let shapesCleared = 0;
+ let editable = false;
+ const changes$ = new Subject();
+ session.register({ id: 'cell', priority: 0, changes$, isActive: () => true, canStart: () => true, capture: () => null, clear: () => {
+ cellsCleared++;
+ return true;
+ } });
+ session.register({
+ id: 'shape',
+ priority: 100,
+ changes$,
+ isActive: () => true,
+ canStart: () => editable,
+ capture: () => ({ unitId: 'u', apply: () => true }),
+ clear: () => {
+ shapesCleared++;
+ return true;
+ },
+ });
+ expect(session.canClear()).toBe(false);
+ expect(await session.clearFormatting()).toBe(false);
+ editable = true;
+ session.activate(true);
+ expect(session.canClear()).toBe(true);
+ expect(await session.clearFormatting()).toBe(true);
+ expect(session.mode).toBe('off');
+ expect(shapesCleared).toBe(1);
+ expect(cellsCleared).toBe(0);
+ });
+
+ it('does not let an old asynchronous application cancel a new session', async () => {
+ const session = setup();
+ let finish!: (success: boolean) => void;
+ session.register({
+ id: 'shape',
+ priority: 1,
+ changes$: new Subject(),
+ isActive: () => true,
+ canStart: () => true,
+ capture: () => ({ unitId: 'unit', apply: () => new Promise<boolean>((resolve) => { finish = resolve; }) }),
+ });
+ session.activate();
+ const pending = session.apply('shape', { unitId: 'unit' });
+ expect(await session.apply('shape', { unitId: 'unit' })).toBe(false);
+ session.cancel();
+ session.activate();
+ finish(true);
+ await pending;
+ expect(session.mode).toBe('once');
+ });
+});
diff --git a/packages/ui/src/services/format-painter/format-painter-canvas.ts b/packages/ui/src/services/format-painter/format-painter-canvas.ts
new file mode 100644
index 0000000000..36d0113b42
--- /dev/null
+++ b/packages/ui/src/services/format-painter/format-painter-canvas.ts
@@ -0,0 +1,117 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { IDisposable } from '@univerjs/core';
+import type { FormatPainterSessionService, IFormatPainterTarget } from './format-painter-session.service';
+
+export const FORMAT_PAINTER_CURSOR_CSS = `
+/* Keep the brush visible while the render engine updates its usual object/text cursors. */
+canvas[data-format-painter="available"] {
+ cursor: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='28' height='28' viewBox='0 0 28 28'%3E%3Cpath d='M2 1v18l4-4 3 7 3-2-3-6h6z' fill='white' stroke='black'/%3E%3Cpath d='m17 13 8-10 2 2-8 10z' fill='white' stroke='black'/%3E%3Cpath d='M17 14c-4 0-2 5-6 6 5 2 10-1 8-5z' fill='black' stroke='white'/%3E%3C/svg%3E") 2 1, crosshair !important;
+}
+canvas[data-format-painter="unavailable"] {
+ cursor: not-allowed !important;
+}
+`;
+
+interface IFormatPainterCanvasOptions {
+ adapterId: string;
+ unitId: string;
+ getUnitId?(): string;
+ /** Object painting consumes the gesture before selection/transform handlers run. */
+ intercept: boolean;
+ getTarget(event: PointerEvent): IFormatPainterTarget | null;
+}
+
+export function bindFormatPainterCanvas(
+ canvas: HTMLCanvasElement,
+ session: FormatPainterSessionService,
+ options: IFormatPainterCanvasOptions
+): IDisposable {
+ let pressed = false;
+ let applyTask: ReturnType<typeof setTimeout> | undefined;
+ const active = () => session.isActive(options.adapterId) && session.unitId === (options.getUnitId?.() ?? options.unitId);
+ const updateCursor = (event?: PointerEvent) => {
+ if (active()) {
+ canvas.dataset.formatPainter = event && !options.getTarget(event) ? 'unavailable' : 'available';
+ }
+ };
+ const subscription = session.state$.subscribe(() => {
+ if (active()) {
+ updateCursor();
+ } else if (session.mode === 'off') {
+ delete canvas.dataset.formatPainter;
+ pressed = false;
+ clearTimeout(applyTask);
+ }
+ });
+ const down = (event: PointerEvent) => {
+ if (!active() || event.button !== 0) {
+ return;
+ }
+ pressed = !!options.getTarget(event);
+ if (options.intercept || !pressed) {
+ canvas.focus();
+ event.preventDefault();
+ event.stopImmediatePropagation();
+ }
+ };
+ const up = (event: PointerEvent) => {
+ if (!active() || !pressed || event.button !== 0) {
+ return;
+ }
+ pressed = false;
+ if (options.intercept) {
+ event.preventDefault();
+ event.stopImmediatePropagation();
+ }
+ // Native event callbacks run microtasks between capture and bubble listeners.
+ // Wait for the complete event dispatch so text/cell selection has committed.
+ clearTimeout(applyTask);
+ applyTask = setTimeout(() => {
+ const target = active() ? options.getTarget(event) : null;
+ if (target) {
+ session.apply(options.adapterId, target).catch((error: unknown) => console.error('[FormatPainter]', error));
+ }
+ }, 0);
+ };
+ const cancel = () => {
+ pressed = false;
+ };
+ const doubleClick = (event: MouseEvent) => {
+ if (active() && options.intercept) {
+ event.preventDefault();
+ event.stopImmediatePropagation();
+ }
+ };
+ canvas.addEventListener('pointerdown', down, true);
+ canvas.addEventListener('pointerup', up, true);
+ canvas.addEventListener('pointermove', updateCursor, true);
+ canvas.addEventListener('pointercancel', cancel, true);
+ canvas.addEventListener('pointerleave', cancel, true);
+ canvas.addEventListener('dblclick', doubleClick, true);
+ return { dispose: () => {
+ clearTimeout(applyTask);
+ subscription.unsubscribe();
+ canvas.removeEventListener('pointerdown', down, true);
+ canvas.removeEventListener('pointerup', up, true);
+ canvas.removeEventListener('pointermove', updateCursor, true);
+ canvas.removeEventListener('pointercancel', cancel, true);
+ canvas.removeEventListener('pointerleave', cancel, true);
+ canvas.removeEventListener('dblclick', doubleClick, true);
+ delete canvas.dataset.formatPainter;
+ } };
+}
diff --git a/packages/ui/src/services/format-painter/format-painter-session.service.ts b/packages/ui/src/services/format-painter/format-painter-session.service.ts
new file mode 100644
index 0000000000..87f3fa676a
--- /dev/null
+++ b/packages/ui/src/services/format-painter/format-painter-session.service.ts
@@ -0,0 +1,158 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { IDisposable, IRange } from '@univerjs/core';
+import type { Observable } from 'rxjs';
+import { Disposable } from '@univerjs/core';
+import { BehaviorSubject } from 'rxjs';
+
+export type FormatPainterMode = 'off' | 'once' | 'continuous';
+
+export interface IFormatPainterTarget {
+ unitId: string;
+ subUnitId?: string;
+ shapeId?: string;
+ range?: IRange;
+}
+
+export interface IFormatPainterSource {
+ unitId: string;
+ apply(target: IFormatPainterTarget): boolean | Promise<boolean>;
+ onModeChange?(mode: FormatPainterMode): void;
+}
+
+export interface IFormatPainterAdapter {
+ id: string;
+ priority: number;
+ changes$: Observable<unknown>;
+ /** Claim the editing context even when its selection cannot be sampled. */
+ isActive(): boolean;
+ canStart(): boolean;
+ capture(): IFormatPainterSource | null;
+ clear?(): boolean | Promise<boolean>;
+}
+
+/** One local interaction session; domain commands retain ownership of persisted formatting. */
+export class FormatPainterSessionService extends Disposable {
+ private readonly _adapters: IFormatPainterAdapter[] = [];
+ private readonly _state$ = new BehaviorSubject<FormatPainterMode>('off');
+ readonly state$ = this._state$.asObservable();
+ private _session: { adapterId: string; source: IFormatPainterSource } | null = null;
+ private _applying = false;
+
+ get mode(): FormatPainterMode { return this._state$.value; }
+ get unitId(): string | undefined { return this._session?.source.unitId; }
+
+ register(adapter: IFormatPainterAdapter): IDisposable {
+ this._adapters.push(adapter);
+ this._adapters.sort((a, b) => b.priority - a.priority);
+ const subscription = adapter.changes$.subscribe(() => this.refresh());
+ this.refresh();
+ return this.disposeWithMe(() => {
+ subscription.unsubscribe();
+ const index = this._adapters.indexOf(adapter);
+ if (index >= 0) {
+ this._adapters.splice(index, 1);
+ }
+ if (this.isActive(adapter.id)) {
+ this.cancel();
+ }
+ this.refresh();
+ });
+ }
+
+ refresh(): void { this._state$.next(this.mode); }
+ canStart(): boolean { return this._adapters.find((adapter) => adapter.isActive())?.canStart() ?? false; }
+ isActive(adapterId: string): boolean { return this._session?.adapterId === adapterId; }
+
+ canClear(): boolean {
+ const adapter = this._adapters.find((candidate) => candidate.isActive());
+ return !!adapter?.clear && adapter.canStart();
+ }
+
+ async clearFormatting(): Promise<boolean> {
+ const adapter = this._adapters.find((candidate) => candidate.isActive());
+ if (!adapter?.clear || !adapter.canStart() || this._applying) {
+ return false;
+ }
+ this.cancel();
+ this._applying = true;
+ try {
+ return await adapter.clear();
+ } finally {
+ this._applying = false;
+ this.refresh();
+ }
+ }
+
+ activate(continuous = false): boolean {
+ if (this._session) {
+ if (continuous) {
+ this._setMode('continuous');
+ } else {
+ this.cancel();
+ }
+ return true;
+ }
+ const adapter = this._adapters.find((candidate) => candidate.isActive());
+ if (!adapter?.canStart()) {
+ return false;
+ }
+ const source = adapter.capture();
+ if (!source) {
+ return false;
+ }
+ this._session = { adapterId: adapter.id, source };
+ this._setMode(continuous ? 'continuous' : 'once');
+ return true;
+ }
+
+ async apply(adapterId: string, target: IFormatPainterTarget): Promise<boolean> {
+ const session = this._session;
+ if (!session || session.adapterId !== adapterId || target.unitId !== session.source.unitId || this._applying) {
+ return false;
+ }
+ this._applying = true;
+ try {
+ const applied = await session.source.apply(target);
+ if (applied && this._session === session && this.mode === 'once') {
+ this.cancel();
+ }
+ return applied;
+ } finally {
+ this._applying = false;
+ }
+ }
+
+ cancel(): void {
+ const session = this._session;
+ this._session = null;
+ session?.source.onModeChange?.('off');
+ this._state$.next('off');
+ }
+
+ private _setMode(mode: FormatPainterMode): void {
+ this._session?.source.onModeChange?.(mode);
+ this._state$.next(mode);
+ }
+
+ override dispose(): void {
+ this.cancel();
+ this._adapters.length = 0;
+ this._state$.complete();
+ super.dispose();
+ }
+}
diff --git a/packages/ui/src/views/components/ribbon/ToolbarItem.tsx b/packages/ui/src/views/components/ribbon/ToolbarItem.tsx
index 0f92f452ea..3d70cb1c41 100644
--- a/packages/ui/src/views/components/ribbon/ToolbarItem.tsx
+++ b/packages/ui/src/views/components/ribbon/ToolbarItem.tsx
@@ -481,8 +481,13 @@ export const ToolbarItem = forwardRef<ITooltipWrapperRef, IToolbarItemProps>((pr
style={buttonStyle}
noIcon={!icon}
active={activated}
+ aria-pressed={props.activated$ ? activated : undefined}
disabled={disabled}
- onClick={() => {
+ onClick={(event) => {
+ // A double-click upgrades the first click's action; do not execute its toggle twice.
+ if (props.subId && event.detail > 1) {
+ return;
+ }
const commandParams = typeof params === 'function' ? params() : params;
executeCommand(props.commandId ?? props.id, commandParams ?? (typeof value === 'undefined' ? undefined : { value }));
}}
diff --git a/packages/ui/src/views/components/ribbon/__tests__/ToolbarItem.spec.tsx b/packages/ui/src/views/components/ribbon/__tests__/ToolbarItem.spec.tsx
index 41cfabeebd..ac24c0a236 100644
--- a/packages/ui/src/views/components/ribbon/__tests__/ToolbarItem.spec.tsx
+++ b/packages/ui/src/views/components/ribbon/__tests__/ToolbarItem.spec.tsx
@@ -315,6 +315,17 @@ describe('ToolbarItem', () => {
expect(getByText('Protect')).toBeTruthy();
});
+ it('executes the primary action once before a native double-click secondary action', () => {
+ const { getByRole, commandService } = renderWithDependencies(
+ <ToolbarItem id="paint-once" subId="paint-continuous" type={MenuItemType.BUTTON} title="Paint" />
+ );
+ const button = getByRole('button', { name: 'Paint' });
+ fireEvent.click(button, { detail: 1 });
+ fireEvent.click(button, { detail: 2 });
+ fireEvent.doubleClick(button, { detail: 2 });
+ expect(commandService.calls.map((call) => call.commandId)).toEqual(['paint-once', 'paint-continuous']);
+ });
+
it('resolves menu params when clicking a button', () => {
const { getByRole, commandService } = renderWithDependencies(
<ToolbarItem