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.

fix(sheets): keep wrap and shrink-to-fit styles mutually exclusive (#7786)

白熱a4e079128381
diff --git a/packages/sheets-ui/src/menu/menu.ts b/packages/sheets-ui/src/menu/menu.ts
index 303dc52f50..a42d4c41f1 100644
--- a/packages/sheets-ui/src/menu/menu.ts
+++ b/packages/sheets-ui/src/menu/menu.ts
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-import type { IAccessor, IColorStyle, Nullable, Workbook } from '@univerjs/core';
+import type { IAccessor, IColorStyle, IStyleData, Nullable, Workbook } from '@univerjs/core';
import type { IMenuButtonItem, IMenuSelectorItem } from '@univerjs/ui';
import type { LocaleKey } from '../locale/types';
import {
@@ -83,6 +83,7 @@ import {
MenuItemType,
} from '@univerjs/ui';
import { combineLatest, combineLatestWith, map, Observable, startWith } from 'rxjs';
+
import {
SheetCopyCommand,
SheetCutCommand,
@@ -109,7 +110,7 @@ import {
import { SetWorksheetColAutoWidthCommand } from '../commands/commands/set-worksheet-auto-col-width.command';
import { ISheetClipboardService } from '../services/clipboard/clipboard.service';
import { FormatPainterStatus, IFormatPainterService } from '../services/format-painter/format-painter.service';
-import { MENU_ITEM_INPUT_COMPONENT } from '../views/menu-item-input/index';
+import { MENU_ITEM_INPUT_COMPONENT } from '../views/menu-item-input/interface';
import { deriveStateFromActiveSheet$, getCurrentRangeDisable$, getObservableWithExclusiveRange$ } from './menu-util';
import { getFontStyleAtCursor } from './utils';
@@ -798,7 +799,7 @@ export function WrapTextMenuItemFactory(accessor: IAccessor): IMenuSelectorItem<
value$: deriveStateFromActiveSheet$<WrapStrategy>(univerInstanceService, defaultValue, ({ worksheet }) => new Observable((subscriber) => {
const disposable = accessor.get(ICommandService).onCommandExecuted((c) => {
const id = c.id;
- if (id !== SetTextWrapCommand.id && id !== SetSelectionsOperation.id && id !== SetWorksheetActiveOperation.id) {
+ if (id !== SetRangeValuesMutation.id && id !== SetSelectionsOperation.id && id !== SetWorksheetActiveOperation.id) {
return;
}
@@ -841,6 +842,20 @@ export function ShrinkToFitMenuItemFactory(accessor: IAccessor): IMenuButtonItem
const commandService = accessor.get(ICommandService);
const univerInstanceService = accessor.get(IUniverInstanceService);
const selectionManagerService = accessor.get(SheetsSelectionsService);
+ const style$ = deriveStateFromActiveSheet$<IStyleData>(univerInstanceService, {}, ({ worksheet }) => new Observable((subscriber) => {
+ const update = () => {
+ const primary = selectionManagerService.getCurrentLastSelection()?.primary;
+ subscriber.next(primary != null ? worksheet.getComposedCellStyle(primary.startRow, primary.startColumn) ?? {} : {});
+ };
+ const disposable = commandService.onCommandExecuted((command) => {
+ if ([SetRangeValuesMutation.id, SetSelectionsOperation.id, SetWorksheetActiveOperation.id].includes(command.id)) {
+ update();
+ }
+ });
+
+ update();
+ return disposable.dispose;
+ }));
return {
id: SetShrinkToFitCommand.id,
@@ -848,25 +863,15 @@ export function ShrinkToFitMenuItemFactory(accessor: IAccessor): IMenuButtonItem
icon: 'ShrinkToFitIcon',
title: 'sheets-ui.toolbar.shrinkToFit',
tooltip: 'sheets-ui.toolbar.shrinkToFit',
- activated$: deriveStateFromActiveSheet$(univerInstanceService, false, ({ worksheet }) => new Observable<boolean>((subscriber) => {
- const update = () => {
- const primary = selectionManagerService.getCurrentLastSelection()?.primary;
- subscriber.next(primary != null && worksheet.getComposedCellStyle(primary.startRow, primary.startColumn)?.stf === BooleanNumber.TRUE);
- };
- const disposable = commandService.onCommandExecuted((command) => {
- if ([SetRangeValuesMutation.id, SetSelectionsOperation.id, SetWorksheetActiveOperation.id].includes(command.id)) {
- update();
- }
- });
-
- update();
- return disposable.dispose;
- })),
- disabled$: getCurrentRangeDisable$(accessor, {
- workbookTypes: [WorkbookEditablePermission],
- worksheetTypes: [WorksheetEditPermission, WorksheetSetCellStylePermission],
- rangeTypes: [RangeProtectionPermissionEditPoint],
- }),
+ activated$: style$.pipe(map((style) => style.stf === BooleanNumber.TRUE && style.tb !== WrapStrategy.WRAP)),
+ disabled$: combineLatest([
+ getCurrentRangeDisable$(accessor, {
+ workbookTypes: [WorkbookEditablePermission],
+ worksheetTypes: [WorksheetEditPermission, WorksheetSetCellStylePermission],
+ rangeTypes: [RangeProtectionPermissionEditPoint],
+ }),
+ style$,
+ ]).pipe(map(([disabled, style]) => disabled || style.tb === WrapStrategy.WRAP)),
hidden$: getMenuHiddenObservable(accessor, UniverInstanceType.UNIVER_SHEET),
};
}
diff --git a/packages/sheets/src/commands/commands/__tests__/set-style.command.spec.ts b/packages/sheets/src/commands/commands/__tests__/set-style.command.spec.ts
index 49bc0fa89e..f7de61baf5 100644
--- a/packages/sheets/src/commands/commands/__tests__/set-style.command.spec.ts
+++ b/packages/sheets/src/commands/commands/__tests__/set-style.command.spec.ts
@@ -31,6 +31,7 @@ import {
WrapStrategy,
} from '@univerjs/core';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
import { SheetsSelectionsService } from '../../../services/selections/selection.service';
import { InsertSheetMutation } from '../../mutations/insert-sheet.mutation';
import { SetRangeValuesMutation } from '../../mutations/set-range-values.mutation';
@@ -691,6 +692,70 @@ describe("Test commands used for updating cells' styles", () => {
});
describe('shrink to fit', () => {
+ it.each([
+ [SetTextWrapCommand.id, WrapStrategy.WRAP, { tb: WrapStrategy.UNSPECIFIED, stf: BooleanNumber.TRUE }, { tb: WrapStrategy.WRAP, stf: BooleanNumber.FALSE }],
+ [SetShrinkToFitCommand.id, BooleanNumber.TRUE, { tb: WrapStrategy.WRAP, stf: BooleanNumber.FALSE }, { tb: WrapStrategy.UNSPECIFIED, stf: BooleanNumber.TRUE }],
+ ])('keeps wrapping and shrink to fit mutually exclusive through %s, undo and redo', async (commandId, value, before, after) => {
+ const range = { startRow: 0, startColumn: 0, endRow: 0, endColumn: 1 };
+ const worksheet = get(IUniverInstanceService).getUnit<Workbook>('test')!.getSheetBySheetId('sheet1')!;
+ commandService.syncExecuteCommand(SetRangeValuesMutation.id, {
+ unitId: 'test',
+ subUnitId: 'sheet1',
+ cellValue: { 0: { 0: { s: before }, 1: { s: before } } },
+ });
+
+ await commandService.executeCommand(commandId, { range, value });
+ expect([0, 1].map((column) => worksheet.getComposedCellStyle(0, column))).toEqual([after, after]);
+
+ await commandService.executeCommand(UndoCommand.id);
+ expect([0, 1].map((column) => worksheet.getComposedCellStyle(0, column))).toEqual([before, before]);
+
+ await commandService.executeCommand(RedoCommand.id);
+ expect([0, 1].map((column) => worksheet.getComposedCellStyle(0, column))).toEqual([after, after]);
+ });
+
+ it('keeps per-cell wrap and shrink settings mutually exclusive when applying style matrices', () => {
+ const range = { startRow: 0, startColumn: 0, endRow: 0, endColumn: 1 };
+ const worksheet = get(IUniverInstanceService).getUnit<Workbook>('test')!.getSheetBySheetId('sheet1')!;
+ commandService.syncExecuteCommand(SetTextWrapCommand.id, { range, value: WrapStrategy.WRAP });
+ commandService.syncExecuteCommand(SetStyleCommand.id, {
+ range,
+ style: { type: 'stf', value: [[BooleanNumber.TRUE, BooleanNumber.FALSE]] },
+ });
+ expect(worksheet.getComposedCellStyle(0, 0)).toEqual({ tb: WrapStrategy.UNSPECIFIED, stf: BooleanNumber.TRUE });
+ expect(worksheet.getComposedCellStyle(0, 1)).toEqual({ tb: WrapStrategy.WRAP, stf: BooleanNumber.FALSE });
+
+ commandService.syncExecuteCommand(SetStyleCommand.id, {
+ range,
+ style: { type: 'tb', value: [[WrapStrategy.WRAP, WrapStrategy.CLIP]] },
+ });
+ expect(worksheet.getComposedCellStyle(0, 0)).toEqual({ tb: WrapStrategy.WRAP, stf: BooleanNumber.FALSE });
+ expect(worksheet.getComposedCellStyle(0, 1)).toEqual({ tb: WrapStrategy.CLIP, stf: BooleanNumber.FALSE });
+ });
+
+ it('preserves clipping and overflow when toggling shrink to fit across mixed cells', () => {
+ const range = { startRow: 0, startColumn: 0, endRow: 0, endColumn: 2 };
+ const worksheet = get(IUniverInstanceService).getUnit<Workbook>('test')!.getSheetBySheetId('sheet1')!;
+ commandService.syncExecuteCommand(SetStyleCommand.id, {
+ range,
+ style: { type: 'tb', value: [[WrapStrategy.OVERFLOW, WrapStrategy.CLIP, WrapStrategy.WRAP]] },
+ });
+
+ commandService.syncExecuteCommand(SetShrinkToFitCommand.id, { range, value: BooleanNumber.TRUE });
+ expect([0, 1, 2].map((column) => worksheet.getComposedCellStyle(0, column))).toEqual([
+ { tb: WrapStrategy.OVERFLOW, stf: BooleanNumber.TRUE },
+ { tb: WrapStrategy.CLIP, stf: BooleanNumber.TRUE },
+ { tb: WrapStrategy.UNSPECIFIED, stf: BooleanNumber.TRUE },
+ ]);
+
+ commandService.syncExecuteCommand(SetShrinkToFitCommand.id, { range, value: BooleanNumber.FALSE });
+ expect([0, 1, 2].map((column) => worksheet.getComposedCellStyle(0, column))).toEqual([
+ { tb: WrapStrategy.OVERFLOW, stf: BooleanNumber.FALSE },
+ { tb: WrapStrategy.CLIP, stf: BooleanNumber.FALSE },
+ { tb: WrapStrategy.UNSPECIFIED, stf: BooleanNumber.FALSE },
+ ]);
+ });
+
it('changes shrink to fit with undo and redo', async () => {
const selectionManager = get(SheetsSelectionsService);
selectionManager.addSelections([
diff --git a/packages/sheets/src/commands/commands/set-style.command.ts b/packages/sheets/src/commands/commands/set-style.command.ts
index 754edfe27a..49ad4699da 100644
--- a/packages/sheets/src/commands/commands/set-style.command.ts
+++ b/packages/sheets/src/commands/commands/set-style.command.ts
@@ -25,7 +25,7 @@ import type {
IStyleData,
ITextRotation,
VerticalAlign,
- WrapStrategy,
+ Worksheet,
} from '@univerjs/core';
import type { ISetRangeValuesMutationParams } from '../mutations/set-range-values.mutation';
import type { ISheetCommandSharedParams } from '../utils/interface';
@@ -40,7 +40,9 @@ import {
ObjectMatrix,
sequenceExecute,
Tools,
+ WrapStrategy,
} from '@univerjs/core';
+
import { SheetsSelectionsService } from '../../services/selections/selection.service';
import { SheetInterceptorService } from '../../services/sheet-interceptor/sheet-interceptor.service';
import { SheetSkeletonService } from '../../skeleton/skeleton.service';
@@ -64,6 +66,41 @@ export interface ISetStyleCommandParams<T> extends ISetStyleCommonParams {
export const AFFECT_LAYOUT_STYLES = ['ff', 'fs', 'stf', 'tr', 'tb'];
+function createStyleCellValue<T>(worksheet: Worksheet, ranges: IRange[], style: IStyleTypeValue<T>): ObjectMatrix<ICellData> {
+ const cellValue = new ObjectMatrix<ICellData>();
+ const iterator = createRangeIteratorWithSkipFilteredRows(worksheet);
+
+ if (Tools.isArray(style.value)) {
+ for (let i = 0; i < ranges.length; i++) {
+ iterator.forOperableEach(ranges[i], (r, c, range) => {
+ cellValue.setValue(r, c, {
+ s: {
+ [style.type]: (style.value as T[][])[r - range.startRow][c - range.startColumn],
+ },
+ });
+ });
+ }
+ } else {
+ const styleObj: ICellData = { s: { [style.type]: style.value } };
+ for (let i = 0; i < ranges.length; i++) {
+ iterator.forOperableEach(ranges[i], (r, c) => cellValue.setValue(r, c, styleObj));
+ }
+ }
+
+ if (style.type === 'tb' || style.type === 'stf') {
+ cellValue.forValue((row, column, cell) => {
+ const cellStyle = cell.s as IStyleData;
+ if (cellStyle.tb === WrapStrategy.WRAP) {
+ cellStyle.stf = BooleanNumber.FALSE;
+ } else if (cellStyle.stf === BooleanNumber.TRUE && worksheet.getComposedCellStyle(row, column)?.tb === WrapStrategy.WRAP) {
+ cellValue.setValue(row, column, { s: { ...cellStyle, tb: WrapStrategy.UNSPECIFIED } });
+ }
+ });
+ }
+
+ return cellValue;
+}
+
/**
* The command to set cell style.
* Set style to a bunch of ranges.
@@ -72,7 +109,6 @@ export const SetStyleCommand: ICommand<ISetStyleCommandParams<unknown>> = {
type: CommandType.COMMAND,
id: 'sheet.command.set-style',
- // eslint-disable-next-line max-lines-per-function
handler: <T>(accessor: IAccessor, params: ISetStyleCommandParams<T>) => {
const univerInstanceService = accessor.get(IUniverInstanceService);
@@ -86,39 +122,12 @@ export const SetStyleCommand: ICommand<ISetStyleCommandParams<unknown>> = {
const selectionManagerService = accessor.get(SheetsSelectionsService);
const ranges = range ? [range] : selectionManagerService.getCurrentSelections()?.map((s) => s.range);
- if (!ranges?.length) {
- return false;
- }
-
- const cellValue = new ObjectMatrix<ICellData>();
-
- const iterator = createRangeIteratorWithSkipFilteredRows(worksheet);
-
- if (Tools.isArray(style.value)) {
- for (let i = 0; i < ranges.length; i++) {
- iterator.forOperableEach(ranges[i], (r, c, range) => {
- cellValue.setValue(r, c, {
- s: {
- [style.type]: (style.value as T[][])[r - range.startRow][c - range.startColumn],
- },
- });
- });
- }
- } else {
- for (let i = 0; i < ranges.length; i++) {
- const styleObj: ICellData = {
- s: {
- [style.type]: style.value,
- },
- };
- iterator.forOperableEach(ranges[i], (r, c) => cellValue.setValue(r, c, styleObj));
- }
- }
+ if (!ranges?.length) return false;
const setRangeValuesMutationParams: ISetRangeValuesMutationParams = {
subUnitId,
unitId,
- cellValue: cellValue.getMatrix(),
+ cellValue: createStyleCellValue(worksheet, ranges, style).getMatrix(),
};
const skeleton = accessor.get(SheetSkeletonService).getSkeleton(unitId, subUnitId);