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.
TypeScript boardcollaborationdocdocxexceloffce365officepdfpptpptxpresentationsdksheetslidesspreadsheetuniverwordwordprocessorworkspacexlsx
fix(sheets): preserve styles when replacing cell text (#7553)
Univere635af8a7e02
diff --git a/e2e/smoking/sheets-ime-input.spec.ts b/e2e/smoking/sheets-ime-input.spec.tsindex 21205976e1..fd453be9c1 100644--- a/e2e/smoking/sheets-ime-input.spec.ts+++ b/e2e/smoking/sheets-ime-input.spec.ts@@ -51,3 +51,68 @@ test('keeps the IME anchor on the active cell across edits', async ({ page }) =>expect(anchorPositions[1].y).toBeGreaterThan(anchorPositions[0].y);});++test('preserves cell styles after deleting all text and entering new IME text', async ({ page }) => {+ await page.goto('/sheets/');+ await page.waitForFunction(() => !!window.univerAPI && !!window.E2EControllerAPI);+ await page.evaluate(() => window.E2EControllerAPI.loadDefaultSheet());++ const canvas = page.locator(SHEET_MAIN_CANVAS);+ await expect(canvas).toBeVisible();+ const canvasBox = await canvas.boundingBox();+ if (!canvasBox) {+ throw new Error('Expected the sheet canvas to have a bounding box');+ }++ await page.mouse.click(canvasBox.x + 200, canvasBox.y + 120);+ const cell = await page.evaluate(() => {+ const range = window.univerAPI.getActiveWorkbook().getActiveRange();+ if (!range) {+ throw new Error('Expected an active sheet range');+ }++ range+ .setValue('A')+ .setHorizontalAlignment('center')+ .setVerticalAlignment('middle')+ .setFontSize(20)+ .setFontColor('#f05252');++ return range.getA1Notation();+ });++ await page.keyboard.press('F2');+ const inputContainer = page.locator(SHEET_EDITOR_INPUT_CONTAINER);+ await expect.poll(async () => (await inputContainer.boundingBox())?.x).toBeGreaterThanOrEqual(canvasBox.x);++ await page.keyboard.press('Backspace');++ const client = await page.context().newCDPSession(page);+ await client.send('Input.imeSetComposition', {+ text: 'xin',+ selectionStart: 3,+ selectionEnd: 3,+ replacementStart: 0,+ replacementEnd: 0,+ });+ await client.send('Input.insertText', { text: '新' });+ await page.keyboard.press('Enter');++ await expect.poll(() => page.evaluate((a1Notation) => {+ const range = window.univerAPI.getActiveWorkbook().getActiveSheet().getRange(a1Notation);+ const style = range.getCellStyleData('cell');+ return {+ value: range.getValue(),+ horizontalAlignment: range.getHorizontalAlignment(),+ verticalAlignment: range.getVerticalAlignment(),+ fontSize: style?.fs,+ fontColor: style?.cl?.rgb,+ };+ }, cell)).toEqual({+ value: '新',+ horizontalAlignment: 'center',+ verticalAlignment: 'middle',+ fontSize: 20,+ fontColor: '#f05252',+ });+});diff --git a/packages/core/src/sheets/__tests__/util.spec.ts b/packages/core/src/sheets/__tests__/util.spec.tsindex 02016ebe65..72289e54eb 100644--- a/packages/core/src/sheets/__tests__/util.spec.ts+++ b/packages/core/src/sheets/__tests__/util.spec.ts@@ -48,6 +48,8 @@ describe('sheet util helpers', () => {}],});expect(documentModel.getSnapshot().documentStyle).toMatchObject({+ textStyle: { ff: 'Inter', fs: 12, va: BaselineOffset.SUPERSCRIPT },+ defaultParagraphStyle: { horizontalAlign: HorizontalAlign.CENTER },marginTop: 1,marginRight: 4,marginBottom: 3,diff --git a/packages/core/src/sheets/util.ts b/packages/core/src/sheets/util.tsindex 4be897b73b..d9bc62e21b 100644--- a/packages/core/src/sheets/util.ts+++ b/packages/core/src/sheets/util.ts@@ -24,7 +24,7 @@ import { TextX } from '../docs/data-model/text-x/text-x';import { convertTextRotation } from '../docs/data-model/utils';import { createParagraphId } from '../docs/paragraph-id';import { createSectionId } from '../docs/section-break-id';-import { Rectangle } from '../shared';+import { Rectangle, Tools } from '../shared';import { HorizontalAlign, VerticalAlign, WrapStrategy } from '../types/enum';import { CustomRangeType, DocumentFlavor } from '../types/interfaces';@@ -112,6 +112,10 @@ export function createDocumentModelWithStyle(content: string, textStyle: ITextSt}],},documentStyle: {+ textStyle: Tools.deepClone(textStyle),+ defaultParagraphStyle: {+ horizontalAlign,+ },pageSize: {width: Number.POSITIVE_INFINITY,height: Number.POSITIVE_INFINITY,diff --git a/packages/docs-ui/src/commands/commands/__tests__/core-editing.command.spec.ts b/packages/docs-ui/src/commands/commands/__tests__/core-editing.command.spec.tsindex f294e192b1..187eef8331 100644--- a/packages/docs-ui/src/commands/commands/__tests__/core-editing.command.spec.ts+++ b/packages/docs-ui/src/commands/commands/__tests__/core-editing.command.spec.ts@@ -22,7 +22,10 @@ import {CustomRangeType,DataStreamTreeTokenType,DeleteDirection,+ DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY,+ DOCS_NORMAL_EDITOR_UNIT_ID_KEY,DocumentBlockRangeType,+ DocumentFlavor,HorizontalAlign,ICommandService,IUniverInstanceService,@@ -172,10 +175,11 @@ describe('core editing commands', () => {let univer: Univer;let get: Injector['get'];let commandService: ICommandService;+ let unitId = 'test-doc';function getBody() {const univerInstanceService = get(IUniverInstanceService);- return univerInstanceService.getUnit<DocumentDataModel>('test-doc', UniverInstanceType.UNIVER_DOC)?.getBody();+ return univerInstanceService.getUnit<DocumentDataModel>(unitId, UniverInstanceType.UNIVER_DOC)?.getBody();}function getDataStream() {@@ -195,15 +199,17 @@ describe('core editing commands', () => {function setActiveSelection(offset: number) {const selectionManager = get(DocSelectionManagerService);selectionManager.__TEST_ONLY_setCurrentSelection({- unitId: 'test-doc',- subUnitId: 'test-doc',+ unitId,+ subUnitId: unitId,});selectionManager.__TEST_ONLY_add([{ startOffset: offset, endOffset: offset, collapsed: true, isActive: true, segmentId: '', style: null as never }]);}function mockSkeleton() {const skeletonManager = get(DocSkeletonManagerService) as unknown as { getSkeleton: () => unknown };- skeletonManager.getSkeleton = () => ({});+ skeletonManager.getSkeleton = () => ({+ findNodeByCharIndex: () => null,+ });}function registerDeleteKeyCommands() {@@ -215,6 +221,7 @@ describe('core editing commands', () => {}beforeEach(() => {+ unitId = 'test-doc';const testBed = createCommandTestBed(getDocumentData());univer = testBed.univer;get = testBed.get;@@ -331,9 +338,11 @@ describe('core editing commands', () => {expect(getBody()?.paragraphs?.[0].paragraphStyle?.horizontalAlign).toBe(HorizontalAlign.LEFT);});- it('resets an empty centered paragraph to left alignment on a second backspace', async () => {+ it('resets an empty centered paragraph to left alignment in a traditional document', async () => {univer.dispose();- const testBed = createCommandTestBed(getCenteredEmptyParagraphDocumentData());+ const documentData = getCenteredEmptyParagraphDocumentData();+ documentData.documentStyle.documentFlavor = DocumentFlavor.TRADITIONAL;+ const testBed = createCommandTestBed(documentData);univer = testBed.univer;get = testBed.get;commandService = get(ICommandService);@@ -349,6 +358,49 @@ describe('core editing commands', () => {expect(getBody()?.paragraphs?.[0].paragraphStyle?.horizontalAlign).toBe(HorizontalAlign.LEFT);});+ it.each([+ [DOCS_NORMAL_EDITOR_UNIT_ID_KEY, DeleteLeftCommand.id],+ [DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY, DeleteRightCommand.id],+ ])('keeps center alignment in Sheet editor %s', async (editorUnitId, commandId) => {+ univer.dispose();+ const documentData = getCenteredEmptyParagraphDocumentData();+ documentData.id = editorUnitId;+ documentData.documentStyle.documentFlavor = DocumentFlavor.UNSPECIFIED;+ unitId = editorUnitId;+ const testBed = createCommandTestBed(documentData);+ univer = testBed.univer;+ get = testBed.get;+ commandService = get(ICommandService);+ registerDeleteKeyCommands();+ mockSkeleton();+ setActiveSelection(0);++ await commandService.executeCommand(commandId);+ await awaitTime(0);++ expect(getDataStream()).toBe('\r\n');+ expect(getBody()?.paragraphs?.[0].paragraphStyle?.horizontalAlign).toBe(HorizontalAlign.CENTER);+ });++ it('resets center alignment in a non-Sheet unspecified document', async () => {+ univer.dispose();+ const documentData = getCenteredEmptyParagraphDocumentData();+ documentData.documentStyle.documentFlavor = DocumentFlavor.UNSPECIFIED;+ const testBed = createCommandTestBed(documentData);+ univer = testBed.univer;+ get = testBed.get;+ commandService = get(ICommandService);+ registerDeleteKeyCommands();+ mockSkeleton();+ setActiveSelection(0);++ await commandService.executeCommand(DeleteLeftCommand.id);+ await awaitTime(0);++ expect(getDataStream()).toBe('\r\n');+ expect(getBody()?.paragraphs?.[0].paragraphStyle?.horizontalAlign).toBe(HorizontalAlign.LEFT);+ });+it('detects delete offsets inside block ranges so backspace does not clear block paragraph indent', () => {const dataStream = `${DataStreamTreeTokenType.BLOCK_START}A${DataStreamTreeTokenType.PARAGRAPH}${DataStreamTreeTokenType.BLOCK_END}\n`;const body = {diff --git a/packages/docs-ui/src/commands/commands/__tests__/create-command-test-bed.ts b/packages/docs-ui/src/commands/commands/__tests__/create-command-test-bed.tsindex 0f5c0b9706..8f360c1f79 100644--- a/packages/docs-ui/src/commands/commands/__tests__/create-command-test-bed.ts+++ b/packages/docs-ui/src/commands/commands/__tests__/create-command-test-bed.ts@@ -146,7 +146,7 @@ export function createCommandTestBed(docData?: IDocumentData, dependencies?: Dep// Refer to packages/sheets-ui/src/services/clipboard/__tests__/clipboard-test-bed.tsconst fakeDocSkeletonManager = new MockDocSkeletonManagerService({unit: doc,- unitId: 'test-doc',+ unitId: doc.getUnitId(),type: UniverInstanceType.UNIVER_DOC,engine: null as any,scene: null as any,@@ -177,7 +177,7 @@ export function createCommandTestBed(docData?: IDocumentData, dependencies?: Dep});}- univerInstanceService.focusUnit('test-doc');+ univerInstanceService.focusUnit(doc.getUnitId());const logService = get(ILogService);logService.setLogLevel(LogLevel.SILENT);diff --git a/packages/docs-ui/src/commands/commands/doc-delete.command.ts b/packages/docs-ui/src/commands/commands/doc-delete.command.tsindex 657e95bc0a..b44002239a 100644--- a/packages/docs-ui/src/commands/commands/doc-delete.command.ts+++ b/packages/docs-ui/src/commands/commands/doc-delete.command.ts@@ -31,6 +31,7 @@ import {JSONX,PositionedObjectLayoutType,sequenceExecuteAsync,+ SHEET_EDITOR_UNITS,TextX,TextXActionType,Tools,@@ -478,7 +479,7 @@ export const DeleteLeftCommand: ICommand = {const actualRange = activeRange;const { startOffset, collapsed } = actualRange;- if (collapsed) {+ if (collapsed && shouldResetEmptyCenteredParagraphAlignment(docDataModel)) {const emptyCenteredParagraph = getEmptyCenteredParagraphAtOffset(body, startOffset);if (emptyCenteredParagraph != null) {return resetEmptyCenteredParagraphAlignment(commandService, docDataModel, segmentId ?? '', emptyCenteredParagraph, style);@@ -701,7 +702,7 @@ export const DeleteRightCommand: ICommand = {const actualRange = activeRange;const { startOffset, endOffset, collapsed } = actualRange;- if (collapsed) {+ if (collapsed && shouldResetEmptyCenteredParagraphAlignment(docDataModel)) {const emptyCenteredParagraph = getEmptyCenteredParagraphAtOffset(body, startOffset);if (emptyCenteredParagraph != null) {return resetEmptyCenteredParagraphAlignment(commandService, docDataModel, segmentId ?? '', emptyCenteredParagraph, style);@@ -843,6 +844,10 @@ function getEmptyCenteredParagraphAtOffset(body: IDocumentBody, offset: number)}}+function shouldResetEmptyCenteredParagraphAlignment(docDataModel: DocumentDataModel) {+ return !SHEET_EDITOR_UNITS.includes(docDataModel.getUnitId());+}+function resetEmptyCenteredParagraphAlignment(commandService: ICommandService,docDataModel: DocumentDataModel,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.tsindex fede0a75ac..8b0b96ea21 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@@ -14,6 +14,7 @@* limitations under the License.*/+import type { ITextStyle } from '@univerjs/core';import {CommandService,ConfigService,@@ -84,7 +85,7 @@ function createService(defaultTextColor?: string): DocMenuStyleService {return injector.get(DocMenuStyleService);}-function createStyleTestBed() {+function createStyleTestBed(textStyle?: ITextStyle) {const injector = new Injector();injector.add([ILogService, { useClass: DesktopLogService }]);injector.add([IConfigService, { useClass: ConfigService }]);@@ -107,6 +108,9 @@ function createStyleTestBed() {tables: [],textRuns: [],},+ documentStyle: {+ textStyle,+ },}));univerInstanceService.setCurrentUnitForType('doc-menu-style');@@ -156,6 +160,23 @@ describe('DocMenuStyleService', () => {expect(service.getDefaultStyle()).toEqual({ ff: 'Arial', fs: 9, cl: { rgb: '#1B1C1F' } });});+ it('uses active document text defaults for the next body input', () => {+ const { service, renderManagerService } = createStyleTestBed({ fs: 20, cl: { rgb: '#f05252' } });++ renderManagerService.editArea = DocumentEditArea.BODY;++ expect(service.getDefaultStyle()).toEqual({ ff: 'Arial', fs: 20, cl: { rgb: '#f05252' } });++ renderManagerService.editArea = DocumentEditArea.FOOTER;+ expect(service.getDefaultStyle()).toEqual({ ff: 'Arial', fs: 9, cl: { rgb: '#f05252' } });+ });++ it('uses active document text defaults before its render is available', () => {+ const { service } = createStyleTestBed({ fs: 20, cl: { rgb: '#f05252' } });++ expect(service.getDefaultStyle()).toEqual({ ff: 'Arial', fs: 20, cl: { rgb: '#f05252' } });+ });+it('clears cached input style when document selection changes', () => {const { service, selectionManager, commandService } = createStyleTestBed();commandService.registerCommand(SetTextSelectionsOperation);diff --git a/packages/docs-ui/src/services/doc-menu-style.service.ts b/packages/docs-ui/src/services/doc-menu-style.service.tsindex 4ab0733bde..84653c581e 100644--- a/packages/docs-ui/src/services/doc-menu-style.service.ts+++ b/packages/docs-ui/src/services/doc-menu-style.service.ts@@ -78,13 +78,18 @@ export class DocMenuStyleService extends Disposable {};}+ const documentDefaultTextStyle = {+ ...defaultTextStyle,+ ...docDataModel.getDocumentStyle().textStyle,+ };+const unitId = docDataModel?.getUnitId();const docSkeletonManagerService = this._renderManagerService.getRenderUnitById(unitId)?.with(DocSkeletonManagerService);const docViewModel = docSkeletonManagerService?.getViewModel();if (docViewModel == null) {return {- ...defaultTextStyle,+ ...documentDefaultTextStyle,};}@@ -92,11 +97,11 @@ export class DocMenuStyleService extends Disposable {if (editArea === DocumentEditArea.BODY) {return {- ...defaultTextStyle,+ ...documentDefaultTextStyle,};} else {return {- ...defaultTextStyle,+ ...documentDefaultTextStyle,fs: HEADER_FOOTER_DEFAULT_FONTSIZE,};}