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): improve editing, formatting and table interactions (#7874)

wpxp123456e5ee00cb605f
diff --git a/packages/core/src/sheets/sheet-skeleton.ts b/packages/core/src/sheets/sheet-skeleton.ts
index c3522e0ef0..d7f58fc134 100644
--- a/packages/core/src/sheets/sheet-skeleton.ts
+++ b/packages/core/src/sheets/sheet-skeleton.ts
@@ -34,6 +34,7 @@ import type {
IWorksheetData,
} from './typedef';
import type { Worksheet } from './worksheet';
+import { Subject } from 'rxjs';
import { AUTO_HEIGHT_FOR_MERGED_CELLS, IS_ROW_STYLE_PRECEDE_COLUMN_STYLE } from '../common/const';
import { Inject, Injector } from '../common/di';
import { DocumentDataModel } from '../docs/data-model/document-data-model';
@@ -286,6 +287,9 @@ export class SheetSkeleton extends Skeleton {
// #region Gap Config
+ private readonly _gapConfigChanged$ = new Subject<void>();
+ readonly gapConfigChanged$ = this._gapConfigChanged$.asObservable();
+
get gapConfig(): ISheetGapConfig {
return this._gapConfig;
}
@@ -298,6 +302,7 @@ export class SheetSkeleton extends Skeleton {
this._gapConfig = this._fillDefaultGapThemeColors(config);
this.makeDirty(true);
this._updateLayout();
+ this._gapConfigChanged$.next();
}
private _fillDefaultGapThemeColors(config: ISheetGapConfig): ISheetGapConfig {
@@ -1191,6 +1196,7 @@ export class SheetSkeleton extends Skeleton {
override dispose(): void {
super.dispose();
+ this._gapConfigChanged$.complete();
this._rowHeightAccumulation = [];
this._columnWidthAccumulation = [];
diff --git a/packages/sheets-data-validation-ui/src/controllers/__tests__/dv-alert.controller.spec.ts b/packages/sheets-data-validation-ui/src/controllers/__tests__/dv-alert.controller.spec.ts
index b16a995cb6..6c07af0c6f 100644
--- a/packages/sheets-data-validation-ui/src/controllers/__tests__/dv-alert.controller.spec.ts
+++ b/packages/sheets-data-validation-ui/src/controllers/__tests__/dv-alert.controller.spec.ts
@@ -14,6 +14,7 @@
* limitations under the License.
*/
+import type { Nullable } from '@univerjs/core';
import type { IHoverCellPosition } from '@univerjs/sheets-ui';
import type { Subject } from 'rxjs';
import {
@@ -22,10 +23,19 @@ import {
DataValidationType,
IUniverInstanceService,
LocaleService,
+ LocaleType,
+ RedoCommand,
+ UndoCommand,
} from '@univerjs/core';
import { IRenderManagerService, RenderManagerService } from '@univerjs/engine-render';
import { IRefSelectionsService, RefSelectionsService, SetRangeValuesMutation } from '@univerjs/sheets';
-import { AddSheetDataValidationCommand } from '@univerjs/sheets-data-validation';
+import {
+ AddSheetDataValidationCommand,
+ RemoveSheetDataValidationCommand,
+ UpdateSheetDataValidationOptionsCommand,
+ UpdateSheetDataValidationRangeCommand,
+} from '@univerjs/sheets-data-validation';
+import sheetsDataValidationEnUS from '@univerjs/sheets-data-validation/locale/en-US';
import {
CellAlertManagerService,
CellPopupManagerService,
@@ -33,7 +43,7 @@ import {
SheetCanvasPopManagerService,
} from '@univerjs/sheets-ui';
import { CanvasPopupService, ICanvasPopupService } from '@univerjs/ui';
-import { afterEach, describe, expect, it, vi } from 'vitest';
+import { afterEach, describe, expect, it, onTestFinished, vi } from 'vitest';
import { createDvUiTestBed } from '../../__tests__/create-dv-ui-test-bed';
import enUS from '../../locale/en-US';
import { DataValidationAlertController } from '../dv-alert.controller';
@@ -42,7 +52,164 @@ afterEach(() => {
vi.useRealTimers();
});
+function createAlertTestBed() {
+ vi.useFakeTimers();
+ const testBed = createDvUiTestBed();
+ const { injector } = testBed;
+ onTestFinished(() => {
+ testBed.univer.dispose();
+ vi.clearAllTimers();
+ });
+ injector.add([IRenderManagerService, { useClass: RenderManagerService }]);
+ injector.add([ICanvasPopupService, { useClass: CanvasPopupService }]);
+ injector.add([IRefSelectionsService, { useClass: RefSelectionsService }]);
+ injector.add([SheetCanvasPopManagerService]);
+ injector.add([CellPopupManagerService]);
+ injector.add([CellAlertManagerService]);
+ injector.add([HoverManagerService]);
+ injector.add([DataValidationAlertController]);
+ injector.get(LocaleService).load({ [LocaleType.EN_US]: { ...sheetsDataValidationEnUS, ...enUS } });
+ injector.get(LocaleService).setLocale(LocaleType.EN_US);
+ const input = injector.get(HoverManagerService) as unknown as { _currentCell$: Subject<Nullable<IHoverCellPosition>> };
+ const hoverCell = (row: number | null, col = 0) => {
+ input._currentCell$.next(row === null
+ ? null
+ : {
+ location: { unitId: 'test', subUnitId: 'sheet1', row, col },
+ position: { startX: col * 100, endX: (col + 1) * 100, startY: row * 28, endY: (row + 1) * 28 },
+ });
+ };
+ const rule = {
+ uid: 'date-alert-rule',
+ type: DataValidationType.DATE,
+ ranges: [{ startRow: 0, endRow: 0, startColumn: 0, endColumn: 0 }],
+ showErrorMessage: true,
+ error: 'Expected a date',
+ };
+ const setValue = (value: number | string, row = 0) => testBed.commandService.syncExecuteCommand(SetRangeValuesMutation.id, {
+ unitId: 'test',
+ subUnitId: 'sheet1',
+ cellValue: { [row]: { 0: { v: value } } },
+ });
+ const addRule = () => testBed.commandService.syncExecuteCommand(AddSheetDataValidationCommand.id, {
+ unitId: 'test',
+ subUnitId: 'sheet1',
+ rule,
+ });
+ return { ...testBed, hoverCell, setValue, addRule, rule, alerts: injector.get(CellAlertManagerService) };
+}
+
describe('DataValidationAlertController', () => {
+ it('closes on undo and reopens on redo without moving the pointer', async () => {
+ const { injector, commandService, alerts, setValue, addRule, hoverCell } = createAlertTestBed();
+ injector.get(DataValidationAlertController);
+ setValue(1);
+ addRule();
+ hoverCell(0);
+ await vi.advanceTimersByTimeAsync(120);
+ expect(alerts.currentAlert.size).toBe(1);
+
+ expect(await commandService.executeCommand(UndoCommand.id)).toBe(true);
+ expect(alerts.currentAlert.size).toBe(0);
+ await vi.advanceTimersByTimeAsync(120);
+ expect(alerts.currentAlert.size).toBe(0);
+
+ expect(await commandService.executeCommand(RedoCommand.id)).toBe(true);
+ await vi.advanceTimersByTimeAsync(0);
+ expect(alerts.currentAlert.size).toBe(1);
+ });
+
+ it.each(['remove', 'range'] as const)('closes when the hovered rule changes through %s', async (action) => {
+ const { injector, commandService, alerts, setValue, addRule, hoverCell, rule } = createAlertTestBed();
+ injector.get(DataValidationAlertController);
+ setValue(1);
+ addRule();
+ hoverCell(0);
+ await vi.advanceTimersByTimeAsync(120);
+ expect(alerts.currentAlert.size).toBe(1);
+
+ await commandService.executeCommand(
+ action === 'remove' ? RemoveSheetDataValidationCommand.id : UpdateSheetDataValidationRangeCommand.id,
+ { unitId: 'test', subUnitId: 'sheet1', ruleId: rule.uid, ranges: [{ startRow: 1, endRow: 1, startColumn: 0, endColumn: 0 }] }
+ );
+ expect(alerts.currentAlert.size).toBe(0);
+ await vi.advanceTimersByTimeAsync(120);
+ expect(alerts.currentAlert.size).toBe(0);
+ });
+
+ it('refreshes changed error text and ignores unrelated rules', async () => {
+ const { injector, commandService, alerts, setValue, addRule, hoverCell, rule } = createAlertTestBed();
+ injector.get(DataValidationAlertController);
+ setValue(1);
+ addRule();
+ hoverCell(0);
+ await vi.advanceTimersByTimeAsync(120);
+ expect([...alerts.currentAlert.values()][0].alert.message).toBe('Expected a date');
+
+ await commandService.executeCommand(UpdateSheetDataValidationOptionsCommand.id, {
+ unitId: 'test',
+ subUnitId: 'sheet1',
+ ruleId: rule.uid,
+ options: { showErrorMessage: true, error: 'Updated date error' },
+ });
+ await vi.advanceTimersByTimeAsync(0);
+ expect([...alerts.currentAlert.values()][0].alert.message).toBe('Updated date error');
+ const currentAlert = [...alerts.currentAlert.values()][0];
+ await commandService.executeCommand(AddSheetDataValidationCommand.id, {
+ unitId: 'test',
+ subUnitId: 'sheet1',
+ rule: { ...rule, uid: 'unrelated-rule', ranges: [{ startRow: 1, endRow: 1, startColumn: 0, endColumn: 0 }] },
+ });
+ await vi.advanceTimersByTimeAsync(0);
+ expect([...alerts.currentAlert.values()][0]).toBe(currentAlert);
+ });
+
+ it('closes when a hovered value becomes valid and opens when it becomes invalid again', async () => {
+ const { injector, alerts, setValue, addRule, hoverCell } = createAlertTestBed();
+ injector.get(DataValidationAlertController);
+ setValue(1);
+ addRule();
+ hoverCell(0);
+ await vi.advanceTimersByTimeAsync(120);
+ expect(alerts.currentAlert.size).toBe(1);
+
+ setValue('2026-10-15');
+ await vi.advanceTimersByTimeAsync(0);
+ expect(alerts.currentAlert.size).toBe(0);
+ setValue(1);
+ await vi.advanceTimersByTimeAsync(0);
+ expect(alerts.currentAlert.size).toBe(1);
+ });
+
+ it.each(['undo', 'leave', 'dispose'] as const)('ignores a pending validation result after %s', async (action) => {
+ const { injector, commandService, alerts, setValue, addRule, hoverCell, dataValidationModel, workbook, rule } = createAlertTestBed();
+ const controller = injector.get(DataValidationAlertController);
+ setValue(1);
+ addRule();
+ hoverCell(0);
+ await vi.advanceTimersByTimeAsync(120);
+ expect(alerts.currentAlert.size).toBe(1);
+
+ setValue(2);
+ expect(dataValidationModel.validator(rule, {
+ unitId: 'test',
+ subUnitId: 'sheet1',
+ row: 0,
+ col: 0,
+ workbook,
+ worksheet: workbook.getActiveSheet(),
+ })).toBe(DataValidationStatus.VALIDATING);
+ if (action === 'undo') {
+ expect(commandService.syncExecuteCommand(UndoCommand.id)).toBe(true);
+ } else if (action === 'leave') {
+ hoverCell(null);
+ } else {
+ controller.dispose();
+ }
+ await vi.advanceTimersByTimeAsync(120);
+ expect(alerts.currentAlert.size).toBe(0);
+ });
+
it.each(['active', 'inactive', 'disposed', 'switched-after-open'] as const)('handles delayed validation hover for a %s worksheet', async (state) => {
vi.useFakeTimers();
const { univer, injector, workbook, commandService, dataValidationModel } = createDvUiTestBed();
diff --git a/packages/sheets-data-validation-ui/src/controllers/__tests__/dv-render.controller.spec.ts b/packages/sheets-data-validation-ui/src/controllers/__tests__/dv-render.controller.spec.ts
index 0d3f3d1b74..2bf65117bf 100644
--- a/packages/sheets-data-validation-ui/src/controllers/__tests__/dv-render.controller.spec.ts
+++ b/packages/sheets-data-validation-ui/src/controllers/__tests__/dv-render.controller.spec.ts
@@ -36,9 +36,12 @@ import { DocSelectionManagerService } from '@univerjs/docs';
import { EditorService, IEditorService } from '@univerjs/docs-ui';
import {
CanvasColorService,
+ DeviceInputEventType,
ICanvasColorService,
IRenderManagerService,
RenderManagerService,
+ SHEET_VIEWPORT_KEY,
+ Viewport,
} from '@univerjs/engine-render';
import {
INTERCEPTOR_POINT,
@@ -54,6 +57,7 @@ import {
EditorBridgeService,
IEditorBridgeService,
ISheetCellDropdownManagerService,
+ SetCellEditVisibleOperation,
SheetCanvasPopManagerService,
SheetCellDropdownManagerService,
SheetSkeletonManagerService,
@@ -120,6 +124,7 @@ for (const Controller of controllers) {
injector.add([IMenuManagerService, { useClass: MenuManagerService }]);
injector.add([Controller]);
injector.add([SheetsDataValidationUIController]);
+ injector.get(ICommandService).registerCommand(SetCellEditVisibleOperation);
const instances = injector.get(IUniverInstanceService);
first = instances.createUnit<IWorkbookData, Workbook>(
UniverInstanceType.UNIVER_SHEET,
@@ -147,6 +152,118 @@ for (const Controller of controllers) {
vi.useRealTimers();
});
+ if (Controller === SheetsDataValidationRenderController) {
+ it.each([
+ DataValidationType.LIST,
+ DataValidationType.LIST_MULTIPLE,
+ DataValidationType.CHECKBOX,
+ ])('keeps %s cells out of text editing on double-click', (type) => {
+ addRule(univer, 'first', 'sheet1', 1, type);
+ selectEditorCell(univer, first, 1);
+ const injector = univer.__getInjector();
+ const bridge = injector.get(IEditorBridgeService);
+ const visibility: boolean[] = [];
+ const subscription = bridge.visible$.subscribe((state) => visibility.push(state.visible));
+
+ expect(injector.get(ICommandService).syncExecuteCommand(SetCellEditVisibleOperation.id, {
+ visible: true,
+ eventType: DeviceInputEventType.Dblclick,
+ unitId: 'first',
+ pointerPosition: { x: 100, y: 100 },
+ })).toBe(false);
+ expect(bridge.isVisible().visible).toBe(false);
+ expect(visibility).toEqual([false]);
+ subscription.unsubscribe();
+ });
+
+ it.each([undefined, DataValidationType.WHOLE, DataValidationType.DECIMAL])(
+ 'preserves double-click editing for cells with rule type %s',
+ (type) => {
+ if (type) {
+ addRule(univer, 'first', 'sheet1', 1, type);
+ }
+ selectEditorCell(univer, first, 1);
+ const injector = univer.__getInjector();
+
+ expect(injector.get(ICommandService).syncExecuteCommand(SetCellEditVisibleOperation.id, {
+ visible: true,
+ eventType: DeviceInputEventType.Dblclick,
+ unitId: 'first',
+ pointerPosition: { x: 100, y: 100 },
+ })).toBe(true);
+ expect(injector.get(IEditorBridgeService).isVisible().visible).toBe(true);
+ }
+ );
+
+ it.each([
+ DeviceInputEventType.Keyboard,
+ DeviceInputEventType.PointerDown,
+ DeviceInputEventType.Dblclick,
+ ])(
+ 'preserves other editing entrances and editor closing (%s)',
+ (eventType) => {
+ addRule(univer, 'first', 'sheet1', 1, DataValidationType.CHECKBOX);
+ selectEditorCell(univer, first, 1);
+ const injector = univer.__getInjector();
+ const commands = injector.get(ICommandService);
+ expect(commands.syncExecuteCommand(SetCellEditVisibleOperation.id, {
+ visible: true,
+ eventType,
+ unitId: 'first',
+ })).toBe(true);
+ expect(injector.get(IEditorBridgeService).isVisible().visible).toBe(true);
+ expect(commands.syncExecuteCommand(SetCellEditVisibleOperation.id, {
+ visible: false,
+ eventType: DeviceInputEventType.Dblclick,
+ unitId: 'first',
+ })).toBe(true);
+ expect(injector.get(IEditorBridgeService).isVisible().visible).toBe(false);
+ }
+ );
+
+ it('checks the edited cell location across cells, worksheets, and workbooks', () => {
+ addRule(univer, 'first', 'sheet1', 1, DataValidationType.LIST);
+ const injector = univer.__getInjector();
+ const commands = injector.get(ICommandService);
+ for (const [workbook, sheetId, column, editable] of [
+ [first, 'sheet1', 0, false],
+ [first, 'sheet1', 1, true],
+ [first, 'sheet2', 0, true],
+ [peer, 'sheet1', 0, true],
+ ] as const) {
+ selectEditorCell(univer, workbook, 1, column, sheetId);
+ const unitId = workbook.getUnitId();
+ expect(commands.syncExecuteCommand(SetCellEditVisibleOperation.id, {
+ visible: true,
+ eventType: DeviceInputEventType.Dblclick,
+ unitId,
+ pointerPosition: { x: 100, y: 100 },
+ })).toBe(editable);
+ expect(injector.get(IEditorBridgeService).isVisible().visible).toBe(editable);
+ commands.syncExecuteCommand(SetCellEditVisibleOperation.id, {
+ visible: false,
+ eventType: DeviceInputEventType.PointerDown,
+ unitId,
+ });
+ }
+ });
+
+ it('releases the editing restriction when disposed', () => {
+ addRule(univer, 'first', 'sheet1', 1, DataValidationType.CHECKBOX);
+ selectEditorCell(univer, first, 1);
+ const injector = univer.__getInjector();
+ injector.get(Controller).dispose();
+
+ expect(injector.get(ICommandService).syncExecuteCommand(SetCellEditVisibleOperation.id, {
+ visible: true,
+ eventType: DeviceInputEventType.Dblclick,
+ unitId: 'first',
+ pointerPosition: { x: 100, y: 100 },
+ })).toBe(true);
+ expect(injector.get(IEditorBridgeService).isVisible().visible).toBe(true);
+ });
+ }
+
it('keeps each workbook and worksheet in a shared batch isolated after focus changes', async () => {
const injector = univer.__getInjector();
const instances = injector.get(IUniverInstanceService);
@@ -235,6 +352,32 @@ for (const Controller of controllers) {
});
}
+function selectEditorCell(univer: Univer, workbook: Workbook, row: number, column = 0, sheetId = 'sheet1') {
+ const injector = univer.__getInjector();
+ injector.get(IUniverInstanceService).setCurrentUnitForType(workbook.getUnitId());
+ const worksheet = workbook.getSheetBySheetId(sheetId)!;
+ workbook.setActiveSheet(worksheet);
+ const render = injector.get(IRenderManagerService).getRenderUnitById(workbook.getUnitId())!;
+ if (!render.scene.getViewport(SHEET_VIEWPORT_KEY.VIEW_MAIN)) {
+ injector.createInstance(Viewport, SHEET_VIEWPORT_KEY.VIEW_MAIN, render.scene, {
+ left: 0,
+ top: 0,
+ right: 0,
+ bottom: 0,
+ });
+ }
+ render.with(SheetSkeletonManagerService).setCurrent({ sheetId });
+ const bridge = injector.get(IEditorBridgeService);
+ bridge.setEditCell({
+ unitId: workbook.getUnitId(),
+ sheetId,
+ scene: render.scene,
+ engine: render.engine,
+ primary: worksheet.getCellInfoInMergeData(row, column),
+ });
+ expect(bridge.getEditLocation()).toMatchObject({ unitId: workbook.getUnitId(), sheetId, row, column });
+}
+
function addRule(
univer: Univer,
unitId: string,
diff --git a/packages/sheets-data-validation-ui/src/controllers/dv-alert.controller.ts b/packages/sheets-data-validation-ui/src/controllers/dv-alert.controller.ts
index 06f46ca635..d890617a82 100644
--- a/packages/sheets-data-validation-ui/src/controllers/dv-alert.controller.ts
+++ b/packages/sheets-data-validation-ui/src/controllers/dv-alert.controller.ts
@@ -14,8 +14,10 @@
* limitations under the License.
*/
-import type { Workbook } from '@univerjs/core';
+import type { IRange, Nullable, Workbook } from '@univerjs/core';
import type { BaseDataValidator } from '@univerjs/data-validation';
+import type { ISheetLocationBase } from '@univerjs/sheets';
+import type { IHoverCellPosition } from '@univerjs/sheets-ui';
import type { LocaleKey } from '../locale/types';
import {
DataValidationStatus,
@@ -23,21 +25,25 @@ import {
Inject,
IUniverInstanceService,
LocaleService,
+ Rectangle,
UniverInstanceType,
} from '@univerjs/core';
-import { SheetDataValidationModel } from '@univerjs/sheets-data-validation';
+import { DataValidationCacheService, SheetDataValidationModel } from '@univerjs/sheets-data-validation';
import { CellAlertManagerService, CellAlertType, HoverManagerService } from '@univerjs/sheets-ui';
-import { debounceTime, of, switchMap } from 'rxjs';
+import { auditTime, debounceTime, filter, of, switchMap, tap } from 'rxjs';
const ALERT_KEY = 'SHEET_DATA_VALIDATION_ALERT';
export class DataValidationAlertController extends Disposable {
+ private _hoveredCell: Nullable<IHoverCellPosition> = null;
+
constructor(
@Inject(HoverManagerService) private readonly _hoverManagerService: HoverManagerService,
@Inject(CellAlertManagerService) private readonly _cellAlertManagerService: CellAlertManagerService,
@IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService,
@Inject(LocaleService) private readonly _localeService: LocaleService,
- @Inject(SheetDataValidationModel) private readonly _dataValidationModel: SheetDataValidationModel
+ @Inject(SheetDataValidationModel) private readonly _dataValidationModel: SheetDataValidationModel,
+ @Inject(DataValidationCacheService) private readonly _dataValidationCacheService: DataValidationCacheService
) {
super();
this._init();
@@ -50,57 +56,119 @@ export class DataValidationAlertController extends Disposable {
private _initCellAlertPopup() {
this.disposeWithMe(this._univerInstanceService.getCurrentTypeOfUnit$<Workbook>(UniverInstanceType.UNIVER_SHEET).pipe(
switchMap((workbook) => workbook?.activeSheet$ ?? of(null))
- ).subscribe(() => this._cellAlertManagerService.removeAlert(ALERT_KEY)));
-
- this.disposeWithMe(this._hoverManagerService.currentCell$.pipe(debounceTime(100)).subscribe((cellPos) => {
- if (cellPos) {
- const workbook = this._univerInstanceService.getUnit<Workbook>(cellPos.location.unitId, UniverInstanceType.UNIVER_SHEET);
- if (!workbook || workbook.getActiveSheet()?.getSheetId() !== cellPos.location.subUnitId) {
- this._cellAlertManagerService.removeAlert(ALERT_KEY);
- return;
- }
- const worksheet = workbook.getSheetBySheetId(cellPos.location.subUnitId);
- if (!worksheet) return;
- const rule = this._dataValidationModel.getRuleByLocation(cellPos.location.unitId, cellPos.location.subUnitId, cellPos.location.row, cellPos.location.col);
- if (!rule) {
- this._cellAlertManagerService.removeAlert(ALERT_KEY);
- return;
- }
+ ).subscribe(() => {
+ this._hoveredCell = null;
+ this._cellAlertManagerService.removeAlert(ALERT_KEY);
+ }));
+
+ this.disposeWithMe(this._hoverManagerService.currentCell$.pipe(
+ tap(() => {
+ this._hoveredCell = null;
+ this._cellAlertManagerService.removeAlert(ALERT_KEY);
+ }),
+ debounceTime(100)
+ ).subscribe((cellPos) => {
+ this._hoveredCell = cellPos;
+ this._refreshAlert();
+ }));
- const validStatus = this._dataValidationModel.validator(rule, { ...cellPos.location, workbook, worksheet });
- if (validStatus === DataValidationStatus.INVALID) {
- const currentAlert = this._cellAlertManagerService.currentAlert.get(ALERT_KEY);
- const currentLoc = currentAlert?.alert?.location;
- if (
- currentLoc &&
- currentLoc.row === cellPos.location.row &&
- currentLoc.col === cellPos.location.col &&
- currentLoc.subUnitId === cellPos.location.subUnitId &&
- currentLoc.unitId === cellPos.location.unitId
- ) {
- this._cellAlertManagerService.removeAlert(ALERT_KEY);
- return;
- }
-
- const validator = this._dataValidationModel.getValidator(rule.type) as BaseDataValidator;
- if (!validator) {
- this._cellAlertManagerService.removeAlert(ALERT_KEY);
- return;
- }
- this._cellAlertManagerService.showAlert({
- type: CellAlertType.ERROR,
- title: this._localeService.t<LocaleKey>('sheets-data-validation-ui.error.title'),
- message: validator?.getRuleFinalError(rule, cellPos.location),
- location: cellPos.location,
- width: 200,
- height: 74,
- key: ALERT_KEY,
- });
- return;
+ this.disposeWithMe(this._dataValidationModel.ruleChange$.subscribe((change) => {
+ if (this._affectsHoveredCell(change, [...change.rule.ranges, ...change.oldRule?.ranges ?? []])) {
+ this._refreshAlert();
+ }
+ }));
+
+ this.disposeWithMe(this._dataValidationCacheService.dirtyRanges$.pipe(
+ filter((change) => this._affectsHoveredCell(change, change.ranges)),
+ tap(() => this._cellAlertManagerService.removeAlert(ALERT_KEY)),
+ // Rule updates invalidate caches before their location matrix has finished updating.
+ auditTime(0)
+ ).subscribe(() => this._refreshAlert()));
+
+ this.disposeWithMe(this._dataValidationModel.validStatusChange$.subscribe((change) => {
+ if (this._isHoveredLocation(change)) {
+ const rule = this._dataValidationModel.getRuleByLocation(change.unitId, change.subUnitId, change.row, change.col);
+ if (rule?.uid === change.ruleId) {
+ this._updateAlert(change.status);
}
}
+ }));
+ this.disposeWithMe(() => {
+ this._hoveredCell = null;
this._cellAlertManagerService.removeAlert(ALERT_KEY);
- }));
+ });
+ }
+
+ private _isHoveredLocation(location: ISheetLocationBase) {
+ const current = this._hoveredCell?.location;
+ return current?.unitId === location.unitId && current?.subUnitId === location.subUnitId &&
+ current?.row === location.row && current?.col === location.col;
+ }
+
+ private _affectsHoveredCell(location: Pick<ISheetLocationBase, 'unitId' | 'subUnitId'>, ranges: IRange[]) {
+ const current = this._hoveredCell?.location;
+ return current?.unitId === location.unitId && current?.subUnitId === location.subUnitId &&
+ ranges.some((range) => Rectangle.contains(range, {
+ startRow: current.row,
+ endRow: current.row,
+ startColumn: current.col,
+ endColumn: current.col,
+ }));
+ }
+
+ private _getHoveredContext() {
+ const location = this._hoveredCell?.location;
+ if (!location) {
+ return;
+ }
+ const workbook = this._univerInstanceService.getUnit<Workbook>(location.unitId, UniverInstanceType.UNIVER_SHEET);
+ const worksheet = workbook?.getActiveSheet();
+ if (!workbook || !worksheet || worksheet.getSheetId() !== location.subUnitId) {
+ return;
+ }
+ const rule = this._dataValidationModel.getRuleByLocation(location.unitId, location.subUnitId, location.row, location.col);
+ if (rule) {
+ return { location, workbook, worksheet, rule };
+ }
+ }
+
+ private _refreshAlert() {
+ const context = this._getHoveredContext();
+ if (!context) {
+ this._cellAlertManagerService.removeAlert(ALERT_KEY);
+ return;
+ }
+ const { location, workbook, worksheet, rule } = context;
+ this._updateAlert(this._dataValidationModel.validator(rule, { ...location, workbook, worksheet }));
+ }
+
+ private _updateAlert(status: DataValidationStatus) {
+ const context = this._getHoveredContext();
+ if (!context || status !== DataValidationStatus.INVALID) {
+ this._cellAlertManagerService.removeAlert(ALERT_KEY);
+ return;
+ }
+ const { location, rule } = context;
+ const validator = this._dataValidationModel.getValidator(rule.type) as BaseDataValidator;
+ if (!validator) {
+ this._cellAlertManagerService.removeAlert(ALERT_KEY);
+ return;
+ }
+ const title = this._localeService.t<LocaleKey>('sheets-data-validation-ui.error.title');
+ const message = validator.getRuleFinalError(rule, location);
+ const currentAlert = this._cellAlertManagerService.currentAlert.get(ALERT_KEY)?.alert;
+ if (currentAlert && this._isHoveredLocation(currentAlert.location) && currentAlert.title === title && currentAlert.message === message) {
+ return;
+ }
+ this._cellAlertManagerService.showAlert({
+ type: CellAlertType.ERROR,
+ title,
+ message,
+ location,
+ width: 200,
+ height: 74,
+ key: ALERT_KEY,
+ });
}
}
diff --git a/packages/sheets-data-validation-ui/src/controllers/dv-render.controller.ts b/packages/sheets-data-validation-ui/src/controllers/dv-render.controller.ts
index 8bf3a7aff8..1e60bdec24 100644
--- a/packages/sheets-data-validation-ui/src/controllers/dv-render.controller.ts
+++ b/packages/sheets-data-validation-ui/src/controllers/dv-render.controller.ts
@@ -16,7 +16,9 @@
import type { CellValue, ICellRenderContext, IRange, Nullable, Workbook } from '@univerjs/core';
import type { IRuleChange } from '@univerjs/data-validation';
+import type { IEditorBridgeServiceVisibleParam } from '@univerjs/sheets-ui';
import {
+ CanceledError,
DataValidationStatus,
DataValidationType,
ICommandService,
@@ -29,10 +31,15 @@ import {
UniverInstanceType,
} from '@univerjs/core';
import { DataValidatorRegistryService } from '@univerjs/data-validation';
-import { IRenderManagerService } from '@univerjs/engine-render';
+import { DeviceInputEventType, IRenderManagerService } from '@univerjs/engine-render';
import { InterceptCellContentPriority, INTERCEPTOR_POINT, SheetInterceptorService } from '@univerjs/sheets';
import { DataValidationCacheService, getCellValueOrigin, SheetDataValidationModel } from '@univerjs/sheets-data-validation';
-import { AutoHeightController, IEditorBridgeService, SheetSkeletonManagerService } from '@univerjs/sheets-ui';
+import {
+ AutoHeightController,
+ IEditorBridgeService,
+ SetCellEditVisibleOperation,
+ SheetSkeletonManagerService,
+} from '@univerjs/sheets-ui';
import { IMenuManagerService } from '@univerjs/ui';
import { bufferTime, filter, takeUntil } from 'rxjs';
import { menuSchema } from '../menu/schema';
@@ -62,6 +69,7 @@ export class SheetsDataValidationRenderController extends RxDisposable {
super();
this._initMenu();
+ this._initEditor();
this._initDropdown();
this._initViewModelIntercept();
this._initAutoHeight();
@@ -71,6 +79,35 @@ export class SheetsDataValidationRenderController extends RxDisposable {
this._menuManagerService.mergeMenu(menuSchema);
}
+ private _initEditor() {
+ this.disposeWithMe(this._commandService.beforeCommandExecuted((command) => {
+ if (command.id !== SetCellEditVisibleOperation.id) {
+ return;
+ }
+
+ const params = command.params as IEditorBridgeServiceVisibleParam | undefined;
+ // Facade startEditing also uses Dblclick, but has no pointer coordinates.
+ if (!params?.visible || params.eventType !== DeviceInputEventType.Dblclick || !params.pointerPosition) {
+ return;
+ }
+
+ const location = this._editorBridgeService?.getEditLocation();
+ if (!location || (params.unitId && params.unitId !== location.unitId)) {
+ return;
+ }
+
+ const { unitId, sheetId, row, column } = location;
+ const rule = this._sheetDataValidationModel.getRuleByLocation(unitId, sheetId, row, column);
+ if (rule && (
+ rule.type === DataValidationType.LIST ||
+ rule.type === DataValidationType.LIST_MULTIPLE ||
+ rule.type === DataValidationType.CHECKBOX
+ )) {
+ throw new CanceledError();
+ }
+ }));
+ }
+
private _initDropdown() {
if (!this._editorBridgeService) {
return;
diff --git a/packages/sheets-hyper-link-ui/src/services/__tests__/resolver.service.spec.ts b/packages/sheets-hyper-link-ui/src/services/__tests__/resolver.service.spec.ts
index 8e03bcfa12..5163c346f3 100644
--- a/packages/sheets-hyper-link-ui/src/services/__tests__/resolver.service.spec.ts
+++ b/packages/sheets-hyper-link-ui/src/services/__tests__/resolver.service.spec.ts
@@ -14,14 +14,31 @@
* limitations under the License.
*/
+import type { IRange, IWorkbookData, Workbook } from '@univerjs/core';
import type { IMessageProps } from '@univerjs/design';
-import { ICommandService, IConfigService, Injector, IUniverInstanceService, LocaleService } from '@univerjs/core';
-import { IDefinedNamesService } from '@univerjs/engine-formula';
-import { SetSelectionsOperation, SetWorksheetActiveOperation } from '@univerjs/sheets';
+import {
+ ICommandService,
+ IConfigService,
+ Injector,
+ IUniverInstanceService,
+ LocaleService,
+ LocaleType,
+ RANGE_TYPE,
+ Univer,
+ UniverInstanceType,
+} from '@univerjs/core';
+import { DefinedNamesService, IDefinedNamesService } from '@univerjs/engine-formula';
+import { IRenderManagerService, RenderManagerService } from '@univerjs/engine-render';
+import {
+ getPrimaryForRange,
+ SetSelectionsOperation,
+ SetWorksheetActiveOperation,
+ SheetsSelectionsService,
+} from '@univerjs/sheets';
import { ERROR_RANGE, SheetHyperLinkType } from '@univerjs/sheets-hyper-link';
import { ScrollToRangeOperation } from '@univerjs/sheets-ui';
-import { IMessageService } from '@univerjs/ui';
-import { afterEach, describe, expect, it } from 'vitest';
+import { DesktopMessageService, IMessageService, IUIPartsService, UIPartsService } from '@univerjs/ui';
+import { afterEach, describe, expect, it, onTestFinished } from 'vitest';
import { SheetsHyperLinkResolverService } from '../resolver.service';
class TestCommandService {
@@ -91,6 +108,9 @@ function createWorksheet(sheetId: string, options?: { hidden?: boolean }) {
return {
getSheetId: () => sheetId,
getMergeData: () => [{ startRow: 1, endRow: 1, startColumn: 1, endColumn: 2 }],
+ getMergedCell: (row: number, col: number) => row === 1 && col >= 1 && col <= 2
+ ? { startRow: 1, endRow: 1, startColumn: 1, endColumn: 2 }
+ : null,
getMaxColumns: () => 10,
getMaxRows: () => 10,
isSheetHidden: () => !!options?.hidden,
@@ -134,15 +154,82 @@ function createResolver() {
const originalOpen = window.open;
const waitForNavigationJobs = () => new Promise((resolve) => setTimeout(resolve));
+function createSelectionResolverTestBed() {
+ const univer = new Univer({ locale: LocaleType.EN_US });
+ onTestFinished(() => univer.dispose());
+ const injector = univer.__getInjector();
+ injector.add([IDefinedNamesService, { useClass: DefinedNamesService }]);
+ injector.add([IUIPartsService, { useClass: UIPartsService }]);
+ injector.add([IMessageService, { useClass: DesktopMessageService }]);
+ injector.add([IRenderManagerService, { useClass: RenderManagerService }]);
+ injector.add([SheetsSelectionsService]);
+ injector.add([SheetsHyperLinkResolverService]);
+ const merge = { startRow: 2, endRow: 7, startColumn: 3, endColumn: 6 };
+ const workbook = univer.createUnit<IWorkbookData, Workbook>(UniverInstanceType.UNIVER_SHEET, {
+ id: 'link-workbook',
+ sheetOrder: ['sheet1'],
+ sheets: { sheet1: { id: 'sheet1', rowCount: 20, columnCount: 20, mergeData: [merge] } },
+ });
+ const commands = injector.get(ICommandService);
+ commands.registerCommand(SetSelectionsOperation);
+ commands.registerCommand(ScrollToRangeOperation);
+ commands.syncExecuteCommand(SetSelectionsOperation.id, {
+ unitId: workbook.getUnitId(),
+ subUnitId: 'sheet1',
+ selections: [{ range: merge, primary: workbook.getActiveSheet().getCellInfoInMergeData(2, 3) }],
+ });
+ return { injector, workbook, merge };
+}
+
describe('SheetsHyperLinkResolverService', () => {
afterEach(() => {
window.open = originalOpen;
});
+ it.each([undefined, RANGE_TYPE.NORMAL])(
+ 'restores the merged selection when cancel navigates to its top-left cell with range type %s',
+ async (rangeType) => {
+ const { injector, workbook, merge } = createSelectionResolverTestBed();
+ const resolver = injector.get(SheetsHyperLinkResolverService);
+ const range: IRange = { startRow: 2, endRow: 2, startColumn: 3, endColumn: 3 };
+ if (rangeType !== undefined) {
+ range.rangeType = rangeType;
+ }
+
+ await resolver.navigateToRange(workbook.getUnitId(), 'sheet1', range, true);
+
+ expect(injector.get(SheetsSelectionsService).getCurrentLastSelection()?.range).toEqual({
+ ...merge,
+ rangeType: RANGE_TYPE.NORMAL,
+ });
+ expect(workbook.getActiveSheet().getMergeData()).toEqual([merge]);
+ expect(injector.get(SheetsSelectionsService).getCurrentLastSelection()?.primary).toEqual(
+ expect.objectContaining({ ...merge, actualRow: 2, actualColumn: 3, isMerged: true, isMergedMainCell: true })
+ );
+ }
+ );
+
+ it.each([
+ { startRow: 2, endRow: 2, startColumn: 0, endColumn: 19, rangeType: RANGE_TYPE.ROW },
+ { startRow: 0, endRow: 19, startColumn: 3, endColumn: 3, rangeType: RANGE_TYPE.COLUMN },
+ { startRow: 9, endRow: 9, startColumn: 9, endColumn: 9 },
+ ])('preserves row, column and unmerged target ranges: %j', async (range) => {
+ const { injector, workbook } = createSelectionResolverTestBed();
+ const resolver = injector.get(SheetsHyperLinkResolverService);
+
+ await resolver.navigateToRange(workbook.getUnitId(), 'sheet1', range);
+
+ expect(injector.get(SheetsSelectionsService).getCurrentLastSelection()?.range).toEqual({
+ ...range,
+ rangeType: range.rangeType ?? RANGE_TYPE.NORMAL,
+ });
+ });
+
it('should navigate to sheet ranges and execute selection and scroll commands', async () => {
const { resolver, commandService, univerInstanceService } = createResolver();
const targetSheet = createWorksheet('sheet-2');
univerInstanceService.currentUnit = createWorkbook({ targetSheet });
+ const targetRange = { startRow: 1, endRow: 9, startColumn: 1, endColumn: 9, rangeType: RANGE_TYPE.NORMAL };
await resolver.navigateToRange('unit-1', 'sheet-2', { startRow: 1, endRow: 20, startColumn: 1, endColumn: 20 }, true);
@@ -153,12 +240,12 @@ describe('SheetsHyperLinkResolverService', () => {
params: {
unitId: 'unit-1',
subUnitId: 'sheet-2',
- selections: [{ range: { startRow: 1, endRow: 9, startColumn: 1, endColumn: 9 }, primary: null }],
+ selections: [{ range: targetRange, primary: getPrimaryForRange(targetRange, targetSheet) }],
},
},
{
id: ScrollToRangeOperation.id,
- params: { range: { startRow: 1, endRow: 9, startColumn: 1, endColumn: 9 }, forceTop: true },
+ params: { range: targetRange, forceTop: true },
},
]);
});
diff --git a/packages/sheets-hyper-link-ui/src/services/resolver.service.ts b/packages/sheets-hyper-link-ui/src/services/resolver.service.ts
index 2d653b7b75..f92cc4e4e3 100644
--- a/packages/sheets-hyper-link-ui/src/services/resolver.service.ts
+++ b/packages/sheets-hyper-link-ui/src/services/resolver.service.ts
@@ -33,7 +33,7 @@ import {
} from '@univerjs/core';
import { MessageType } from '@univerjs/design';
import { deserializeRangeWithSheet, IDefinedNamesService } from '@univerjs/engine-formula';
-import { SetSelectionsOperation, SetWorksheetActiveOperation } from '@univerjs/sheets';
+import { getPrimaryForRange, SetSelectionsOperation, SetWorksheetActiveOperation } from '@univerjs/sheets';
import { ERROR_RANGE, SheetHyperLinkType } from '@univerjs/sheets-hyper-link';
import { ScrollToRangeOperation } from '@univerjs/sheets-ui';
import { IMessageService } from '@univerjs/ui';
@@ -51,7 +51,7 @@ function getContainRange(range: IRange, worksheet: Worksheet) {
range.endRow = maxRow;
}
- if (range.rangeType === RANGE_TYPE.COLUMN || RANGE_TYPE.ROW) {
+ if (range.rangeType === RANGE_TYPE.COLUMN || range.rangeType === RANGE_TYPE.ROW) {
return range;
}
@@ -153,7 +153,7 @@ export class SheetsHyperLinkResolverService {
selections: [{
range: realRange,
- primary: null,
+ primary: getPrimaryForRange(realRange, worksheet),
}],
} as ISetSelectionsOperationParams
);
diff --git a/packages/sheets-hyper-link-ui/src/views/CellLinkEdit.tsx b/packages/sheets-hyper-link-ui/src/views/CellLinkEdit.tsx
index 1c207d94ea..cba87f7283 100644
--- a/packages/sheets-hyper-link-ui/src/views/CellLinkEdit.tsx
+++ b/packages/sheets-hyper-link-ui/src/views/CellLinkEdit.tsx
@@ -41,7 +41,7 @@ import {
serializeRangeWithSheet,
} from '@univerjs/engine-formula';
import { IRenderManagerService } from '@univerjs/engine-render';
-import { SetWorksheetActiveOperation, SheetsSelectionsService } from '@univerjs/sheets';
+import { SheetsSelectionsService } from '@univerjs/sheets';
import { RangeSelector } from '@univerjs/sheets-formula-ui';
import {
AddHyperLinkCommand,
@@ -51,7 +51,7 @@ import {
UpdateHyperLinkCommand,
UpdateRichHyperLinkCommand,
} from '@univerjs/sheets-hyper-link';
-import { IEditorBridgeService, IMarkSelectionService, ScrollToRangeOperation } from '@univerjs/sheets-ui';
+import { IEditorBridgeService, IMarkSelectionService } from '@univerjs/sheets-ui';
import { KeyCode, useDependency, useEvent, useObservable } from '@univerjs/ui';
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { CloseHyperLinkPopupOperation } from '../commands/operations/popup.operations';
@@ -407,19 +407,11 @@ export const CellLinkEdit = () => {
}
}
if (editing?.type === HyperLinkEditSourceType.VIEWING) {
- await commandService.executeCommand(SetWorksheetActiveOperation.id, {
- unitId: editing.unitId,
- subUnitId: editing.subUnitId,
- });
-
- const GAP = 1;
- await commandService.executeCommand(ScrollToRangeOperation.id, {
- range: {
- startRow: Math.max(editing.row - GAP, 0),
- endRow: editing.row + GAP,
- startColumn: Math.max(editing.col - GAP, 0),
- endColumn: editing.col + GAP,
- },
+ await resolverService.navigateToRange(editing.unitId, editing.subUnitId, {
+ startRow: editing.row,
+ endRow: editing.row,
+ startColumn: editing.col,
+ endColumn: editing.col,
});
}
diff --git a/packages/sheets-hyper-link-ui/src/views/MobileCellLinkEdit.tsx b/packages/sheets-hyper-link-ui/src/views/MobileCellLinkEdit.tsx
index 7ed5f8917d..4bc67faea8 100644
--- a/packages/sheets-hyper-link-ui/src/views/MobileCellLinkEdit.tsx
+++ b/packages/sheets-hyper-link-ui/src/views/MobileCellLinkEdit.tsx
@@ -41,7 +41,7 @@ import {
serializeRangeWithSheet,
} from '@univerjs/engine-formula';
import { IRenderManagerService } from '@univerjs/engine-render';
-import { SetWorksheetActiveOperation, SheetsSelectionsService } from '@univerjs/sheets';
+import { SheetsSelectionsService } from '@univerjs/sheets';
import { MobileRangeSelector } from '@univerjs/sheets-formula-ui';
import {
AddHyperLinkCommand,
@@ -51,7 +51,7 @@ import {
UpdateHyperLinkCommand,
UpdateRichHyperLinkCommand,
} from '@univerjs/sheets-hyper-link';
-import { IEditorBridgeService, IMarkSelectionService, ScrollToRangeOperation } from '@univerjs/sheets-ui';
+import { IEditorBridgeService, IMarkSelectionService } from '@univerjs/sheets-ui';
import { KeyCode, useDependency, useEvent, useObservable } from '@univerjs/ui';
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { CloseHyperLinkPopupOperation } from '../commands/operations/popup.operations';
@@ -407,19 +407,11 @@ export const MobileCellLinkEdit = () => {
}
}
if (editing?.type === HyperLinkEditSourceType.VIEWING) {
- await commandService.executeCommand(SetWorksheetActiveOperation.id, {
- unitId: editing.unitId,
- subUnitId: editing.subUnitId,
- });
-
- const GAP = 1;
- await commandService.executeCommand(ScrollToRangeOperation.id, {
- range: {
- startRow: Math.max(editing.row - GAP, 0),
- endRow: editing.row + GAP,
- startColumn: Math.max(editing.col - GAP, 0),
- endColumn: editing.col + GAP,
- },
+ await resolverService.navigateToRange(editing.unitId, editing.subUnitId, {
+ startRow: editing.row,
+ endRow: editing.row,
+ startColumn: editing.col,
+ endColumn: editing.col,
});
}
diff --git a/packages/sheets-hyper-link-ui/src/views/__tests__/CellLinkEdit.spec.tsx b/packages/sheets-hyper-link-ui/src/views/__tests__/CellLinkEdit.spec.tsx
new file mode 100644
index 0000000000..5951dde682
--- /dev/null
+++ b/packages/sheets-hyper-link-ui/src/views/__tests__/CellLinkEdit.spec.tsx
@@ -0,0 +1,263 @@
+/**
+ * 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 { Root } from 'react-dom/client';
+import type { TestRenderManagerService } from './hyper-link-popup-test-bed';
+import { CustomRangeType, LocaleService, LocaleType } from '@univerjs/core';
+import { IRenderManagerService } from '@univerjs/engine-render';
+import { SetSelectionsOperation, SheetsSelectionsService } from '@univerjs/sheets';
+import { SheetHyperLinkType } from '@univerjs/sheets-hyper-link';
+import { IMarkSelectionService } from '@univerjs/sheets-ui';
+import { RediContext } from '@univerjs/ui';
+import { act } from 'react';
+import { createRoot } from 'react-dom/client';
+import { afterEach, describe, expect, it } from 'vitest';
+import { ISheetsHyperLinkPopupService } from '../../services/popup.service';
+import { HyperLinkEditSourceType } from '../../types/enums/edit-source';
+import { CellLinkEdit } from '../CellLinkEdit';
+import { MobileCellLinkEdit } from '../MobileCellLinkEdit';
+import { createPopupTestBed, inputText, MERGED_RANGE, selectOption, SUB_UNIT_ID, UNIT_ID } from './hyper-link-popup-test-bed';
+
+describe('CellLinkEdit', () => {
+ let root: Root | undefined;
+ let container: HTMLDivElement | undefined;
+ let currentTestBed: ReturnType<typeof createPopupTestBed> | undefined;
+
+ afterEach(() => {
+ act(() => {
+ root?.unmount();
+ });
+ container?.remove();
+ currentTestBed?.univer.dispose();
+ root = undefined;
+ container = undefined;
+ currentTestBed = undefined;
+ });
+
+ it.each([
+ { LinkEdit: CellLinkEdit, action: 'Cancel' },
+ { LinkEdit: CellLinkEdit, action: 'OK' },
+ { LinkEdit: MobileCellLinkEdit, action: 'Cancel' },
+ { LinkEdit: MobileCellLinkEdit, action: 'OK' },
+ ])('clears the source marker and restores the merged primary after $action', async ({ LinkEdit, action }) => {
+ currentTestBed = createPopupTestBed();
+ const { injector, commandService, workbook } = currentTestBed;
+ injector.get(LocaleService).setLocale(LocaleType.EN_US);
+ const worksheet = workbook.getActiveSheet();
+ const popupService = injector.get(ISheetsHyperLinkPopupService);
+ const markSelectionService = injector.get(IMarkSelectionService);
+ const row = MERGED_RANGE.startRow;
+ const col = MERGED_RANGE.startColumn;
+ commandService.syncExecuteCommand(SetSelectionsOperation.id, {
+ unitId: UNIT_ID,
+ subUnitId: SUB_UNIT_ID,
+ selections: [{ range: MERGED_RANGE, primary: worksheet.getCellInfoInMergeData(row, col) }],
+ });
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+ act(() => {
+ popupService.startAddEditing({ unitId: UNIT_ID, subUnitId: SUB_UNIT_ID, row, col, type: HyperLinkEditSourceType.VIEWING });
+ root!.render(
+ <RediContext.Provider value={{ injector }}>
+ <LinkEdit />
+ </RediContext.Provider>
+ );
+ });
+ expect(markSelectionService.getShapeMap().size).toBe(1);
+ expect([...markSelectionService.getShapeMap().values()][0].selection.range).toEqual(MERGED_RANGE);
+ if (action === 'OK') {
+ const inputs = container.querySelectorAll('input');
+ await act(async () => {
+ inputText(inputs[0], 'Merged link');
+ inputText(inputs[inputs.length - 1], 'https://univer.ai');
+ });
+ }
+ commandService.syncExecuteCommand(SetSelectionsOperation.id, {
+ unitId: UNIT_ID,
+ subUnitId: SUB_UNIT_ID,
+ selections: [{
+ range: { startRow: 10, endRow: 10, startColumn: 10, endColumn: 10 },
+ primary: worksheet.getCellInfoInMergeData(10, 10),
+ }],
+ });
+ const renderManagerService = injector.get(IRenderManagerService) as unknown as TestRenderManagerService;
+ renderManagerService.enableScrollRender = true;
+ const button = [...container.querySelectorAll<HTMLButtonElement>('button')].find((button) => button.textContent === action);
+ expect(button).toBeDefined();
+ await act(async () => {
+ button!.click();
+ });
+ expect(popupService.currentEditing).toBeNull();
+ expect(markSelectionService.getShapeMap().size).toBe(0);
+ const selection = injector.get(SheetsSelectionsService).getCurrentLastSelection();
+ expect(selection?.range).toEqual(expect.objectContaining(MERGED_RANGE));
+ expect(selection?.primary).toEqual(expect.objectContaining({
+ ...MERGED_RANGE,
+ actualRow: row,
+ actualColumn: col,
+ isMerged: true,
+ isMergedMainCell: true,
+ }));
+ if (action === 'OK') {
+ expect(worksheet.getCellRaw(row, col)?.p?.body?.customRanges?.[0].properties?.url).toBe('https://univer.ai');
+ }
+ });
+
+ it('inherits the page direction for labels and uses left-to-right direction for URLs', () => {
+ currentTestBed = createPopupTestBed();
+ container = document.createElement('div');
+ container.dir = 'rtl';
+ document.body.appendChild(container);
+ root = createRoot(container);
+ const popupService = currentTestBed.injector.get(ISheetsHyperLinkPopupService);
+
+ act(() => {
+ popupService.startAddEditing({
+ unitId: UNIT_ID,
+ subUnitId: SUB_UNIT_ID,
+ row: 1,
+ col: 0,
+ type: HyperLinkEditSourceType.VIEWING,
+ });
+ });
+
+ for (const LinkEdit of [CellLinkEdit, MobileCellLinkEdit]) {
+ act(() => {
+ root!.render(
+ <RediContext.Provider value={{ injector: currentTestBed!.injector }}>
+ <LinkEdit />
+ </RediContext.Provider>
+ );
+ });
+
+ const inputs = Array.from(container.querySelectorAll('input'));
+ expect(inputs).toHaveLength(3);
+ expect(inputs[0].hasAttribute('dir')).toBe(false);
+ expect(inputs[1].hasAttribute('dir')).toBe(false);
+ expect(inputs[2].dir).toBe('ltr');
+ }
+ });
+
+ it('adds a URL hyperlink to the current cell text and closes the popup', async () => {
+ currentTestBed = createPopupTestBed();
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+ const popupService = currentTestBed.injector.get(ISheetsHyperLinkPopupService);
+ const renderManagerService = currentTestBed.injector.get(IRenderManagerService) as unknown as TestRenderManagerService;
+
+ act(() => {
+ popupService.startAddEditing({
+ unitId: UNIT_ID,
+ subUnitId: SUB_UNIT_ID,
+ row: 0,
+ col: 0,
+ type: HyperLinkEditSourceType.VIEWING,
+ });
+ root!.render(
+ <RediContext.Provider value={{ injector: currentTestBed!.injector }}>
+ <CellLinkEdit />
+ </RediContext.Provider>
+ );
+ });
+
+ const inputs = Array.from(container.querySelectorAll('input'));
+ expect(inputs).toHaveLength(2);
+
+ await act(async () => {
+ inputText(inputs[0], 'Documentation tip');
+ inputText(inputs[1], 'docs.univer.ai');
+ await Promise.resolve();
+ });
+ renderManagerService.enableScrollRender = true;
+
+ const formButtons = Array.from(container.querySelectorAll<HTMLButtonElement>('[data-u-comp="button"]'));
+ const okButton = formButtons[formButtons.length - 1];
+ expect(okButton).toBeDefined();
+
+ await act(async () => {
+ okButton!.click();
+ await Promise.resolve();
+ });
+
+ const cell = currentTestBed.workbook.getSheetBySheetId(SUB_UNIT_ID)?.getCellRaw(0, 0);
+ const body = cell?.p?.body;
+ const linkRange = body?.customRanges?.find((range) => range.rangeType === CustomRangeType.HYPERLINK);
+
+ expect(body?.dataStream).toBe('Univer\r\n');
+ expect(linkRange?.properties?.url).toBe('http://docs.univer.ai');
+ expect(linkRange?.properties?.tooltip).toBe('Documentation tip');
+ expect(popupService.currentEditing).toBeNull();
+ });
+
+ it('switches from URL to worksheet link and saves the selected sheet target', async () => {
+ currentTestBed = createPopupTestBed();
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+ const popupService = currentTestBed.injector.get(ISheetsHyperLinkPopupService);
+ const renderManagerService = currentTestBed.injector.get(IRenderManagerService) as unknown as TestRenderManagerService;
+
+ act(() => {
+ popupService.startAddEditing({
+ unitId: UNIT_ID,
+ subUnitId: SUB_UNIT_ID,
+ row: 0,
+ col: 0,
+ type: HyperLinkEditSourceType.VIEWING,
+ });
+ root!.render(
+ <RediContext.Provider value={{ injector: currentTestBed!.injector }}>
+ <CellLinkEdit />
+ </RediContext.Provider>
+ );
+ });
+
+ const typeSelect = container.querySelector('[data-u-comp="select"]');
+ expect(typeSelect?.textContent).toContain('sheets-hyper-link-ui.form.link');
+
+ await act(async () => {
+ await selectOption(typeSelect!, 'sheets-hyper-link-ui.form.worksheet');
+ await Promise.resolve();
+ });
+
+ const selects = Array.from(container.querySelectorAll('[data-u-comp="select"]'));
+ expect(selects).toHaveLength(2);
+
+ await act(async () => {
+ await selectOption(selects[1], 'Sheet 1');
+ await Promise.resolve();
+ });
+ renderManagerService.enableScrollRender = true;
+
+ const formButtons = Array.from(container.querySelectorAll<HTMLButtonElement>('[data-u-comp="button"]'));
+ const okButton = formButtons[formButtons.length - 1];
+
+ await act(async () => {
+ okButton!.click();
+ await Promise.resolve();
+ });
+
+ const cell = currentTestBed.workbook.getSheetBySheetId(SUB_UNIT_ID)?.getCellRaw(0, 0);
+ const body = cell?.p?.body;
+ const sheetLink = body?.customRanges?.find((range) => range.properties?.url === `#${SheetHyperLinkType.SHEET}=${SUB_UNIT_ID}`);
+
+ expect(body?.dataStream).toBe('Univer\r\n');
+ expect(sheetLink?.rangeType).toBe(CustomRangeType.HYPERLINK);
+ expect(popupService.currentEditing).toBeNull();
+ });
+});
diff --git a/packages/sheets-hyper-link-ui/src/views/__tests__/CellLinkPopup.spec.tsx b/packages/sheets-hyper-link-ui/src/views/__tests__/CellLinkPopup.spec.tsx
index ad2a1e9d2a..2fd6c8dae0 100644
--- a/packages/sheets-hyper-link-ui/src/views/__tests__/CellLinkPopup.spec.tsx
+++ b/packages/sheets-hyper-link-ui/src/views/__tests__/CellLinkPopup.spec.tsx
@@ -14,344 +14,17 @@
* limitations under the License.
*/
-import type { ICustomRange, IWorkbookData, Workbook } from '@univerjs/core';
import type { Root } from 'react-dom/client';
-import {
- CellValueType,
- CustomRangeType,
- ICommandService,
- IUniverInstanceService,
- LocaleService,
- LocaleType,
- toDisposable,
- Univer,
- UniverInstanceType,
-} from '@univerjs/core';
-import { DocSelectionManagerService } from '@univerjs/docs';
-import { IDefinedNamesService } from '@univerjs/engine-formula';
-import { IRenderManagerService } from '@univerjs/engine-render';
-import {
- SetRangeValuesMutation,
- SetWorksheetActiveOperation,
- SheetInterceptorService,
- SheetsSelectionsService,
-} from '@univerjs/sheets';
-import {
- AddHyperLinkCommand,
- AddHyperLinkMutation,
- CancelHyperLinkCommand,
- HyperLinkModel,
- RemoveHyperLinkMutation,
- SheetHyperLinkType,
- SheetsHyperLinkParserService,
- UpdateHyperLinkMutation,
-} from '@univerjs/sheets-hyper-link';
-import {
- IEditorBridgeService,
- IMarkSelectionService,
- ScrollToRangeOperation,
- SheetCanvasPopManagerService,
-} from '@univerjs/sheets-ui';
-import { IDialogService, IMessageService, RediContext } from '@univerjs/ui';
+import { LocaleService, LocaleType } from '@univerjs/core';
+import { RediContext } from '@univerjs/ui';
import { act } from 'react';
import { createRoot } from 'react-dom/client';
-import { of } from 'rxjs';
import { afterEach, describe, expect, it } from 'vitest';
-import {
- CloseHyperLinkPopupOperation,
- OpenHyperLinkEditPanelOperation,
-} from '../../commands/operations/popup.operations';
-import { ISheetsHyperLinkPopupService, SheetsHyperLinkPopupService } from '../../services/popup.service';
-import { SheetsHyperLinkResolverService } from '../../services/resolver.service';
-import { SheetsHyperLinkSidePanelService } from '../../services/side-panel.service';
+import { OpenHyperLinkEditPanelOperation } from '../../commands/operations/popup.operations';
import { HyperLinkEditSourceType } from '../../types/enums/edit-source';
-import { CellLinkEdit } from '../CellLinkEdit';
import { CellLinkPopupPure } from '../CellLinkPopup';
-import { MobileCellLinkEdit } from '../MobileCellLinkEdit';
import { MobileCellLinkPopupPure } from '../MobileCellLinkPopup';
-
-(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
-
-const UNIT_ID = 'sheet-link-popup-workbook';
-const SUB_UNIT_ID = 'sheet-1';
-
-class TestCanvasPopManagerService {
- attachPopupToCell() {
- return toDisposable(() => undefined);
- }
-
- attachPopupByPosition() {
- return toDisposable(() => undefined);
- }
-
- attachPopupToAbsolutePosition() {
- return toDisposable(() => undefined);
- }
-}
-
-class TestRenderManagerService {
- enableScrollRender = false;
- readonly scrollRanges: unknown[] = [];
-
- getRenderUnitById(id: string) {
- if (id !== UNIT_ID || !this.enableScrollRender) {
- return undefined;
- }
-
- return {
- with: () => ({
- scrollToRange: (range: unknown) => {
- this.scrollRanges.push(range);
- return true;
- },
- }),
- };
- }
-}
-
-class TestMarkSelectionService {
- readonly shapes = new Map<string, unknown>();
-
- addShape(selection: unknown) {
- const id = `shape-${this.shapes.size + 1}`;
- this.shapes.set(id, selection);
- return id;
- }
-
- addShapeWithNoFresh(selection: unknown) {
- return this.addShape(selection);
- }
-
- removeShape(id: string) {
- this.shapes.delete(id);
- }
-
- removeAllShapes() {
- this.shapes.clear();
- }
-
- refreshShapes() {}
-
- getShapeMap() {
- return this.shapes;
- }
-}
-
-class TestEditorBridgeService {
- forceKeepVisible = false;
-
- getCurrentEditorId() {
- return 'sheet-popup-editor';
- }
-
- isVisible() {
- return { visible: false };
- }
-
- getEditCellState() {
- return null;
- }
-
- enableForceKeepVisible() {
- this.forceKeepVisible = true;
- }
-
- disableForceKeepVisible() {
- this.forceKeepVisible = false;
- }
-}
-
-class TestDefinedNamesService {
- getValueById() {
- return undefined;
- }
-
- getDefinedNameMap() {
- return {};
- }
-
- getWorksheetByRef() {
- return undefined;
- }
-
- focusRange() {
- // Defined-name navigation is outside these popup component scenarios.
- }
-}
-
-class TestMessageService {
- readonly messages: unknown[] = [];
-
- show(message: unknown) {
- this.messages.push(message);
- }
-}
-
-class TestDialogService {
- open() {
- return toDisposable(() => undefined);
- }
-
- close(): void {}
-
- closeAll(): void {}
-
- getDialogs$() {
- return of([]);
- }
-}
-
-function createCellDocument(text: string, range: ICustomRange) {
- return {
- id: `${range.rangeId}-doc`,
- documentStyle: {
- pageSize: { width: 100, height: 40 },
- marginTop: 0,
- marginBottom: 0,
- marginLeft: 0,
- marginRight: 0,
- },
- body: {
- dataStream: `${text}\r\n`,
- customRanges: [range],
- },
- };
-}
-
-function createWorkbookData(customRange: ICustomRange): IWorkbookData {
- return {
- id: UNIT_ID,
- appVersion: '3.0.0-alpha',
- name: 'hyperlink popup workbook',
- locale: LocaleType.EN_US,
- sheetOrder: [SUB_UNIT_ID],
- styles: {},
- sheets: {
- [SUB_UNIT_ID]: {
- id: SUB_UNIT_ID,
- name: 'Sheet 1',
- cellData: {
- 0: {
- 0: {
- p: createCellDocument('Univer', customRange),
- t: CellValueType.STRING,
- },
- },
- },
- },
- },
- };
-}
-
-function createHyperLinkRange(): ICustomRange {
- return {
- rangeId: 'link-range',
- rangeType: CustomRangeType.HYPERLINK,
- startIndex: 0,
- endIndex: 5,
- properties: {
- url: 'https://univer.ai',
- },
- };
-}
-
-function createPopupTestBed() {
- const customRange = createHyperLinkRange();
- const univer = new Univer();
- const injector = univer.__getInjector();
-
- injector.add([SheetInterceptorService]);
- injector.add([HyperLinkModel]);
- injector.add([DocSelectionManagerService]);
- injector.add([IDefinedNamesService, { useClass: TestDefinedNamesService as never }]);
- injector.add([IRenderManagerService, { useClass: TestRenderManagerService as never }]);
- injector.add([IMessageService, { useClass: TestMessageService as never }]);
- injector.add([IDialogService, { useClass: TestDialogService }]);
- injector.add([IEditorBridgeService, { useClass: TestEditorBridgeService as never }]);
- injector.add([IMarkSelectionService, { useClass: TestMarkSelectionService as never }]);
- injector.add([SheetCanvasPopManagerService, { useClass: TestCanvasPopManagerService as never }]);
- injector.add([SheetsSelectionsService]);
- injector.add([SheetsHyperLinkParserService]);
- injector.add([SheetsHyperLinkResolverService]);
- injector.add([ISheetsHyperLinkPopupService, { useClass: SheetsHyperLinkPopupService }]);
- injector.add([SheetsHyperLinkSidePanelService]);
-
- const workbook = univer.createUnit<IWorkbookData, Workbook>(UniverInstanceType.UNIVER_SHEET, createWorkbookData(customRange));
- injector.get(IUniverInstanceService).focusUnit(UNIT_ID);
- injector.get(LocaleService).load({
- [LocaleType.EN_US]: {
- 'sheets-hyper-link-ui': {
- popup: {
- open: 'Open link',
- edit: 'Edit',
- cancel: 'Remove link',
- },
- form: {
- label: 'Display text',
- labelPlaceholder: 'Text',
- type: 'Link type',
- link: 'Web link',
- range: 'Range',
- worksheet: 'Worksheet',
- definedName: 'Defined name',
- linkPlaceholder: 'URL',
- inputError: 'Required',
- linkError: 'Invalid link',
- selectError: 'Select a target',
- cancel: 'Cancel',
- ok: 'OK',
- },
- message: {
- coped: 'Copied',
- },
- },
- 'sheets-hyper-link': {
- message: {
- refError: 'Invalid reference',
- },
- },
- },
- });
- const commandService = injector.get(ICommandService);
- commandService.registerCommand(SetRangeValuesMutation);
- commandService.registerCommand(AddHyperLinkMutation);
- commandService.registerCommand(UpdateHyperLinkMutation);
- commandService.registerCommand(RemoveHyperLinkMutation);
- commandService.registerCommand(AddHyperLinkCommand);
- commandService.registerCommand(CancelHyperLinkCommand);
- commandService.registerCommand(OpenHyperLinkEditPanelOperation);
- commandService.registerCommand(CloseHyperLinkPopupOperation);
- commandService.registerCommand(SetWorksheetActiveOperation);
- commandService.registerCommand(ScrollToRangeOperation);
-
- return {
- univer,
- injector,
- commandService,
- workbook,
- customRange,
- };
-}
-
-function inputText(input: HTMLInputElement, value: string) {
- const valueSetter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')?.set;
- valueSetter?.call(input, value);
- input.dispatchEvent(new Event('input', { bubbles: true }));
-}
-
-async function selectOption(trigger: Element, optionText: string) {
- trigger.dispatchEvent(new PointerEvent('pointerdown', { bubbles: true, button: 0 }));
- trigger.dispatchEvent(new MouseEvent('click', { bubbles: true }));
- await Promise.resolve();
-
- const option = Array.from(document.querySelectorAll('button, [data-slot="dropdown-menu-radio-item"]')).find((item) => item.textContent === optionText);
-
- if (!option) {
- throw new Error(`Option ${optionText} was not rendered`);
- }
-
- option.dispatchEvent(new MouseEvent('click', { bubbles: true }));
-}
+import { createPopupTestBed, SUB_UNIT_ID, UNIT_ID } from './hyper-link-popup-test-bed';
function renderPopup(
root: Root,
@@ -488,164 +161,3 @@ describe('CellLinkPopupPure', () => {
expect(cell?.p?.body?.dataStream).toBe('Univer\r\n');
});
});
-
-describe('CellLinkEdit', () => {
- let root: Root | undefined;
- let container: HTMLDivElement | undefined;
- let currentTestBed: ReturnType<typeof createPopupTestBed> | undefined;
-
- afterEach(() => {
- act(() => {
- root?.unmount();
- });
- container?.remove();
- currentTestBed?.univer.dispose();
- root = undefined;
- container = undefined;
- currentTestBed = undefined;
- });
-
- it('inherits the page direction for labels and uses left-to-right direction for URLs', () => {
- currentTestBed = createPopupTestBed();
- container = document.createElement('div');
- container.dir = 'rtl';
- document.body.appendChild(container);
- root = createRoot(container);
- const popupService = currentTestBed.injector.get(ISheetsHyperLinkPopupService);
-
- act(() => {
- popupService.startAddEditing({
- unitId: UNIT_ID,
- subUnitId: SUB_UNIT_ID,
- row: 1,
- col: 0,
- type: HyperLinkEditSourceType.VIEWING,
- });
- });
-
- for (const LinkEdit of [CellLinkEdit, MobileCellLinkEdit]) {
- act(() => {
- root!.render(
- <RediContext.Provider value={{ injector: currentTestBed!.injector }}>
- <LinkEdit />
- </RediContext.Provider>
- );
- });
-
- const inputs = Array.from(container.querySelectorAll('input'));
- expect(inputs).toHaveLength(3);
- expect(inputs[0].hasAttribute('dir')).toBe(false);
- expect(inputs[1].hasAttribute('dir')).toBe(false);
- expect(inputs[2].dir).toBe('ltr');
- }
- });
-
- it('adds a URL hyperlink to the current cell text and closes the popup', async () => {
- currentTestBed = createPopupTestBed();
- container = document.createElement('div');
- document.body.appendChild(container);
- root = createRoot(container);
- const popupService = currentTestBed.injector.get(ISheetsHyperLinkPopupService);
- const renderManagerService = currentTestBed.injector.get(IRenderManagerService) as unknown as TestRenderManagerService;
-
- act(() => {
- popupService.startAddEditing({
- unitId: UNIT_ID,
- subUnitId: SUB_UNIT_ID,
- row: 0,
- col: 0,
- type: HyperLinkEditSourceType.VIEWING,
- });
- root!.render(
- <RediContext.Provider value={{ injector: currentTestBed!.injector }}>
- <CellLinkEdit />
- </RediContext.Provider>
- );
- });
-
- const inputs = Array.from(container.querySelectorAll('input'));
- expect(inputs).toHaveLength(2);
-
- await act(async () => {
- inputText(inputs[0], 'Documentation tip');
- inputText(inputs[1], 'docs.univer.ai');
- await Promise.resolve();
- });
- renderManagerService.enableScrollRender = true;
-
- const formButtons = Array.from(container.querySelectorAll<HTMLButtonElement>('[data-u-comp="button"]'));
- const okButton = formButtons[formButtons.length - 1];
- expect(okButton).toBeDefined();
-
- await act(async () => {
- okButton!.click();
- await Promise.resolve();
- });
-
- const cell = currentTestBed.workbook.getSheetBySheetId(SUB_UNIT_ID)?.getCellRaw(0, 0);
- const body = cell?.p?.body;
- const linkRange = body?.customRanges?.find((range) => range.rangeType === CustomRangeType.HYPERLINK);
-
- expect(body?.dataStream).toBe('Univer\r\n');
- expect(linkRange?.properties?.url).toBe('http://docs.univer.ai');
- expect(linkRange?.properties?.tooltip).toBe('Documentation tip');
- expect(popupService.currentEditing).toBeNull();
- });
-
- it('switches from URL to worksheet link and saves the selected sheet target', async () => {
- currentTestBed = createPopupTestBed();
- container = document.createElement('div');
- document.body.appendChild(container);
- root = createRoot(container);
- const popupService = currentTestBed.injector.get(ISheetsHyperLinkPopupService);
- const renderManagerService = currentTestBed.injector.get(IRenderManagerService) as unknown as TestRenderManagerService;
-
- act(() => {
- popupService.startAddEditing({
- unitId: UNIT_ID,
- subUnitId: SUB_UNIT_ID,
- row: 0,
- col: 0,
- type: HyperLinkEditSourceType.VIEWING,
- });
- root!.render(
- <RediContext.Provider value={{ injector: currentTestBed!.injector }}>
- <CellLinkEdit />
- </RediContext.Provider>
- );
- });
-
- const typeSelect = container.querySelector('[data-u-comp="select"]');
- expect(typeSelect?.textContent).toContain('sheets-hyper-link-ui.form.link');
-
- await act(async () => {
- await selectOption(typeSelect!, 'sheets-hyper-link-ui.form.worksheet');
- await Promise.resolve();
- });
-
- const selects = Array.from(container.querySelectorAll('[data-u-comp="select"]'));
- expect(selects).toHaveLength(2);
-
- await act(async () => {
- await selectOption(selects[1], 'Sheet 1');
- await Promise.resolve();
- });
- renderManagerService.enableScrollRender = true;
-
- const formButtons = Array.from(container.querySelectorAll<HTMLButtonElement>('[data-u-comp="button"]'));
- const okButton = formButtons[formButtons.length - 1];
-
- await act(async () => {
- okButton!.click();
- await Promise.resolve();
- });
-
- const cell = currentTestBed.workbook.getSheetBySheetId(SUB_UNIT_ID)?.getCellRaw(0, 0);
- const body = cell?.p?.body;
- const sheetLink = body?.customRanges?.find((range) => range.properties?.url === `#${SheetHyperLinkType.SHEET}=${SUB_UNIT_ID}`);
-
- expect(body?.dataStream).toBe('Univer\r\n');
- expect(sheetLink?.rangeType).toBe(CustomRangeType.HYPERLINK);
- expect(popupService.currentEditing).toBeNull();
- });
-});
diff --git a/packages/sheets-hyper-link-ui/src/views/__tests__/hyper-link-popup-test-bed.ts b/packages/sheets-hyper-link-ui/src/views/__tests__/hyper-link-popup-test-bed.ts
new file mode 100644
index 0000000000..4a3282f65f
--- /dev/null
+++ b/packages/sheets-hyper-link-ui/src/views/__tests__/hyper-link-popup-test-bed.ts
@@ -0,0 +1,325 @@
+/**
+ * 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 { ICustomRange, IWorkbookData, Workbook } from '@univerjs/core';
+import {
+ CellValueType,
+ CustomRangeType,
+ ICommandService,
+ IUniverInstanceService,
+ LocaleService,
+ LocaleType,
+ toDisposable,
+ Univer,
+ UniverInstanceType,
+} from '@univerjs/core';
+import { DocSelectionManagerService } from '@univerjs/docs';
+import { IDefinedNamesService } from '@univerjs/engine-formula';
+import { IRenderManagerService } from '@univerjs/engine-render';
+import {
+ SetRangeValuesMutation,
+ SetSelectionsOperation,
+ SetWorksheetActiveOperation,
+ SheetInterceptorService,
+ SheetSkeletonService,
+ SheetsSelectionsService,
+} from '@univerjs/sheets';
+import {
+ AddHyperLinkCommand,
+ AddHyperLinkMutation,
+ CancelHyperLinkCommand,
+ HyperLinkModel,
+ RemoveHyperLinkMutation,
+ SheetsHyperLinkParserService,
+ UpdateHyperLinkMutation,
+} from '@univerjs/sheets-hyper-link';
+import {
+ IEditorBridgeService,
+ IMarkSelectionService,
+ MarkSelectionService,
+ ScrollToRangeOperation,
+ SheetCanvasPopManagerService,
+} from '@univerjs/sheets-ui';
+import { IDialogService, IMessageService } from '@univerjs/ui';
+import { of } from 'rxjs';
+import {
+ CloseHyperLinkPopupOperation,
+ OpenHyperLinkEditPanelOperation,
+} from '../../commands/operations/popup.operations';
+import { ISheetsHyperLinkPopupService, SheetsHyperLinkPopupService } from '../../services/popup.service';
+import { SheetsHyperLinkResolverService } from '../../services/resolver.service';
+import { SheetsHyperLinkSidePanelService } from '../../services/side-panel.service';
+
+(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+const UNIT_ID = 'sheet-link-popup-workbook';
+const SUB_UNIT_ID = 'sheet-1';
+const MERGED_RANGE = { startRow: 2, endRow: 5, startColumn: 1, endColumn: 3 };
+
+class TestCanvasPopManagerService {
+ attachPopupToCell() {
+ return toDisposable(() => undefined);
+ }
+
+ attachPopupByPosition() {
+ return toDisposable(() => undefined);
+ }
+
+ attachPopupToAbsolutePosition() {
+ return toDisposable(() => undefined);
+ }
+}
+
+class TestRenderManagerService {
+ enableScrollRender = false;
+ readonly scrollRanges: unknown[] = [];
+
+ getRenderUnitById(id: string) {
+ if (id !== UNIT_ID || !this.enableScrollRender) {
+ return undefined;
+ }
+
+ return {
+ with: () => ({
+ scrollToRange: (range: unknown) => {
+ this.scrollRanges.push(range);
+ return true;
+ },
+ }),
+ };
+ }
+}
+
+class TestEditorBridgeService {
+ forceKeepVisible = false;
+
+ getCurrentEditorId() {
+ return 'sheet-popup-editor';
+ }
+
+ isVisible() {
+ return { visible: false };
+ }
+
+ getEditCellState() {
+ return null;
+ }
+
+ enableForceKeepVisible() {
+ this.forceKeepVisible = true;
+ }
+
+ disableForceKeepVisible() {
+ this.forceKeepVisible = false;
+ }
+}
+
+class TestDefinedNamesService {
+ getValueById() {
+ return undefined;
+ }
+
+ getDefinedNameMap() {
+ return {};
+ }
+
+ getWorksheetByRef() {
+ return undefined;
+ }
+
+ focusRange() {
+ // Defined-name navigation is outside these popup component scenarios.
+ }
+}
+
+class TestMessageService {
+ readonly messages: unknown[] = [];
+
+ show(message: unknown) {
+ this.messages.push(message);
+ }
+}
+
+class TestDialogService {
+ open() {
+ return toDisposable(() => undefined);
+ }
+
+ close(): void {}
+
+ closeAll(): void {}
+
+ getDialogs$() {
+ return of([]);
+ }
+}
+
+function createCellDocument(text: string, range: ICustomRange) {
+ return {
+ id: `${range.rangeId}-doc`,
+ documentStyle: {
+ pageSize: { width: 100, height: 40 },
+ marginTop: 0,
+ marginBottom: 0,
+ marginLeft: 0,
+ marginRight: 0,
+ },
+ body: {
+ dataStream: `${text}\r\n`,
+ customRanges: [range],
+ },
+ };
+}
+
+function createWorkbookData(customRange: ICustomRange): IWorkbookData {
+ return {
+ id: UNIT_ID,
+ appVersion: '3.0.0-alpha',
+ name: 'hyperlink popup workbook',
+ locale: LocaleType.EN_US,
+ sheetOrder: [SUB_UNIT_ID],
+ styles: {},
+ sheets: {
+ [SUB_UNIT_ID]: {
+ id: SUB_UNIT_ID,
+ name: 'Sheet 1',
+ mergeData: [MERGED_RANGE],
+ cellData: {
+ 0: {
+ 0: {
+ p: createCellDocument('Univer', customRange),
+ t: CellValueType.STRING,
+ },
+ },
+ },
+ },
+ },
+ };
+}
+
+function createHyperLinkRange(): ICustomRange {
+ return {
+ rangeId: 'link-range',
+ rangeType: CustomRangeType.HYPERLINK,
+ startIndex: 0,
+ endIndex: 5,
+ properties: {
+ url: 'https://univer.ai',
+ },
+ };
+}
+
+function createPopupTestBed() {
+ const customRange = createHyperLinkRange();
+ const univer = new Univer();
+ const injector = univer.__getInjector();
+
+ injector.add([SheetInterceptorService]);
+ injector.add([HyperLinkModel]);
+ injector.add([DocSelectionManagerService]);
+ injector.add([IDefinedNamesService, { useClass: TestDefinedNamesService as never }]);
+ injector.add([IRenderManagerService, { useClass: TestRenderManagerService as never }]);
+ injector.add([IMessageService, { useClass: TestMessageService as never }]);
+ injector.add([IDialogService, { useClass: TestDialogService }]);
+ injector.add([IEditorBridgeService, { useClass: TestEditorBridgeService as never }]);
+ injector.add([SheetSkeletonService]);
+ injector.add([IMarkSelectionService, { useClass: MarkSelectionService }]);
+ injector.add([SheetCanvasPopManagerService, { useClass: TestCanvasPopManagerService as never }]);
+ injector.add([SheetsSelectionsService]);
+ injector.add([SheetsHyperLinkParserService]);
+ injector.add([SheetsHyperLinkResolverService]);
+ injector.add([ISheetsHyperLinkPopupService, { useClass: SheetsHyperLinkPopupService }]);
+ injector.add([SheetsHyperLinkSidePanelService]);
+
+ const workbook = univer.createUnit<IWorkbookData, Workbook>(UniverInstanceType.UNIVER_SHEET, createWorkbookData(customRange));
+ injector.get(IUniverInstanceService).focusUnit(UNIT_ID);
+ injector.get(LocaleService).load({
+ [LocaleType.EN_US]: {
+ 'sheets-hyper-link-ui': {
+ popup: {
+ open: 'Open link',
+ edit: 'Edit',
+ cancel: 'Remove link',
+ },
+ form: {
+ label: 'Display text',
+ labelPlaceholder: 'Text',
+ type: 'Link type',
+ link: 'Web link',
+ range: 'Range',
+ worksheet: 'Worksheet',
+ definedName: 'Defined name',
+ linkPlaceholder: 'URL',
+ inputError: 'Required',
+ linkError: 'Invalid link',
+ selectError: 'Select a target',
+ cancel: 'Cancel',
+ ok: 'OK',
+ },
+ message: {
+ coped: 'Copied',
+ },
+ },
+ 'sheets-hyper-link': {
+ message: {
+ refError: 'Invalid reference',
+ },
+ },
+ },
+ });
+ const commandService = injector.get(ICommandService);
+ commandService.registerCommand(SetRangeValuesMutation);
+ commandService.registerCommand(SetSelectionsOperation);
+ commandService.registerCommand(AddHyperLinkMutation);
+ commandService.registerCommand(UpdateHyperLinkMutation);
+ commandService.registerCommand(RemoveHyperLinkMutation);
+ commandService.registerCommand(AddHyperLinkCommand);
+ commandService.registerCommand(CancelHyperLinkCommand);
+ commandService.registerCommand(OpenHyperLinkEditPanelOperation);
+ commandService.registerCommand(CloseHyperLinkPopupOperation);
+ commandService.registerCommand(SetWorksheetActiveOperation);
+ commandService.registerCommand(ScrollToRangeOperation);
+
+ return {
+ univer,
+ injector,
+ commandService,
+ workbook,
+ customRange,
+ };
+}
+
+function inputText(input: HTMLInputElement, value: string) {
+ const valueSetter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')?.set;
+ valueSetter?.call(input, value);
+ input.dispatchEvent(new Event('input', { bubbles: true }));
+}
+
+async function selectOption(trigger: Element, optionText: string) {
+ trigger.dispatchEvent(new PointerEvent('pointerdown', { bubbles: true, button: 0 }));
+ trigger.dispatchEvent(new MouseEvent('click', { bubbles: true }));
+ await Promise.resolve();
+
+ const option = Array.from(document.querySelectorAll('button, [data-slot="dropdown-menu-radio-item"]')).find((item) => item.textContent === optionText);
+
+ if (!option) {
+ throw new Error(`Option ${optionText} was not rendered`);
+ }
+
+ option.dispatchEvent(new MouseEvent('click', { bubbles: true }));
+}
+
+export { createPopupTestBed, inputText, MERGED_RANGE, selectOption, SUB_UNIT_ID, TestRenderManagerService, UNIT_ID };
diff --git a/packages/sheets-numfmt-ui/src/menu/__tests__/menu.spec.ts b/packages/sheets-numfmt-ui/src/menu/__tests__/menu.spec.ts
new file mode 100644
index 0000000000..01e7ba4326
--- /dev/null
+++ b/packages/sheets-numfmt-ui/src/menu/__tests__/menu.spec.ts
@@ -0,0 +1,216 @@
+/**
+ * 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 { IRange, IWorkbookData, Workbook } from '@univerjs/core';
+import type { ISelectionWithStyle } from '@univerjs/sheets';
+import {
+ ICommandService,
+ IUniverInstanceService,
+ LocaleService,
+ LocaleType,
+ RedoCommand,
+ RegionService,
+ UndoCommand,
+ Univer,
+ UniverInstanceType,
+} from '@univerjs/core';
+import {
+ INumfmtService,
+ NumfmtService,
+ RemoveNumfmtMutation,
+ SetNumfmtMutation,
+ SetRangeValuesMutation,
+ SetWorksheetActiveOperation,
+ SheetsSelectionsService,
+} from '@univerjs/sheets';
+import { SetCurrencyCommand, SetNumfmtCommand, SetPercentCommand } from '@univerjs/sheets-numfmt';
+import { Subscription } from 'rxjs';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+import enUS from '../../locale/en-US';
+import zhCN from '../../locale/zh-CN';
+import { CurrencySymbolIconMenuItem, FactoryOtherMenuItem, PercentMenuItem } from '../menu';
+import { FactoryMobileOtherMenuItem } from '../mobile-menu';
+
+describe('number format menu state', () => {
+ let univer: Univer;
+ let workbook: Workbook;
+ let commands: ICommandService;
+ let selections: SheetsSelectionsService;
+ let localeService: LocaleService;
+ let subscriptions: Subscription;
+ let label: string;
+ let mobileLabel: string;
+ let currencyActive: boolean;
+ let percentActive: boolean;
+
+ function createSelection(row: number, column: number, range?: IRange): ISelectionWithStyle {
+ return {
+ range: range ?? { startRow: row, endRow: row, startColumn: column, endColumn: column },
+ primary: workbook.getActiveSheet().getCellInfoInMergeData(row, column),
+ style: null,
+ };
+ }
+
+ beforeEach(() => {
+ univer = new Univer();
+ const injector = univer.__getInjector();
+ injector.add([SheetsSelectionsService]);
+ injector.add([INumfmtService, { useClass: NumfmtService }]);
+ localeService = injector.get(LocaleService);
+ localeService.load({ [LocaleType.EN_US]: enUS, [LocaleType.ZH_CN]: zhCN });
+ localeService.setLocale(LocaleType.EN_US);
+ localeService.setDirection('ltr');
+ workbook = univer.createUnit<IWorkbookData, Workbook>(UniverInstanceType.UNIVER_SHEET, {
+ id: 'test',
+ appVersion: '3.0.0-alpha',
+ locale: LocaleType.EN_US,
+ name: '',
+ sheetOrder: ['sheet1', 'sheet2'],
+ styles: {
+ currency: { n: { pattern: '$#,##0.00' } },
+ percent: { n: { pattern: '0.000%' } },
+ },
+ sheets: {
+ sheet1: {
+ id: 'sheet1',
+ cellData: { 0: { 0: { v: 1 }, 1: { v: 100.11, s: 'currency' }, 2: { v: 1, s: 'percent' } } },
+ },
+ sheet2: { id: 'sheet2' },
+ },
+ });
+ injector.get(IUniverInstanceService).focusUnit('test');
+ selections = injector.get(SheetsSelectionsService);
+ commands = injector.get(ICommandService);
+ [
+ SetNumfmtMutation,
+ RemoveNumfmtMutation,
+ SetRangeValuesMutation,
+ SetNumfmtCommand,
+ SetCurrencyCommand,
+ SetPercentCommand,
+ SetWorksheetActiveOperation,
+ ].forEach((command) => commands.registerCommand(command));
+ subscriptions = new Subscription();
+ subscriptions.add(FactoryOtherMenuItem(injector).value$!.subscribe((value) => {
+ label = value;
+ }));
+ subscriptions.add(FactoryMobileOtherMenuItem(injector).value$!.subscribe((value) => {
+ mobileLabel = value;
+ }));
+ subscriptions.add(CurrencySymbolIconMenuItem(injector).activated$!.subscribe((value) => {
+ currencyActive = value;
+ }));
+ subscriptions.add(PercentMenuItem(injector).activated$!.subscribe((value) => {
+ percentActive = value;
+ }));
+ });
+
+ afterEach(() => {
+ subscriptions.unsubscribe();
+ univer.dispose();
+ });
+
+ it('uses the focus cell within a range and the last of multiple selections', () => {
+ const range = { startRow: 0, endRow: 0, startColumn: 0, endColumn: 2 };
+ selections.setSelections([createSelection(0, 1, range)]);
+ expect([label, mobileLabel, currencyActive, percentActive]).toEqual(['Currency', 'Currency', true, false]);
+
+ selections.setSelections([createSelection(0, 2, range)]);
+ expect([label, mobileLabel, currencyActive, percentActive]).toEqual(['Percentage', 'Percentage', false, true]);
+
+ selections.setSelections([createSelection(0, 1), createSelection(0, 0)]);
+ expect([label, mobileLabel, currencyActive, percentActive]).toEqual(['General', 'General', false, false]);
+ selections.setSelections([{ range: createSelection(0, 1).range, primary: null }]);
+ expect([label, currencyActive, percentActive]).toEqual(['Currency', true, false]);
+ selections.setSelections([]);
+ expect([currencyActive, percentActive]).toEqual([false, false]);
+ });
+
+ it('updates classification and active buttons immediately after locale changes', () => {
+ selections.setSelections([createSelection(0, 1)]);
+ expect(label).toBe('Currency');
+ localeService.setLocale(LocaleType.ZH_CN);
+ expect([label, mobileLabel]).toEqual(['货币', '货币']);
+ expect([currencyActive, percentActive]).toEqual([false, false]);
+ localeService.setLocale(LocaleType.EN_US);
+ expect([label, mobileLabel]).toEqual(['Currency', 'Currency']);
+ expect(currencyActive).toBe(true);
+ });
+
+ it.each([
+ { region: LocaleType.ZH_CN, symbol: '¥', otherRegion: LocaleType.EN_US },
+ { region: LocaleType.EN_US, symbol: '$', otherRegion: LocaleType.ZH_CN },
+ { region: LocaleType.FR_FR, symbol: '€', otherRegion: LocaleType.EN_US },
+ { region: LocaleType.ZH_TW, symbol: 'NT$', otherRegion: LocaleType.EN_US },
+ { region: LocaleType.ZH_HK, symbol: 'HK$', otherRegion: LocaleType.EN_US },
+ { region: LocaleType.PT_BR, symbol: 'R$', otherRegion: LocaleType.EN_US },
+ ])('activates only the matching currency symbol $symbol in $region', async ({ region, symbol, otherRegion }) => {
+ const regionService = univer.__getInjector().get(RegionService);
+ regionService.setRegion(region);
+ selections.setSelections([createSelection(0, 0)]);
+
+ expect(await commands.executeCommand(SetNumfmtCommand.id, {
+ values: [{ row: 0, col: 0, pattern: `"${symbol}"#,##0.000` }],
+ })).toBe(true);
+ expect(currencyActive).toBe(true);
+ regionService.setRegion(otherRegion);
+ expect(currencyActive).toBe(false);
+ expect([label, mobileLabel]).toEqual(['Currency', 'Currency']);
+ regionService.setRegion(region);
+ expect(currencyActive).toBe(true);
+
+ expect(await commands.executeCommand(SetPercentCommand.id)).toBe(true);
+ expect([currencyActive, percentActive]).toEqual([false, true]);
+ });
+
+ it('uses the same explicit region as the currency icon when the UI language changes', () => {
+ univer.__getInjector().get(RegionService).setRegion(LocaleType.EN_US);
+ selections.setSelections([createSelection(0, 1)]);
+ localeService.setLocale(LocaleType.ZH_CN);
+ expect([label, currencyActive]).toEqual(['货币', true]);
+ });
+
+ it('tracks shortcut commands, undo, redo and clearing the format without moving focus', async () => {
+ selections.setSelections([createSelection(0, 0)]);
+ expect(await commands.executeCommand(SetPercentCommand.id)).toBe(true);
+ expect([label, currencyActive, percentActive]).toEqual(['Percentage', false, true]);
+ expect(await commands.executeCommand(SetCurrencyCommand.id)).toBe(true);
+ expect([label, currencyActive, percentActive]).toEqual(['Currency', true, false]);
+ expect(await commands.executeCommand(UndoCommand.id)).toBe(true);
+ expect([label, currencyActive, percentActive]).toEqual(['Percentage', false, true]);
+ expect(await commands.executeCommand(RedoCommand.id)).toBe(true);
+ expect([label, currencyActive, percentActive]).toEqual(['Currency', true, false]);
+ expect(await commands.executeCommand(SetNumfmtCommand.id, { values: [{ row: 0, col: 0 }] })).toBe(true);
+ expect([label, mobileLabel, currencyActive, percentActive]).toEqual(['General', 'General', false, false]);
+ });
+
+ it('clears and restores active state when switching sheets or disposing the workbook', () => {
+ selections.setSelections([createSelection(0, 1)]);
+ selections.setSelections('test', 'sheet2', [createSelection(0, 1)]);
+ expect(commands.syncExecuteCommand(SetWorksheetActiveOperation.id, {
+ unitId: 'test',
+ subUnitId: 'sheet2',
+ })).toBe(true);
+ expect([label, currencyActive, percentActive]).toEqual(['General', false, false]);
+ expect(commands.syncExecuteCommand(SetWorksheetActiveOperation.id, {
+ unitId: 'test',
+ subUnitId: 'sheet1',
+ })).toBe(true);
+ expect([label, currencyActive, percentActive]).toEqual(['Currency', true, false]);
+ univer.__getInjector().get(IUniverInstanceService).disposeUnit('test');
+ expect([currencyActive, percentActive]).toEqual([false, false]);
+ });
+});
diff --git a/packages/sheets-numfmt-ui/src/menu/__tests__/numfmt-menu-util.spec.ts b/packages/sheets-numfmt-ui/src/menu/__tests__/numfmt-menu-util.spec.ts
new file mode 100644
index 0000000000..93cfb403b2
--- /dev/null
+++ b/packages/sheets-numfmt-ui/src/menu/__tests__/numfmt-menu-util.spec.ts
@@ -0,0 +1,39 @@
+/**
+ * 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 { getNumfmtParseValueFilter } from '@univerjs/core';
+import { describe, expect, it } from 'vitest';
+import { getNumberFormatLabelKey } from '../numfmt-menu-util';
+
+describe('getNumberFormatLabelKey', () => {
+ it.each(['en', 'zh-CN'])('classifies typed dollar amounts as currency in %s', (locale) => {
+ const parsed = getNumfmtParseValueFilter('$100.11', { locale });
+ expect(parsed?.v).toBe(100.11);
+ expect(getNumberFormatLabelKey(parsed?.z, '$')).toBe('sheets-numfmt-ui.currency');
+ expect(getNumberFormatLabelKey(parsed?.z, '¥')).toBe('sheets-numfmt-ui.currency');
+ });
+
+ it('preserves specific presets while recognizing other patterns by type', () => {
+ expect(getNumberFormatLabelKey('"$" #,##0.00_);[Red]("$"#,##0.00)', '$')).toBe('sheets-numfmt-ui.accounting');
+ expect(getNumberFormatLabelKey('"$"#,##0;[Red]"$"#,##0', '$')).toBe('sheets-numfmt-ui.roundingCurrency');
+ expect(getNumberFormatLabelKey('[h]:mm:ss', '$')).toBe('sheets-numfmt-ui.timeDuration');
+ expect(getNumberFormatLabelKey('"€"#,##0.000', '$')).toBe('sheets-numfmt-ui.currency');
+ expect(getNumberFormatLabelKey('0.000%;[Red]-0.000%', '$')).toBe('sheets-numfmt-ui.percent');
+ expect(getNumberFormatLabelKey('dd/mm/yyyy', '$')).toBe('sheets-numfmt-ui.date');
+ expect(getNumberFormatLabelKey('#,##0.000', '$')).toBe('sheets-numfmt-ui.number');
+ expect(getNumberFormatLabelKey('# ?/?', '$')).toBe('sheets-numfmt-ui.moreFmt');
+ });
+});
diff --git a/packages/sheets-numfmt-ui/src/menu/menu.ts b/packages/sheets-numfmt-ui/src/menu/menu.ts
index 2bcbba2108..3422c023fb 100644
--- a/packages/sheets-numfmt-ui/src/menu/menu.ts
+++ b/packages/sheets-numfmt-ui/src/menu/menu.ts
@@ -18,20 +18,12 @@ import type { IAccessor } from '@univerjs/core';
import type { IMenuButtonItem, IMenuSelectorItem } from '@univerjs/ui';
import type { LocaleKey } from '../locale/types';
import {
- fromCallback,
- ICommandService,
- isDefaultFormat,
- isPatternEqualWithoutDecimal,
- IUniverInstanceService,
LocaleService,
RegionService,
UniverInstanceType,
} from '@univerjs/core';
import {
RangeProtectionPermissionEditPoint,
- RemoveNumfmtMutation,
- SetNumfmtMutation,
- SheetsSelectionsService,
WorkbookEditablePermission,
WorksheetEditPermission,
WorksheetSetCellStylePermission,
@@ -40,16 +32,18 @@ import {
AddDecimalCommand,
getCurrencySymbolByLocale,
getCurrencySymbolIconByLocale,
+ getCurrencyType,
+ getPatternType,
SetCurrencyCommand,
SetPercentCommand,
SubtractDecimalCommand,
} from '@univerjs/sheets-numfmt';
-import { deriveStateFromActiveSheet$, getCurrentRangeDisable$ } from '@univerjs/sheets-ui';
+import { getCurrentRangeDisable$ } from '@univerjs/sheets-ui';
import { getMenuHiddenObservable, MenuItemType } from '@univerjs/ui';
-import { filter, map, merge, Observable } from 'rxjs';
+import { combineLatest, distinctUntilChanged, map } from 'rxjs';
import { OpenNumfmtPanelOperator } from '../commands/operations/open.numfmt.panel.operation';
import { MORE_NUMFMT_TYPE_KEY, OPTIONS_KEY } from '../views/components/MoreNumfmtType';
-import { MENU_OPTIONS } from './number-format-options';
+import { getCurrentNumfmtPattern$, getNumberFormatLabelKey } from './numfmt-menu-util';
export function CurrencySymbolIconMenuItem(accessor: IAccessor): IMenuButtonItem<LocaleKey> {
const regionService = accessor.get(RegionService);
@@ -60,6 +54,12 @@ export function CurrencySymbolIconMenuItem(accessor: IAccessor): IMenuButtonItem
title: 'sheets-numfmt-ui.currency',
tooltip: 'sheets-numfmt-ui.currency',
type: MenuItemType.BUTTON,
+ activated$: combineLatest([getCurrentNumfmtPattern$(accessor), regionService.currentRegion$]).pipe(
+ map(([pattern, region]) => !!pattern
+ && getPatternType(pattern) === 'currency'
+ && getCurrencyType(pattern) === getCurrencySymbolIconByLocale(region).symbol),
+ distinctUntilChanged()
+ ),
hidden$: getMenuHiddenObservable(accessor, UniverInstanceType.UNIVER_SHEET),
disabled$: getCurrentRangeDisable$(accessor, {
workbookTypes: [WorkbookEditablePermission],
@@ -108,67 +108,29 @@ export function PercentMenuItem(accessor: IAccessor): IMenuButtonItem<LocaleKey>
title: 'sheets-numfmt-ui.percent',
tooltip: 'sheets-numfmt-ui.percent',
type: MenuItemType.BUTTON,
+ activated$: getCurrentNumfmtPattern$(accessor).pipe(
+ map((pattern) => !!pattern && getPatternType(pattern) === 'percent'),
+ distinctUntilChanged()
+ ),
hidden$: getMenuHiddenObservable(accessor, UniverInstanceType.UNIVER_SHEET),
disabled$: getCurrentRangeDisable$(accessor, {
workbookTypes: [WorkbookEditablePermission],
worksheetTypes: [WorksheetEditPermission, WorksheetSetCellStylePermission],
rangeTypes: [RangeProtectionPermissionEditPoint],
}),
-
};
};
export function FactoryOtherMenuItem(accessor: IAccessor): IMenuSelectorItem<LocaleKey, string> {
- const univerInstanceService = accessor.get(IUniverInstanceService);
- const commandService = accessor.get(ICommandService);
const localeService = accessor.get(LocaleService);
const regionService = accessor.get(RegionService);
-
- const selectionManagerService = accessor.get(SheetsSelectionsService);
- const commandList = [RemoveNumfmtMutation.id, SetNumfmtMutation.id];
- const value$ = deriveStateFromActiveSheet$(
- univerInstanceService,
- '',
- ({ workbook, worksheet }) => new Observable((subscribe) =>
- merge(
- selectionManagerService.selectionMoveEnd$,
- regionService.currentRegion$,
- fromCallback(commandService.onCommandExecuted.bind(commandService)).pipe(
- filter(([commandInfo]) => commandList.includes(commandInfo.id))
- )
- ).subscribe(() => {
- const selections = selectionManagerService.getCurrentSelections();
- if (selections && selections[0]) {
- const range = selections[0].range;
- const row = range.startRow;
- const col = range.startColumn;
- const numfmtValue = workbook.getStyles().get(worksheet.getCell(row, col)?.s)?.n;
- const pattern = numfmtValue?.pattern;
- const currencySymbol = getCurrencySymbolByLocale(regionService.getCurrentRegion());
-
- // Adapts the 'General' obtained during import, or the 'General' set manually
- let value: string = localeService.t<LocaleKey>('sheets-numfmt-ui.general');
-
- if (isDefaultFormat(pattern)) {
- subscribe.next(value);
- return;
- }
-
- if (pattern) {
- const item = MENU_OPTIONS(currencySymbol).filter((item) => typeof item === 'object' && item.pattern).find(
- (item) => isPatternEqualWithoutDecimal(pattern, (item as { pattern: string }).pattern)
- );
- if (item && typeof item === 'object' && item.pattern) {
- value = localeService.t<LocaleKey>(item.label);
- } else {
- value = localeService.t<LocaleKey>('sheets-numfmt-ui.moreFmt');
- }
- }
-
- subscribe.next(value);
- }
- })
- )
+ const value$ = combineLatest([
+ getCurrentNumfmtPattern$(accessor),
+ regionService.currentRegion$,
+ localeService.currentLocale$,
+ ]).pipe(
+ map(([pattern, region]) => localeService.t<LocaleKey>(getNumberFormatLabelKey(pattern, getCurrencySymbolByLocale(region)))),
+ distinctUntilChanged()
);
return {
diff --git a/packages/sheets-numfmt-ui/src/menu/mobile-menu.ts b/packages/sheets-numfmt-ui/src/menu/mobile-menu.ts
index b5a77bfa74..4c76627336 100644
--- a/packages/sheets-numfmt-ui/src/menu/mobile-menu.ts
+++ b/packages/sheets-numfmt-ui/src/menu/mobile-menu.ts
@@ -19,20 +19,12 @@ import type { IMenuSelectorItem } from '@univerjs/ui';
import type { LocaleKey } from '../locale/types';
import {
DEFAULT_TEXT_FORMAT_EXCEL,
- fromCallback,
- ICommandService,
- isDefaultFormat,
- isPatternEqualWithoutDecimal,
- IUniverInstanceService,
LocaleService,
RegionService,
UniverInstanceType,
} from '@univerjs/core';
import {
RangeProtectionPermissionEditPoint,
- RemoveNumfmtMutation,
- SetNumfmtMutation,
- SheetsSelectionsService,
WorkbookEditablePermission,
WorksheetEditPermission,
WorksheetSetCellStylePermission,
@@ -46,11 +38,12 @@ import {
SetPercentCommand,
SubtractDecimalCommand,
} from '@univerjs/sheets-numfmt';
-import { deriveStateFromActiveSheet$, getCurrentRangeDisable$ } from '@univerjs/sheets-ui';
+import { getCurrentRangeDisable$ } from '@univerjs/sheets-ui';
import { getMenuHiddenObservable, MenuItemType } from '@univerjs/ui';
-import { filter, merge, Observable } from 'rxjs';
+import { combineLatest, distinctUntilChanged, map } from 'rxjs';
import { SetMobileNumfmtCommand } from '../commands/commands/set-mobile-numfmt.command';
import { MENU_OPTIONS } from './number-format-options';
+import { getCurrentNumfmtPattern$, getNumberFormatLabelKey } from './numfmt-menu-util';
export const MOBILE_NUMFMT_MENU_ID = 'sheet.menu.mobile.numfmt';
export const MOBILE_CUSTOM_NUMFMT_COMPONENT = 'sheets-numfmt-ui.mobile.custom-format';
@@ -120,54 +113,15 @@ export function createMobileNumberFormatMenuConfig(currencySymbol: string): IMob
export function FactoryMobileOtherMenuItem(
accessor: IAccessor
): IMenuSelectorItem<LocaleKey, string> & { mobileNumberFormat: IMobileNumberFormatMenuConfig } {
- const univerInstanceService = accessor.get(IUniverInstanceService);
- const commandService = accessor.get(ICommandService);
const localeService = accessor.get(LocaleService);
const regionService = accessor.get(RegionService);
- const selectionManagerService = accessor.get(SheetsSelectionsService);
- const commandList = [RemoveNumfmtMutation.id, SetNumfmtMutation.id];
- const value$ = deriveStateFromActiveSheet$(
- univerInstanceService,
- '',
- ({ workbook, worksheet }) => new Observable((subscribe) =>
- merge(
- selectionManagerService.selectionMoveEnd$,
- regionService.currentRegion$,
- fromCallback(commandService.onCommandExecuted.bind(commandService)).pipe(
- filter(([commandInfo]) => commandList.includes(commandInfo.id))
- )
- ).subscribe(() => {
- const selection = selectionManagerService.getCurrentSelections()?.[0];
- if (!selection) {
- return;
- }
-
- const { startRow, startColumn } = selection.range;
- const numfmtValue = workbook.getStyles().get(worksheet.getCell(startRow, startColumn)?.s)?.n;
- const pattern = numfmtValue?.pattern;
- const currencySymbol = getCurrencySymbolByLocale(regionService.getCurrentRegion());
- let value = localeService.t<LocaleKey>('sheets-numfmt-ui.general');
-
- if (isDefaultFormat(pattern)) {
- subscribe.next(value);
- return;
- }
-
- if (pattern) {
- const item = MENU_OPTIONS(currencySymbol)
- .filter((option) => typeof option === 'object' && option.pattern)
- .find((option) => isPatternEqualWithoutDecimal(
- pattern,
- (option as { pattern: string }).pattern
- ));
- value = item && typeof item === 'object' && item.pattern
- ? localeService.t<LocaleKey>(item.label)
- : localeService.t<LocaleKey>('sheets-numfmt-ui.moreFmt');
- }
-
- subscribe.next(value);
- })
- )
+ const value$ = combineLatest([
+ getCurrentNumfmtPattern$(accessor),
+ regionService.currentRegion$,
+ localeService.currentLocale$,
+ ]).pipe(
+ map(([pattern, region]) => localeService.t<LocaleKey>(getNumberFormatLabelKey(pattern, getCurrencySymbolByLocale(region)))),
+ distinctUntilChanged()
);
return {
diff --git a/packages/sheets-numfmt-ui/src/menu/numfmt-menu-util.ts b/packages/sheets-numfmt-ui/src/menu/numfmt-menu-util.ts
new file mode 100644
index 0000000000..04099d0f97
--- /dev/null
+++ b/packages/sheets-numfmt-ui/src/menu/numfmt-menu-util.ts
@@ -0,0 +1,87 @@
+/**
+ * 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 { FormatType } from '@univerjs/sheets';
+import type { Observable } from 'rxjs';
+import type { LocaleKey } from '../locale/types';
+import {
+ fromCallback,
+ ICommandService,
+ isDefaultFormat,
+ isPatternEqualWithoutDecimal,
+ isTextFormat,
+ IUniverInstanceService,
+} from '@univerjs/core';
+import { RemoveNumfmtMutation, SetNumfmtMutation, SetRangeValuesMutation, SheetsSelectionsService } from '@univerjs/sheets';
+import { getPatternType } from '@univerjs/sheets-numfmt';
+import { deriveStateFromActiveSheet$ } from '@univerjs/sheets-ui';
+import { distinctUntilChanged, filter, map, merge, startWith } from 'rxjs';
+import { MENU_OPTIONS } from './number-format-options';
+
+const FORMAT_TYPE_LABELS: Partial<Record<FormatType, LocaleKey>> = {
+ currency: 'sheets-numfmt-ui.currency',
+ date: 'sheets-numfmt-ui.date',
+ datetime: 'sheets-numfmt-ui.dateTime',
+ general: 'sheets-numfmt-ui.general',
+ grouped: 'sheets-numfmt-ui.number',
+ number: 'sheets-numfmt-ui.number',
+ percent: 'sheets-numfmt-ui.percent',
+ scientific: 'sheets-numfmt-ui.scientific',
+ text: 'sheets-numfmt-ui.text',
+ time: 'sheets-numfmt-ui.time',
+};
+
+export function getNumberFormatLabelKey(pattern: string | undefined, currencySymbol: string): LocaleKey {
+ if (!pattern || isDefaultFormat(pattern)) {
+ return 'sheets-numfmt-ui.general';
+ }
+ if (isTextFormat(pattern)) {
+ return 'sheets-numfmt-ui.text';
+ }
+
+ const preset = MENU_OPTIONS(currencySymbol).find((option) =>
+ typeof option === 'object' && option.pattern && isPatternEqualWithoutDecimal(pattern, option.pattern));
+ if (preset && typeof preset === 'object') {
+ return preset.label;
+ }
+
+ return FORMAT_TYPE_LABELS[getPatternType(pattern)] ?? 'sheets-numfmt-ui.moreFmt';
+}
+
+export function getCurrentNumfmtPattern$(accessor: IAccessor): Observable<string | undefined> {
+ const commandService = accessor.get(ICommandService);
+ const instanceService = accessor.get(IUniverInstanceService);
+ const selectionService = accessor.get(SheetsSelectionsService);
+ const commandIds = [RemoveNumfmtMutation.id, SetNumfmtMutation.id, SetRangeValuesMutation.id];
+
+ return deriveStateFromActiveSheet$<string | undefined>(instanceService, undefined, ({ worksheet }) => merge(
+ selectionService.selectionChanged$,
+ fromCallback(commandService.onCommandExecuted.bind(commandService)).pipe(
+ filter(([command]) => commandIds.includes(command.id))
+ )
+ ).pipe(
+ startWith(null),
+ map(() => {
+ const selection = selectionService.getCurrentLastSelection();
+ if (!selection) {
+ return undefined;
+ }
+ const cell = selection.primary ?? selection.range;
+ return worksheet.getCellStyle(cell.startRow, cell.startColumn)?.n?.pattern;
+ })
+ )).pipe(distinctUntilChanged());
+}
diff --git a/packages/sheets-table-ui/src/controllers/sheet-table-controls-render.controller.ts b/packages/sheets-table-ui/src/controllers/sheet-table-controls-render.controller.ts
index 71874e300c..f44057e3cc 100644
--- a/packages/sheets-table-ui/src/controllers/sheet-table-controls-render.controller.ts
+++ b/packages/sheets-table-ui/src/controllers/sheet-table-controls-render.controller.ts
@@ -37,7 +37,7 @@ import {
LocaleService,
toDisposable,
} from '@univerjs/core';
-import { CURSOR_TYPE } from '@univerjs/engine-render';
+import { CURSOR_TYPE, Vector2 } from '@univerjs/engine-render';
import {
SelectRangeCommand,
SheetRangeThemeModel,
@@ -54,7 +54,6 @@ import {
} from '@univerjs/sheets-table';
import {
ExpandSelectionCommand,
- getTransformCoord,
ISheetSelectionRenderService,
MoveSelectionCommand,
MoveSelectionEnterAndTabCommand,
@@ -619,14 +618,9 @@ export class SheetTableControlsRenderController extends Disposable implements IR
}
private _getLocalPoint(evt: IPointerEvent | IMouseEvent): { x: number; y: number } {
- const skeleton = this._sheetSkeletonManagerService.getCurrentSkeleton();
- if (skeleton) {
- return getTransformCoord(evt.offsetX, evt.offsetY, this._context.scene, skeleton);
- }
-
- return {
- x: evt.offsetX,
- y: evt.offsetY,
- };
+ const { scene } = this._context;
+ const point = new Vector2(evt.offsetX, evt.offsetY);
+ const viewport = scene.getActiveViewportByCoord(point) ?? scene.getDefaultViewport();
+ return viewport?.transformVector2SceneCoord(point) ?? point;
}
}
diff --git a/packages/sheets-table-ui/src/services/__tests__/sheets-table-ui.service.spec.ts b/packages/sheets-table-ui/src/services/__tests__/sheets-table-ui.service.spec.ts
index 5234af4a62..2dc88a7d7a 100644
--- a/packages/sheets-table-ui/src/services/__tests__/sheets-table-ui.service.spec.ts
+++ b/packages/sheets-table-ui/src/services/__tests__/sheets-table-ui.service.spec.ts
@@ -15,7 +15,7 @@
*/
import type { Dependency, IWorkbookData, Workbook } from '@univerjs/core';
-import type { ITableRecordFilterItem } from '@univerjs/sheets-table';
+import type { ITableManualFilterItem, ITableRecordFilterItem } from '@univerjs/sheets-table';
import {
FilterSelectionMode,
ICommandService,
@@ -255,11 +255,59 @@ describe('SheetsTableUiService', () => {
expect(items.allItemsCount).toBe(2);
expect(items.data).toEqual([
- { title: 12, key: '1_1', leaf: true },
- { title: 8, key: '1_3', leaf: true },
+ { title: '12', key: '1_1', leaf: true },
+ { title: '8', key: '1_3', leaf: true },
]);
- expect(items.itemsCountMap.get(12 as unknown as string)).toBe(1);
- expect(items.itemsCountMap.get(8 as unknown as string)).toBe(1);
+ expect(items.itemsCountMap.get('12')).toBe(1);
+ expect(items.itemsCountMap.get('8')).toBe(1);
+ });
+
+ it('filters numeric candidates using the same keys as the list and restores them through undo and redo', async () => {
+ testBed = createTestBed();
+ const service = testBed.get(SheetsTableUiService);
+ const unitId = testBed.workbook.getUnitId();
+ testBed.get(IUniverInstanceService).focusUnit(unitId);
+ const sheet = testBed.workbook.getSheetBySheetId('sheet1')!;
+ const commands = testBed.get(ICommandService);
+ await service.setTableFilter(unitId, 'table-orders', 0, undefined);
+ const items = service.getTableFilterItems(unitId, 'sheet1', 'table-orders', 1);
+ expect(items.data.map((item) => item.title)).toEqual(['12', '8']);
+ expect(items.itemsCountMap.get('12')).toBe(2);
+ expect(service.createItemFilter(unitId, 'table-orders', 1, items, new Set(['12', '8']), false))
+ .toBeUndefined();
+
+ const filter = service.createItemFilter(unitId, 'table-orders', 1, items, new Set(['12']), false);
+ expect(filter).toEqual({ filterType: TableColumnFilterTypeEnum.manual, values: ['12'] });
+ expect(await service.setTableFilter(unitId, 'table-orders', 1, filter)).toBe(true);
+ const table = testBed.get(TableManager).getTable(unitId, 'table-orders')!;
+ const filteredRows = () => [...table.getTableFilters().doFilter(sheet, table.getTableFilterRange())];
+ expect(filteredRows()).toEqual([3]);
+ expect(service.getTableFilterCheckedItems(unitId, 'table-orders', 1)).toEqual(['12']);
+
+ expect(await commands.executeCommand(UndoCommand.id)).toBe(true);
+ expect(filteredRows()).toEqual([]);
+ expect(await commands.executeCommand(RedoCommand.id)).toBe(true);
+ expect(filteredRows()).toEqual([3]);
+ });
+
+ it('reopens numeric manual filters saved before value keys were normalized', async () => {
+ testBed = createTestBed();
+ const service = testBed.get(SheetsTableUiService);
+ const unitId = testBed.workbook.getUnitId();
+ await service.setTableFilter(unitId, 'table-orders', 0, undefined);
+ const table = testBed.get(TableManager).getTable(unitId, 'table-orders')!;
+ table.getTableFilters().fromJSON({
+ tableColumnFilterList: [undefined, {
+ filterType: TableColumnFilterTypeEnum.manual,
+ values: [12],
+ } as unknown as ITableManualFilterItem],
+ });
+
+ expect(service.getTableFilterCheckedItems(unitId, 'table-orders', 1)).toEqual(['12']);
+ expect([...table.getTableFilters().doFilter(
+ testBed.workbook.getSheetBySheetId('sheet1')!,
+ table.getTableFilterRange()
+ )]).toEqual([3]);
});
it('refreshes cached candidates when table data changes inside the filter range', async () => {
@@ -268,8 +316,8 @@ describe('SheetsTableUiService', () => {
const commandService = testBed.get(ICommandService);
expect(service.getTableFilterItems(testBed.workbook.getUnitId(), 'sheet1', 'table-orders', 1).data).toEqual([
- { title: 12, key: '1_1', leaf: true },
- { title: 8, key: '1_3', leaf: true },
+ { title: '12', key: '1_1', leaf: true },
+ { title: '8', key: '1_3', leaf: true },
]);
await commandService.executeCommand(SetRangeValuesMutation.id, {
@@ -283,8 +331,8 @@ describe('SheetsTableUiService', () => {
});
expect(service.getTableFilterItems(testBed.workbook.getUnitId(), 'sheet1', 'table-orders', 1).data).toEqual([
- { title: 15, key: '1_1', leaf: true },
- { title: 8, key: '1_3', leaf: true },
+ { title: '15', key: '1_1', leaf: true },
+ { title: '8', key: '1_3', leaf: true },
]);
});
@@ -397,8 +445,8 @@ describe('SheetsTableUiService', () => {
'table-orders'
);
- expect(service.getTableFilterItems(testBed.workbook.getUnitId(), 'sheet1', 'table-orders', 1).data[0].title).toBe(12);
- expect(service.getTableFilterItems(secondWorkbook.getUnitId(), 'sheet1', 'table-orders', 1).data[0].title).toBe(99);
+ expect(service.getTableFilterItems(testBed.workbook.getUnitId(), 'sheet1', 'table-orders', 1).data[0].title).toBe('12');
+ expect(service.getTableFilterItems(secondWorkbook.getUnitId(), 'sheet1', 'table-orders', 1).data[0].title).toBe('99');
});
it('keeps the legacy behavior of clearing a manual whitelist when every current candidate is selected', () => {
diff --git a/packages/sheets-table-ui/src/services/sheets-table-ui.service.ts b/packages/sheets-table-ui/src/services/sheets-table-ui.service.ts
index 6f2743e1c3..cf8700325d 100644
--- a/packages/sheets-table-ui/src/services/sheets-table-ui.service.ts
+++ b/packages/sheets-table-ui/src/services/sheets-table-ui.service.ts
@@ -147,7 +147,9 @@ export class SheetsTableUiService extends Disposable {
if (table) {
const filter = table.getTableFilterColumn(columnIndex);
if (isManualTableFilter(filter)) {
- checkedItems.push(...filter.values.map((value) => value === TABLE_FILTER_EMPTY_VALUE ? this._localeService.t<LocaleKey>('sheets-table-ui.condition.empty') : value));
+ checkedItems.push(...filter.values.map((value) => value === TABLE_FILTER_EMPTY_VALUE
+ ? this._localeService.t<LocaleKey>('sheets-table-ui.condition.empty')
+ : String(value)));
} else if (isRecordTableFilter(filter)) {
const accepts = compileTableRecordFilter(filter);
const items = this.getTableFilterItems(unitId, table.getSubunitId(), tableId, columnIndex);
@@ -318,14 +320,10 @@ export class SheetsTableUiService extends Disposable {
if (filteredRowsByOtherColumns.has(row)) {
continue;
}
- let stringItem = this._sheetTableService.getCellValueWithConditionType(worksheet, row, column) as string;
-
- if (stringItem == null) {
- stringItem = this._localeService.t<LocaleKey>('sheets-table-ui.condition.empty');
- }
- if (useRecordValues && typeof stringItem !== 'string') {
- stringItem = String(stringItem);
- }
+ const cellValue = this._sheetTableService.getCellValueWithConditionType(worksheet, row, column);
+ const stringItem = cellValue == null
+ ? this._localeService.t<LocaleKey>('sheets-table-ui.condition.empty')
+ : String(cellValue);
const recordValue = useRecordValues ? getTableRecordValue(worksheet, row, column) : undefined;
const valueKey = recordValue ? getTableRecordValueKey(recordValue) : undefined;
diff --git a/packages/sheets-table-ui/src/views/widgets/table-filter-button.shape.ts b/packages/sheets-table-ui/src/views/widgets/table-filter-button.shape.ts
index 1ec2aa2776..80474f346d 100644
--- a/packages/sheets-table-ui/src/views/widgets/table-filter-button.shape.ts
+++ b/packages/sheets-table-ui/src/views/widgets/table-filter-button.shape.ts
@@ -15,11 +15,12 @@
*/
import type { IMouseEvent, IPointerEvent, IShapeProps, UniverRenderingContext2D } from '@univerjs/engine-render';
-import type { SheetsTableButtonStateEnum } from '@univerjs/sheets-table';
import type { IOpenTableFilterPanelOperationParams } from '../../commands/operations/open-table-filter-dialog.opration';
import { ICommandService } from '@univerjs/core';
import { Shape } from '@univerjs/engine-render';
+import { SheetsTableButtonStateEnum } from '@univerjs/sheets-table';
import { OpenTableFilterPanelOperation } from '../../commands/operations/open-table-filter-dialog.opration';
+import { filterPartial } from './icons';
export const FILTER_ICON_SIZE = 16;
export const FILTER_ICON_PADDING = 1;
@@ -47,6 +48,7 @@ export class SheetsTableFilterButtonShape extends Shape<ISheetsTableFilterButton
private _hoverIconColor = '#202124';
private _hovered = false;
+ private _filteredIconPath: Path2D | null = null;
constructor(
key: string,
@@ -119,7 +121,18 @@ export class SheetsTableFilterButtonShape extends Shape<ISheetsTableFilterButton
ctx.restore();
}
- this._drawChevron(ctx, this._hovered ? this._hoverIconColor : this._iconColor);
+ const iconColor = this._hovered ? this._hoverIconColor : this._iconColor;
+ const buttonState = this._filterParams?.buttonState;
+ const hasFilter = buttonState === SheetsTableButtonStateEnum.FilteredSortNone
+ || buttonState === SheetsTableButtonStateEnum.FilteredSortAsc
+ || buttonState === SheetsTableButtonStateEnum.FilteredSortDesc;
+ if (hasFilter) {
+ this._filteredIconPath ??= new Path2D(filterPartial[0]);
+ ctx.fillStyle = iconColor;
+ ctx.fill(this._filteredIconPath);
+ } else {
+ this._drawChevron(ctx, iconColor);
+ }
ctx.restore();
}
diff --git a/packages/sheets-table/src/commands/commands/__tests__/table-commands.spec.ts b/packages/sheets-table/src/commands/commands/__tests__/table-commands.spec.ts
index a339e763e8..4163090a14 100644
--- a/packages/sheets-table/src/commands/commands/__tests__/table-commands.spec.ts
+++ b/packages/sheets-table/src/commands/commands/__tests__/table-commands.spec.ts
@@ -117,6 +117,7 @@ describe('sheets-table commands', () => {
name: 'Table1',
range: { startRow: 1, endRow: 5, startColumn: 2, endColumn: 4 },
options: { headerRow: true },
+ filters: {},
};
const tableManager = {
getTable: vi.fn(() => ({ toJSON: () => tableSnapshot })),
diff --git a/packages/sheets-table/src/commands/commands/delete-sheet-table.command.ts b/packages/sheets-table/src/commands/commands/delete-sheet-table.command.ts
index 1f84c3d261..de5478b237 100644
--- a/packages/sheets-table/src/commands/commands/delete-sheet-table.command.ts
+++ b/packages/sheets-table/src/commands/commands/delete-sheet-table.command.ts
@@ -21,6 +21,7 @@ import { SheetInterceptorService } from '@univerjs/sheets';
import { TableManager } from '../../models/table-manager';
import { AddSheetTableMutation } from '../mutations/add-sheet-table.mutation';
import { DeleteSheetTableMutation } from '../mutations/delete-sheet-table.mutation';
+import { SetSheetTableFilterMutation } from '../mutations/set-table-filter.mutation';
export const DeleteSheetTableCommand: ICommand<IDeleteSheetTableParams> = {
id: 'sheet.command.delete-table',
@@ -69,6 +70,19 @@ export const DeleteSheetTableCommand: ICommand<IDeleteSheetTableParams> = {
options: tableConfig.options,
},
});
+ tableConfig.filters.tableColumnFilterList?.forEach((tableFilter, column) => {
+ if (tableFilter) {
+ undos.push({
+ id: SetSheetTableFilterMutation.id,
+ params: {
+ unitId: params.unitId,
+ tableId: params.tableId,
+ column,
+ tableFilter,
+ },
+ });
+ }
+ });
undos.push(...interceptorCommands.undos);
const res = sequenceExecute(redos, commandService);
diff --git a/packages/sheets-table/src/controllers/__tests__/table-filter.controller.spec.ts b/packages/sheets-table/src/controllers/__tests__/table-filter.controller.spec.ts
index 37adbab2d3..f7b2a101e4 100644
--- a/packages/sheets-table/src/controllers/__tests__/table-filter.controller.spec.ts
+++ b/packages/sheets-table/src/controllers/__tests__/table-filter.controller.spec.ts
@@ -14,103 +14,165 @@
* limitations under the License.
*/
-import { DateSystem, toDisposable } from '@univerjs/core';
-import { BehaviorSubject, Subject } from 'rxjs';
-import { describe, expect, it, vi } from 'vitest';
+import type { IWorkbookData, Workbook } from '@univerjs/core';
+import {
+ BooleanNumber,
+ ICommandService,
+ IUniverInstanceService,
+ LocaleService,
+ LocaleType,
+ RedoCommand,
+ UndoCommand,
+ Univer,
+ UniverInstanceType,
+} from '@univerjs/core';
+import { ISheetRowFilteredService, SheetRowFilteredService } from '@univerjs/engine-formula';
+import {
+ INTERCEPTOR_POINT,
+ SheetInterceptorService,
+ SheetRangeThemeModel,
+ ZebraCrossingCacheController,
+} from '@univerjs/sheets';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+import { DeleteSheetTableCommand } from '../../commands/commands/delete-sheet-table.command';
+import { SetSheetTableFilterCommand } from '../../commands/commands/set-table-filter.command';
+import { AddSheetTableMutation } from '../../commands/mutations/add-sheet-table.mutation';
+import { DeleteSheetTableMutation } from '../../commands/mutations/delete-sheet-table.mutation';
+import { SetSheetTableFilterMutation } from '../../commands/mutations/set-table-filter.mutation';
+import enUS from '../../locale/en-US';
+import { TableManager } from '../../models/table-manager';
+import { SheetTableService } from '../../services/table.service';
+import { TableColumnFilterTypeEnum } from '../../types/enum';
import { TableFilterController } from '../table-filter.controller';
describe('TableFilterController', () => {
- it('should merge filtered rows from table filter events and initialize intercept behavior', () => {
- const tableFilterChanged$ = new Subject<any>();
- const tableInitStatus$ = new BehaviorSubject(false);
-
- const mainFilter = {
- doFilter: vi.fn(),
- getFilterOutRows: () => new Set([4]),
- };
- const mainTable = {
- getTableFilters: () => mainFilter,
- getTableFilterRange: () => ({ startRow: 1, endRow: 10, startColumn: 1, endColumn: 2 }),
- };
-
- const extraTable = {
- getTableFilters: () => ({
- getFilterOutRows: () => new Set([8]),
- }),
- };
-
- const tableManager = {
- tableFilterChanged$,
- tableInitStatus$,
- getTable: vi.fn(() => mainTable),
- getTablesBySubunitId: vi.fn((_unitId, subUnitId) => subUnitId === 's1' ? [mainTable, extraTable] : []),
- };
-
- let rowFilteredHandler: any;
- const sheetInterceptorService = {
- intercept: vi.fn((_point: any, config: any) => {
- rowFilteredHandler = config.handler;
- return { dispose: vi.fn() };
- }),
- };
-
- const activeSheet$ = new Subject<any>();
- const workbook = {
- getUnitId: () => 'u1',
- getActiveSheet: () => ({ getSheetId: () => 's1' }),
- activeSheet$,
- getSheetBySheetId: vi.fn(() => ({ id: 'sheet1' })),
- getDateSystem: () => DateSystem.Date1904,
- };
-
- const workbookType$ = new Subject<any>();
- const univerInstanceService = {
- getCurrentTypeOfUnit$: vi.fn(() => workbookType$),
- getCurrentUnitOfType: vi.fn(() => workbook),
- getUnit: vi.fn(() => workbook),
- };
-
- const zebraCrossingCacheController = {
- updateZebraCrossingCache: vi.fn(),
- };
-
- let formulaRowFiltered: ((unitId: string, subUnitId: string, row: number) => boolean) | undefined;
- const sheetRowFilteredService = {
- register: vi.fn((callback) => {
- formulaRowFiltered = callback;
- return toDisposable(() => {
- formulaRowFiltered = undefined;
- });
- }),
- };
-
- const controller = new TableFilterController(
- tableManager as any,
- sheetInterceptorService as any,
- univerInstanceService as any,
- sheetRowFilteredService as any,
- zebraCrossingCacheController as any
- );
-
- tableFilterChanged$.next({ unitId: 'u1', subUnitId: 's1', tableId: 't1' });
-
- expect(mainFilter.doFilter).toHaveBeenCalledWith(
- { id: 'sheet1' },
- { startRow: 1, endRow: 10, startColumn: 1, endColumn: 2 },
- DateSystem.Date1904
- );
- expect(zebraCrossingCacheController.updateZebraCrossingCache).toHaveBeenCalledWith('u1', 's1');
- expect(rowFilteredHandler(false, { unitId: 'u1', subUnitId: 's1', row: 4 }, vi.fn(() => false))).toBe(true);
- expect(formulaRowFiltered?.('u1', 's1', 4)).toBe(true);
- expect(rowFilteredHandler(false, { unitId: 'u1', subUnitId: 's2', row: 4 }, vi.fn(() => false))).toBe(false);
- expect(rowFilteredHandler(false, { unitId: 'u1', subUnitId: 's1', row: 9 }, vi.fn(() => false))).toBe(false);
-
- tableInitStatus$.next(true);
- workbookType$.next(workbook);
- activeSheet$.next({ getSheetId: () => 's1' });
+ let univer: Univer;
+ let workbook: Workbook;
+
+ beforeEach(() => {
+ univer = new Univer();
+ const injector = univer.__getInjector();
+ injector.add([TableManager]);
+ injector.add([SheetTableService]);
+ injector.add([SheetInterceptorService]);
+ injector.add([SheetRangeThemeModel]);
+ injector.add([ZebraCrossingCacheController]);
+ injector.add([ISheetRowFilteredService, { useClass: SheetRowFilteredService }]);
+ injector.add([TableFilterController]);
+ const locale = injector.get(LocaleService);
+ locale.load({ enUS });
+ locale.setLocale(LocaleType.EN_US);
+ locale.setDirection('ltr');
+ injector.get(SheetInterceptorService);
+ workbook = univer.createUnit<IWorkbookData, Workbook>(UniverInstanceType.UNIVER_SHEET, {
+ id: 'test',
+ appVersion: '1.0.3',
+ locale: LocaleType.EN_US,
+ name: 'Tables',
+ styles: {},
+ sheetOrder: ['sheet1', 'sheet2'],
+ sheets: {
+ sheet1: {
+ id: 'sheet1',
+ name: 'Source',
+ rowCount: 20,
+ columnCount: 10,
+ rowData: { 2: { hd: BooleanNumber.TRUE } },
+ cellData: {
+ 0: { 0: { v: 'Name' }, 2: { v: 'Other' } },
+ 1: { 0: { v: 'A' }, 2: { v: 'X' } },
+ 2: { 0: { v: 'B' }, 2: { v: 'Y' } },
+ 3: { 0: { v: 'C' }, 2: { v: 'Z' } },
+ },
+ },
+ sheet2: { id: 'sheet2', name: 'Other', rowCount: 20, columnCount: 10 },
+ },
+ });
+ injector.get(IUniverInstanceService).focusUnit('test');
+ injector.get(TableFilterController);
+ const commands = injector.get(ICommandService);
+ [DeleteSheetTableCommand, DeleteSheetTableMutation, AddSheetTableMutation, SetSheetTableFilterCommand, SetSheetTableFilterMutation].forEach((command) => commands.registerCommand(command));
+ });
- expect(rowFilteredHandler(false, { unitId: 'u1', subUnitId: 's1', row: 8 }, vi.fn(() => false))).toBe(true);
+ afterEach(() => univer.dispose());
+
+ it('releases filtered rows on deletion and restores filters on undo and redo', async () => {
+ const injector = univer.__getInjector();
+ const manager = injector.get(TableManager);
+ const unitId = workbook.getUnitId();
+ const sheet = workbook.getSheetBySheetId('sheet1')!;
+ const formulaRows = injector.get(ISheetRowFilteredService);
+ const commands = injector.get(ICommandService);
+ const tableId = manager.addTable(unitId, 'sheet1', 'Orders', {
+ startRow: 0,
+ endRow: 3,
+ startColumn: 0,
+ endColumn: 0,
+ });
+ const filter = { filterType: TableColumnFilterTypeEnum.manual, values: ['A'] };
+ expect(await commands.executeCommand(SetSheetTableFilterCommand.id, {
+ unitId,
+ tableId,
+ column: 0,
+ tableFilter: filter,
+ })).toBe(true);
+ expect(sheet.isRowFiltered(1)).toBe(false);
+ expect(sheet.isRowFiltered(3)).toBe(true);
+ expect(formulaRows.getRowFiltered(unitId, 'sheet1', 3)).toBe(true);
+ expect(manager.toJSON(unitId).sheet1.tableFilteredOutRows).toEqual([2, 3]);
+
+ expect(await commands.executeCommand(DeleteSheetTableCommand.id, {
+ unitId,
+ subUnitId: 'sheet1',
+ tableId,
+ })).toBe(true);
+ expect(sheet.isRowFiltered(3)).toBe(false);
+ expect(sheet.getRowVisible(3)).toBe(true);
+ expect(sheet.getRowVisible(2)).toBe(false);
+ expect(formulaRows.getRowFiltered(unitId, 'sheet1', 3)).toBe(false);
+
+ expect(await commands.executeCommand(UndoCommand.id)).toBe(true);
+ expect(manager.getTable(unitId, tableId)?.getTableFilterColumn(0)).toEqual(filter);
+ expect(sheet.isRowFiltered(3)).toBe(true);
+ expect(formulaRows.getRowFiltered(unitId, 'sheet1', 3)).toBe(true);
+ expect(await commands.executeCommand(RedoCommand.id)).toBe(true);
+ expect(sheet.isRowFiltered(3)).toBe(false);
+ expect(formulaRows.getRowFiltered(unitId, 'sheet1', 3)).toBe(false);
+ });
- controller.dispose();
+ it('retains other table and sheet filters when a filtered table is deleted', () => {
+ const injector = univer.__getInjector();
+ const manager = injector.get(TableManager);
+ const unitId = workbook.getUnitId();
+ const sheet = workbook.getSheetBySheetId('sheet1')!;
+ const first = manager.addTable(unitId, 'sheet1', 'First', {
+ startRow: 0,
+ endRow: 3,
+ startColumn: 0,
+ endColumn: 0,
+ }, undefined, undefined, {
+ filters: [{ filterType: TableColumnFilterTypeEnum.manual, values: ['A'] }],
+ });
+ manager.addTable(unitId, 'sheet1', 'Second', {
+ startRow: 0,
+ endRow: 3,
+ startColumn: 2,
+ endColumn: 2,
+ }, undefined, undefined, {
+ filters: [{ filterType: TableColumnFilterTypeEnum.manual, values: ['Z'] }],
+ });
+ const intercept = injector.get(SheetInterceptorService).intercept(INTERCEPTOR_POINT.ROW_FILTERED, {
+ priority: 0,
+ handler: (filtered, location, next) => location.row === 5 ? true : next(filtered),
+ });
+ expect(sheet.isRowFiltered(3)).toBe(true);
+ expect(sheet.isRowFiltered(1)).toBe(true);
+ manager.deleteTable(unitId, first);
+ expect(sheet.isRowFiltered(3)).toBe(false);
+ expect(sheet.isRowFiltered(1)).toBe(true);
+ expect(sheet.isRowFiltered(5)).toBe(true);
+ expect(workbook.getSheetBySheetId('sheet2')!.isRowFiltered(1)).toBe(false);
+ expect(injector.get(ISheetRowFilteredService).getRowFiltered(unitId, 'sheet1', 1)).toBe(true);
+ intercept.dispose();
});
});
diff --git a/packages/sheets-table/src/controllers/table-filter.controller.ts b/packages/sheets-table/src/controllers/table-filter.controller.ts
index 063b6af89f..82b21c1495 100644
--- a/packages/sheets-table/src/controllers/table-filter.controller.ts
+++ b/packages/sheets-table/src/controllers/table-filter.controller.ts
@@ -54,7 +54,9 @@ export class TableFilterController extends Disposable {
// Priority must be higher than sheet filtering, because filtering has no next, and those below filtering will not trigger interceptor
priority: 100,
handler: (filtered, rowLocation, next) => {
- if (filtered) return true;
+ if (filtered) {
+ return true;
+ }
const isTableFiltered = this._getTableFilteredOutRows(rowLocation.unitId, rowLocation.subUnitId).has(rowLocation.row);
return isTableFiltered ? true : next(isTableFiltered);
},
@@ -81,6 +83,10 @@ export class TableFilterController extends Disposable {
}
registerFilterChangeEvent() {
+ this.disposeWithMe(this._tableManager.tableDelete$.subscribe(({ unitId, subUnitId }) => {
+ this._refreshTableFilteredOutRows(unitId, subUnitId);
+ this._zebraCrossingCacheController.updateZebraCrossingCache(unitId, subUnitId);
+ }));
this.disposeWithMe(
this._tableManager.tableFilterChanged$.subscribe((event) => {
const { unitId, subUnitId, tableId, oldSubUnitId } = event;
diff --git a/packages/sheets-table/src/models/table-filter.ts b/packages/sheets-table/src/models/table-filter.ts
index 2a444e87cd..5e8d9f6099 100644
--- a/packages/sheets-table/src/models/table-filter.ts
+++ b/packages/sheets-table/src/models/table-filter.ts
@@ -152,7 +152,7 @@ export class TableFilters {
getExecuteFunc(sheet: Worksheet, range: ITableRange, columnIndex: number, filter: ITableFilterItem): (value: any) => boolean {
if (filter.filterType === TableColumnFilterTypeEnum.manual) {
- const valuesSet = new Set(filter.values);
+ const valuesSet = new Set(filter.values.map(String));
return (value: string | number) => {
if (value == null) {
return valuesSet.has(TABLE_FILTER_EMPTY_VALUE);
diff --git a/packages/sheets-ui/src/commands/commands/__tests__/set-frozen.command.spec.ts b/packages/sheets-ui/src/commands/commands/__tests__/set-frozen.command.spec.ts
index d2b7a3305d..b49731f43c 100644
--- a/packages/sheets-ui/src/commands/commands/__tests__/set-frozen.command.spec.ts
+++ b/packages/sheets-ui/src/commands/commands/__tests__/set-frozen.command.spec.ts
@@ -16,8 +16,16 @@
import type { IFreeze, Injector, IWorkbookData, Univer, Workbook } from '@univerjs/core';
import type { IScrollStateWithSearchParam } from '../../../services/scroll-manager.service';
-import { ICommandService, IUniverInstanceService, RANGE_TYPE, UniverInstanceType } from '@univerjs/core';
-import { CancelFrozenCommand, SheetsSelectionsService } from '@univerjs/sheets';
+import {
+ ICommandService,
+ IUniverInstanceService,
+ RANGE_TYPE,
+ RedoCommand,
+ UndoCommand,
+ UniverInstanceType,
+} from '@univerjs/core';
+import { deserializeRangeWithSheet } from '@univerjs/engine-formula';
+import { CancelFrozenCommand, getPrimaryForRange, SetSelectionsOperation, SheetsSelectionsService } from '@univerjs/sheets';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import { SheetScrollManagerService } from '../../../services/scroll-manager.service';
import {
@@ -126,6 +134,31 @@ describe('Test commands used for change selections', () => {
expect(config?.startRow === 2 && config.startColumn === 2).toBeTruthy();
});
+ it.each(['D12', '$D$12', 'D12:F15'])('freezes a parsed reference %s and supports undo and redo', async (reference) => {
+ const workbook = get(IUniverInstanceService).getCurrentUnitOfType<Workbook>(UniverInstanceType.UNIVER_SHEET)!;
+ const worksheet = workbook.getActiveSheet();
+ const { range } = deserializeRangeWithSheet(reference);
+ const originalFreeze = { ...worksheet.getFreeze() };
+ commandService.syncExecuteCommand(SetSelectionsOperation.id, {
+ unitId: workbook.getUnitId(),
+ subUnitId: worksheet.getSheetId(),
+ selections: [{ range, primary: getPrimaryForRange(range, worksheet), style: null }],
+ });
+
+ expect(selectionManagerService.getCurrentLastSelectionPrimaryCell()).toMatchObject({
+ actualRow: 11,
+ actualColumn: 3,
+ });
+ await expect(commandService.executeCommand(SetSelectionFrozenCommand.id)).resolves.toBe(true);
+ const expectedFreeze = { startRow: 11, startColumn: 3, xSplit: 3, ySplit: 11 };
+ expect(getFreeze()).toEqual(expectedFreeze);
+
+ await commandService.executeCommand(UndoCommand.id);
+ expect(getFreeze()).toEqual(originalFreeze);
+ await commandService.executeCommand(RedoCommand.id);
+ expect(getFreeze()).toEqual(expectedFreeze);
+ });
+
it('Should keep default freeze config when selection is invalid', async () => {
await commandService.executeCommand(CancelFrozenCommand.id);
diff --git a/packages/sheets-ui/src/commands/commands/set-frozen.command.ts b/packages/sheets-ui/src/commands/commands/set-frozen.command.ts
index e88fb5b1cc..b4cc055a26 100644
--- a/packages/sheets-ui/src/commands/commands/set-frozen.command.ts
+++ b/packages/sheets-ui/src/commands/commands/set-frozen.command.ts
@@ -36,13 +36,14 @@ export interface ISetSelectionFrozenCommandParams {
export const SetSelectionFrozenCommand: ICommand<ISetSelectionFrozenCommandParams> = {
type: CommandType.COMMAND,
id: 'sheet.command.set-selection-frozen',
- // eslint-disable-next-line max-lines-per-function
handler: async (accessor, params) => {
const { type } = params || {};
const univerInstanceService = accessor.get(IUniverInstanceService);
const undoRedoService = accessor.get(IUndoRedoService);
const target = getSheetCommandTarget(univerInstanceService);
- if (!target) return false;
+ if (!target) {
+ return false;
+ }
const { unitId, subUnitId } = target;
const commandService = accessor.get(ICommandService);
@@ -62,7 +63,7 @@ export const SetSelectionFrozenCommand: ICommand<ISetSelectionFrozenCommandParam
let freezedColCount;
if (type === SetSelectionFrozenType.FirstRow) {
- startRow = sheetViewStartRow + 1; ;
+ startRow = sheetViewStartRow + 1;
freezedRowCount = 1;
startColumn = -1;
freezedColCount = 0;
@@ -82,7 +83,7 @@ export const SetSelectionFrozenCommand: ICommand<ISetSelectionFrozenCommandParam
if (selectColumn === 0) {
selectColumn = 1;
}
- const rangeType = range.rangeType;
+ const rangeType = range.rangeType ?? RANGE_TYPE.NORMAL;
if (rangeType === RANGE_TYPE.ROW || type === SetSelectionFrozenType.Row) {
// Frozen to Row
diff --git a/packages/sheets-ui/src/common/__tests__/utils.spec.ts b/packages/sheets-ui/src/common/__tests__/utils.spec.ts
index ae705d6c6e..a570f67616 100644
--- a/packages/sheets-ui/src/common/__tests__/utils.spec.ts
+++ b/packages/sheets-ui/src/common/__tests__/utils.spec.ts
@@ -14,7 +14,11 @@
* limitations under the License.
*/
+import type { IWorkbookData, Workbook } from '@univerjs/core';
+import type { Scene } from '@univerjs/engine-render';
+import { Univer, UniverInstanceType } from '@univerjs/core';
import { SHEET_VIEWPORT_KEY } from '@univerjs/engine-render';
+import { SheetSkeletonService } from '@univerjs/sheets';
import { describe, expect, it } from 'vitest';
import {
checkCellContentInRange,
@@ -29,6 +33,61 @@ import {
} from '../utils';
describe('common utils', () => {
+ it.each([
+ { xSplit: 0, scale: 1 },
+ { xSplit: 1, scale: 1 },
+ { xSplit: 1, scale: 1.25 },
+ { xSplit: 1, scale: 2 },
+ ])('keeps a frozen Table menu below its title with %j', ({ xSplit, scale }) => {
+ const univer = new Univer();
+ const injector = univer.__getInjector();
+ injector.add([SheetSkeletonService]);
+ const skeletonService = injector.get(SheetSkeletonService);
+ const workbook = univer.createUnit<IWorkbookData, Workbook>(UniverInstanceType.UNIVER_SHEET, {
+ id: 'table-menu',
+ sheetOrder: ['sheet1'],
+ sheets: {
+ sheet1: {
+ id: 'sheet1',
+ rowCount: 20,
+ columnCount: 20,
+ freeze: { startRow: 3, startColumn: xSplit || -1, ySplit: 3, xSplit },
+ },
+ },
+ });
+
+ try {
+ const worksheet = workbook.getActiveSheet();
+ const skeleton = skeletonService.getSkeleton(workbook.getUnitId(), worksheet.getSheetId())!;
+ skeleton.setGapConfig({ rowGaps: { 0: { size: 32 } } });
+ const frozenEnd = skeleton.getNoMergeCellWithCoordByIndex(3, xSplit, false);
+ // Only the platform viewport is supplied here; worksheet and layout use real providers.
+ const scene = {
+ getAncestorScale: () => ({ scaleX: scale, scaleY: scale }),
+ getViewport: () => ({
+ left: (skeleton.rowHeaderWidth + frozenEnd.startX) * scale,
+ top: (skeleton.columnHeaderHeight + frozenEnd.startY) * scale,
+ viewportScrollX: 150,
+ viewportScrollY: 300,
+ }),
+ } as unknown as Scene;
+ const cell = skeleton.getNoMergeCellWithCoordByIndex(0, 0);
+ const title = {
+ left: cell.startX,
+ right: cell.startX + 122,
+ top: cell.startY - 28,
+ bottom: cell.startY,
+ };
+ const bound = transformBound2OffsetBound(title, scene, skeleton, worksheet);
+
+ // The popup's anchor bottom must stay at the visible bottom of the title after scrolling.
+ expect(bound.top).toBe(title.top * scale);
+ expect(bound.bottom).toBe(title.bottom * scale);
+ } finally {
+ univer.dispose();
+ }
+ });
+
it('compares collaborator user lists by user id and role', () => {
const list1 = [
{ id: 'b', subject: { userID: 'u2' }, role: 'viewer' },
@@ -120,7 +179,7 @@ describe('common utils', () => {
const scene = {
getAncestorScale: () => ({ scaleX: 2, scaleY: 3 }),
- getViewport: () => ({ top: 50, left: 40, viewportScrollX: 5, viewportScrollY: 6 }),
+ getViewport: () => ({ top: 150, left: 80, viewportScrollX: 5, viewportScrollY: 6 }),
};
const skeleton = {
getNoMergeCellWithCoordByIndex: (row: number, col: number) => {
@@ -137,7 +196,7 @@ describe('common utils', () => {
};
const result = transformPosition2Offset(60, 20, scene as any, skeleton as any, worksheet as any);
- expect(result).toEqual({ x: 110, y: 76 });
+ expect(result).toEqual({ x: 110, y: 114 });
const bound = transformBound2OffsetBound({ left: 30, top: 20, right: 60, bottom: 70 } as any, scene as any, skeleton as any, worksheet as any);
expect(bound.left).toBeTypeOf('number');
diff --git a/packages/sheets-ui/src/common/utils.ts b/packages/sheets-ui/src/common/utils.ts
index c1e44fbaa3..002fe0fbaa 100644
--- a/packages/sheets-ui/src/common/utils.ts
+++ b/packages/sheets-ui/src/common/utils.ts
@@ -136,22 +136,26 @@ export function transformPosition2Offset(x: number, y: number, scene: Scene, ske
const endSheetView = skeleton.getNoMergeCellWithCoordByIndex(startRow, startColumn, false);
const { rowHeaderWidth, columnHeaderHeight } = skeleton;
const freezeWidth = endSheetView.startX - startSheetView.startX;
- const freezeHeight = endSheetView.startY - startSheetView.startY;
+ // Match the frozen viewport, which includes the leading gap when freezing from the first row.
+ const freezeStartY = ySplit > 0 && startRow === ySplit ? 0 : startSheetView.startY;
+ const freezeHeight = endSheetView.startY - freezeStartY;
const { top, left, viewportScrollX, viewportScrollY } = viewMain;
+ const viewportLeft = left / scaleX;
+ const viewportTop = top / scaleY;
let offsetX: number;
// viewMain or viewTop
- if (x > left) {
+ if (x > viewportLeft) {
offsetX = (x - viewportScrollX) * scaleX;
} else {
- offsetX = ((freezeWidth + rowHeaderWidth) - (left - x)) * scaleX;
+ offsetX = ((freezeWidth + rowHeaderWidth) - (viewportLeft - x)) * scaleX;
}
let offsetY: number;
- if (y > top) {
+ if (y > viewportTop) {
offsetY = (y - viewportScrollY) * scaleY;
} else {
- offsetY = ((freezeHeight + columnHeaderHeight) - (top - y)) * scaleX;
+ offsetY = ((freezeHeight + columnHeaderHeight) - (viewportTop - y)) * scaleY;
}
return {
diff --git a/packages/sheets-ui/src/controllers/render-controllers/__tests__/freeze.render-controller.spec.ts b/packages/sheets-ui/src/controllers/render-controllers/__tests__/freeze.render-controller.spec.ts
index 18ea288d26..fea37a6181 100644
--- a/packages/sheets-ui/src/controllers/render-controllers/__tests__/freeze.render-controller.spec.ts
+++ b/packages/sheets-ui/src/controllers/render-controllers/__tests__/freeze.render-controller.spec.ts
@@ -16,14 +16,97 @@
import { ICommandService } from '@univerjs/core';
import { SHEET_VIEWPORT_KEY, TRANSFORM_CHANGE_OBSERVABLE_TYPE } from '@univerjs/engine-render';
-import { SetFrozenCommand, SetWorksheetActiveOperation } from '@univerjs/sheets';
+import { SetFrozenCommand, SetWorksheetActiveOperation, SheetSkeletonService } from '@univerjs/sheets';
import { BehaviorSubject } from 'rxjs';
import { describe, expect, it, vi } from 'vitest';
import { SheetScrollManagerService } from '../../../services/scroll-manager.service';
+import { SheetSkeletonManagerService } from '../../../services/sheet-skeleton-manager.service';
import { HeaderFreezeRenderController } from '../freeze.render-controller';
import { createRenderTestBed } from './render-test-bed';
describe('HeaderFreezeRenderController', () => {
+ it.each([
+ { startRow: 3, startColumn: -1, ySplit: 3, xSplit: 0 },
+ { startRow: 3, startColumn: 2, ySplit: 3, xSplit: 2 },
+ ])('keeps the leading Table title gap visible with freeze config %j', (freeze) => {
+ const testBed = createRenderTestBed();
+ const { sheet, context, viewportMap } = testBed;
+ const injector = testBed.injector.createChild();
+ injector.add([SheetSkeletonService]);
+ injector.add([SheetSkeletonManagerService, {
+ useFactory: function createSkeletonManager() {
+ return injector.createInstance(SheetSkeletonManagerService, context);
+ },
+ }]);
+ injector.add([SheetScrollManagerService, {
+ useFactory: function createScrollManager() {
+ return injector.createInstance(SheetScrollManagerService, context);
+ },
+ }]);
+ injector.add([HeaderFreezeRenderController, {
+ useFactory: function createFreezeController() {
+ return injector.createInstance(HeaderFreezeRenderController, context);
+ },
+ }]);
+
+ try {
+ const manager = injector.get(SheetSkeletonManagerService);
+ const worksheet = sheet.getActiveSheet();
+ manager.setCurrent({ sheetId: worksheet.getSheetId() });
+ const skeleton = manager.getCurrentSkeleton()!;
+ const frozenRowsHeight = skeleton.getNoMergeCellWithCoordByIndex(3, 0, false).startY;
+ const headerHeight = skeleton.columnHeaderHeightAndMarginTop;
+ skeleton.setGapConfig({ rowGaps: { 0: { size: 32 } } });
+ worksheet.getConfig().freeze = freeze;
+ injector.get(HeaderFreezeRenderController);
+ // A scene scale refresh also applies the initial freeze layout.
+ testBed.scene.onTransformChange$.emit({
+ type: TRANSFORM_CHANGE_OBSERVABLE_TYPE.scale,
+ value: { scaleX: 1, scaleY: 1 },
+ }, { stopPropagation: () => {} });
+
+ const viewMain = viewportMap.get(SHEET_VIEWPORT_KEY.VIEW_MAIN)!;
+ const viewMainTop = viewportMap.get(SHEET_VIEWPORT_KEY.VIEW_MAIN_TOP)!;
+ const viewRowTop = viewportMap.get(SHEET_VIEWPORT_KEY.VIEW_ROW_TOP)!;
+ const viewMainLeftTop = viewportMap.get(SHEET_VIEWPORT_KEY.VIEW_MAIN_LEFT_TOP)!;
+ expect(viewMainTop.viewportScrollY).toBe(0);
+ expect(viewRowTop.viewportScrollY).toBe(0);
+ expect(viewMainTop.height).toBe(frozenRowsHeight + 32);
+ expect(viewMain.top).toBe(headerHeight + frozenRowsHeight + 32);
+ if (freeze.xSplit > 0) {
+ expect(viewMainLeftTop.viewportScrollY).toBe(0);
+ expect(viewMainLeftTop.height).toBe(frozenRowsHeight + 32);
+ }
+
+ // Removing and recreating the top Table must resize an existing frozen area too.
+ skeleton.setGapConfig({});
+ expect(viewMainTop.height).toBe(frozenRowsHeight);
+ expect(viewMain.top).toBe(headerHeight + frozenRowsHeight);
+ skeleton.setGapConfig({ rowGaps: { 0: { size: 32 } } });
+ expect(viewMainTop.height).toBe(frozenRowsHeight + 32);
+ expect(viewMainTop.viewportScrollY).toBe(0);
+
+ // A frozen range starting below row 1 must still skip the preceding rows and gap.
+ worksheet.getConfig().freeze = { ...freeze, startRow: 5 };
+ testBed.scene.onTransformChange$.emit({
+ type: TRANSFORM_CHANGE_OBSERVABLE_TYPE.scale,
+ value: { scaleX: 1, scaleY: 1 },
+ }, { stopPropagation: () => {} });
+ expect(viewMainTop.viewportScrollY).toBe(skeleton.getNoMergeCellWithCoordByIndex(2, 0, false).startY);
+
+ worksheet.getConfig().freeze = { startRow: -1, startColumn: -1, ySplit: 0, xSplit: 0 };
+ testBed.scene.onTransformChange$.emit({
+ type: TRANSFORM_CHANGE_OBSERVABLE_TYPE.scale,
+ value: { scaleX: 1, scaleY: 1 },
+ }, { stopPropagation: () => {} });
+ expect(viewMainTop.isActive).toBe(false);
+ expect(viewMain.top).toBe(headerHeight);
+ } finally {
+ injector.dispose();
+ testBed.univer.dispose();
+ }
+ });
+
it('refreshes viewports when switching sheets and freeze is enabled', () => {
const validViewportScrollInfo$ = new BehaviorSubject<any>(null);
const scrollManagerService = {
diff --git a/packages/sheets-ui/src/controllers/render-controllers/freeze.render-controller.ts b/packages/sheets-ui/src/controllers/render-controllers/freeze.render-controller.ts
index e5b68d3a22..e2dac9bf11 100644
--- a/packages/sheets-ui/src/controllers/render-controllers/freeze.render-controller.ts
+++ b/packages/sheets-ui/src/controllers/render-controllers/freeze.render-controller.ts
@@ -45,7 +45,6 @@ import {
ThemeService,
toDisposable,
} from '@univerjs/core';
-
import { CURSOR_TYPE, Rect, SHEET_VIEWPORT_KEY, TRANSFORM_CHANGE_OBSERVABLE_TYPE, Vector2 } from '@univerjs/engine-render';
import {
InsertColCommand,
@@ -70,9 +69,8 @@ import {
SheetInterceptorService,
SheetsSelectionsService,
} from '@univerjs/sheets';
-import { Subscription } from 'rxjs';
+import { EMPTY, Subscription, switchMap } from 'rxjs';
import { SetColumnHeaderHeightCommand, SetRowHeaderWidthCommand } from '../../commands/commands/headersize-changed.command';
-
import { ScrollCommand } from '../../commands/commands/set-scroll.command';
import { SetZoomRatioOperation } from '../../commands/operations/set-zoom-ratio.operation';
import { SHEET_COMPONENT_HEADER_LAYER_INDEX } from '../../common/keys';
@@ -861,6 +859,10 @@ export class HeaderFreezeRenderController extends Disposable implements IRenderM
// freeze start
const startSheetView = skeleton.getNoMergeCellWithCoordByIndex(row - ySplit, column - xSplit, false);
+ // The gap above the first row belongs to the frozen area, including any Table title in it.
+ if (isTopView && row === ySplit) {
+ startSheetView.startY = 0;
+ }
// freeze end
const endSheetView = skeleton.getNoMergeCellWithCoordByIndex(row, column, false);
@@ -1147,6 +1149,11 @@ export class HeaderFreezeRenderController extends Disposable implements IRenderM
* When switching sheet tabs, it is necessary to update the frozen state of the current view.
*/
private _skeletonListener() {
+ this.disposeWithMe(
+ this._sheetSkeletonManagerService.currentSkeleton$.pipe(
+ switchMap((param) => param?.skeleton?.gapConfigChanged$ ?? EMPTY)
+ ).subscribe(() => this._refreshCurrent())
+ );
this.disposeWithMe(
toDisposable(
this._sheetSkeletonManagerService.currentSkeleton$.subscribe((param) => {
diff --git a/packages/sheets-ui/src/menu/__tests__/merge.menu.spec.ts b/packages/sheets-ui/src/menu/__tests__/merge.menu.spec.ts
new file mode 100644
index 0000000000..3714eef523
--- /dev/null
+++ b/packages/sheets-ui/src/menu/__tests__/merge.menu.spec.ts
@@ -0,0 +1,169 @@
+/**
+ * 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 { IRange } from '@univerjs/core';
+import type { ISelectionWithStyle } from '@univerjs/sheets';
+import type { Subscription } from 'rxjs';
+import type { ITestBed } from '../../commands/commands/__tests__/create-command-test-bed';
+import {
+ ICommandService,
+ IUniverInstanceService,
+ LocaleType,
+ RANGE_TYPE,
+ RedoCommand,
+ UndoCommand,
+} from '@univerjs/core';
+import {
+ AddWorksheetMergeMutation,
+ ExclusiveRangeService,
+ IExclusiveRangeService,
+ MergeCellController,
+ RefRangeService,
+ RemoveWorksheetMergeCommand,
+ RemoveWorksheetMergeMutation,
+ SetRangeValuesMutation,
+ SetSelectionsOperation,
+ SetWorksheetActiveOperation,
+ SheetsSelectionsService,
+} from '@univerjs/sheets';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+import { createCommandTestBed } from '../../commands/commands/__tests__/create-command-test-bed';
+import { CellMergeMenuItemFactory } from '../merge.menu';
+
+describe('merge menu active state', () => {
+ let testBed: ITestBed;
+ let commandService: ICommandService;
+ let selections: SheetsSelectionsService;
+ let subscription: Subscription;
+ let active: boolean;
+
+ const mergedRange: IRange = {
+ startRow: 1,
+ endRow: 2,
+ startColumn: 1,
+ endColumn: 2,
+ rangeType: RANGE_TYPE.NORMAL,
+ };
+
+ function selectCell(row: number, column: number, range?: IRange): ISelectionWithStyle {
+ const cell = testBed.sheet.getActiveSheet().getCellInfoInMergeData(row, column);
+ return {
+ range: range ?? { startRow: row, endRow: row, startColumn: column, endColumn: column },
+ primary: { ...cell, actualRow: row, actualColumn: column },
+ style: null,
+ };
+ }
+
+ function subscribe() {
+ subscription = CellMergeMenuItemFactory(testBed.univer.__getInjector()).activated$!.subscribe((value) => {
+ active = value;
+ });
+ }
+
+ beforeEach(() => {
+ testBed = createCommandTestBed({
+ id: 'test',
+ appVersion: '3.0.0-alpha',
+ locale: LocaleType.EN_US,
+ name: '',
+ styles: {},
+ sheetOrder: ['sheet1', 'sheet2'],
+ sheets: {
+ sheet1: { id: 'sheet1', mergeData: [mergedRange] },
+ sheet2: { id: 'sheet2' },
+ },
+ }, [
+ [IExclusiveRangeService, { useClass: ExclusiveRangeService }],
+ [RefRangeService],
+ [MergeCellController],
+ ]);
+ commandService = testBed.get(ICommandService);
+ selections = testBed.get(SheetsSelectionsService);
+ [
+ AddWorksheetMergeMutation,
+ RemoveWorksheetMergeMutation,
+ RemoveWorksheetMergeCommand,
+ SetRangeValuesMutation,
+ SetSelectionsOperation,
+ SetWorksheetActiveOperation,
+ ].forEach((command) => commandService.registerCommand(command));
+ });
+
+ afterEach(() => {
+ subscription?.unsubscribe();
+ testBed.univer.dispose();
+ });
+
+ it('follows the focused cell, including the merge anchor and the last of multiple selections', () => {
+ selections.setSelections([selectCell(1, 1, mergedRange)]);
+ subscribe();
+ expect(active).toBe(true);
+
+ const ordinaryCell = selectCell(0, 0, { startRow: 0, endRow: 4, startColumn: 0, endColumn: 4 });
+ selections.setSelections([ordinaryCell]);
+ expect(active).toBe(false);
+
+ const mergedCell = selectCell(2, 2, mergedRange);
+ selections.setSelections([ordinaryCell, mergedCell]);
+ expect(active).toBe(true);
+ selections.setSelections([mergedCell, ordinaryCell]);
+ expect(active).toBe(false);
+ selections.setSelections([]);
+ expect(active).toBe(false);
+ });
+
+ it('updates after unmerge, undo and redo without requiring another cell click', async () => {
+ selections.setSelections([selectCell(1, 1, mergedRange)]);
+ subscribe();
+ expect(active).toBe(true);
+
+ expect(await commandService.executeCommand(RemoveWorksheetMergeCommand.id)).toBe(true);
+ expect(active).toBe(false);
+ expect(await commandService.executeCommand(UndoCommand.id)).toBe(true);
+ expect(active).toBe(true);
+ expect(await commandService.executeCommand(RedoCommand.id)).toBe(true);
+ expect(active).toBe(false);
+
+ // The selection can still carry pre-mutation merge flags, so read the worksheet's merge model.
+ expect(commandService.syncExecuteCommand(AddWorksheetMergeMutation.id, {
+ unitId: testBed.sheet.getUnitId(),
+ subUnitId: 'sheet1',
+ ranges: [mergedRange],
+ })).toBe(true);
+ expect(active).toBe(true);
+ });
+
+ it('refreshes when switching sheets and when there is no current workbook', () => {
+ selections.setSelections([selectCell(1, 1, mergedRange)]);
+ selections.setSelections('test', 'sheet2', [selectCell(1, 1, mergedRange)]);
+ subscribe();
+ expect(active).toBe(true);
+
+ expect(commandService.syncExecuteCommand(SetWorksheetActiveOperation.id, {
+ unitId: 'test',
+ subUnitId: 'sheet2',
+ })).toBe(true);
+ expect(active).toBe(false);
+ expect(commandService.syncExecuteCommand(SetWorksheetActiveOperation.id, {
+ unitId: 'test',
+ subUnitId: 'sheet1',
+ })).toBe(true);
+ expect(active).toBe(true);
+
+ testBed.get(IUniverInstanceService).disposeUnit('test');
+ expect(active).toBe(false);
+ });
+});
diff --git a/packages/sheets-ui/src/menu/merge.menu.ts b/packages/sheets-ui/src/menu/merge.menu.ts
index 4fbeb9b603..9035becc6d 100644
--- a/packages/sheets-ui/src/menu/merge.menu.ts
+++ b/packages/sheets-ui/src/menu/merge.menu.ts
@@ -17,25 +17,37 @@
import type { IAccessor } from '@univerjs/core';
import type { IMenuButtonItem, IMenuSelectorItem } from '@univerjs/ui';
import type { LocaleKey } from '../locale/types';
-import { FOCUSING_COMMON_DRAWINGS, IContextService, UniverInstanceType } from '@univerjs/core';
+import {
+ FOCUSING_COMMON_DRAWINGS,
+ ICommandService,
+ IContextService,
+ IUniverInstanceService,
+ UniverInstanceType,
+} from '@univerjs/core';
import {
AddWorksheetMergeAllCommand,
AddWorksheetMergeCommand,
AddWorksheetMergeHorizontalCommand,
+ AddWorksheetMergeMutation,
AddWorksheetMergeVerticalCommand,
RangeProtectionPermissionEditPoint,
RemoveWorksheetMergeCommand,
+ RemoveWorksheetMergeMutation,
+ SheetsSelectionsService,
WorkbookEditablePermission,
WorksheetEditPermission,
WorksheetSetCellStylePermission,
WorksheetSetCellValuePermission,
} from '@univerjs/sheets';
import { getMenuHiddenObservable, MenuItemType } from '@univerjs/ui';
-import { combineLatest, combineLatestWith, map, startWith } from 'rxjs';
+import { combineLatest, combineLatestWith, distinctUntilChanged, map, Observable, startWith } from 'rxjs';
import { getSheetSelectionsDisabled$ } from '../controllers/utils/selections-tools';
-import { getCurrentRangeDisable$, getObservableWithExclusiveRange$ } from './menu-util';
+import { deriveStateFromActiveSheet$, getCurrentRangeDisable$, getObservableWithExclusiveRange$ } from './menu-util';
export function CellMergeMenuItemFactory(accessor: IAccessor): IMenuSelectorItem<LocaleKey> {
+ const commandService = accessor.get(ICommandService);
+ const instanceService = accessor.get(IUniverInstanceService);
+ const selectionService = accessor.get(SheetsSelectionsService);
const editDisabled$ = getObservableWithExclusiveRange$(accessor, getCurrentRangeDisable$(accessor, {
workbookTypes: [WorkbookEditablePermission],
worksheetTypes: [WorksheetEditPermission, WorksheetSetCellValuePermission, WorksheetSetCellStylePermission],
@@ -48,7 +60,24 @@ export function CellMergeMenuItemFactory(accessor: IAccessor): IMenuSelectorItem
icon: 'MergeAllIcon',
tooltip: 'sheets-ui.toolbar.mergeCell.main',
type: MenuItemType.SUBITEMS,
- // selections: [...MERGE_CHILDREN],
+ activated$: deriveStateFromActiveSheet$(instanceService, false, ({ worksheet }) => new Observable<boolean>((subscriber) => {
+ const update = () => {
+ const primary = selectionService.getCurrentLastSelection()?.primary;
+ subscriber.next(!!primary && !!worksheet.getMergedCell(primary.actualRow, primary.actualColumn));
+ };
+ const selectionSubscription = selectionService.selectionChanged$.subscribe(update);
+ const commandDisposable = commandService.onCommandExecuted((command) => {
+ if (command.id === AddWorksheetMergeMutation.id || command.id === RemoveWorksheetMergeMutation.id) {
+ update();
+ }
+ });
+ update();
+
+ return () => {
+ selectionSubscription.unsubscribe();
+ commandDisposable.dispose();
+ };
+ })).pipe(distinctUntilChanged()),
hidden$: combineLatest([
getMenuHiddenObservable(accessor, UniverInstanceType.UNIVER_SHEET),
accessor.get(IContextService).subscribeContextValue$(FOCUSING_COMMON_DRAWINGS).pipe(startWith(false)),
diff --git a/packages/sheets-ui/src/services/clipboard/clipboard.service.ts b/packages/sheets-ui/src/services/clipboard/clipboard.service.ts
index 703dcd50cd..75d1aa5cff 100644
--- a/packages/sheets-ui/src/services/clipboard/clipboard.service.ts
+++ b/packages/sheets-ui/src/services/clipboard/clipboard.service.ts
@@ -185,9 +185,10 @@ interface ICopyContent {
* This service provide hooks for sheet features to supplement content or modify behavior of clipboard.
*/
+// Univer clipboard HTML also contains Word compatibility metadata.
+HtmlToUSMService.use(UniverPastePlugin);
HtmlToUSMService.use(WordPastePlugin);
HtmlToUSMService.use(LarkPastePlugin);
-HtmlToUSMService.use(UniverPastePlugin);
export interface ISheetClipboardService {
showMenu$: Observable<boolean>;
diff --git a/packages/sheets-ui/src/services/clipboard/html-to-usm/__tests__/converter.spec.ts b/packages/sheets-ui/src/services/clipboard/html-to-usm/__tests__/converter.spec.ts
index d513f46fbb..cf44c82f04 100644
--- a/packages/sheets-ui/src/services/clipboard/html-to-usm/__tests__/converter.spec.ts
+++ b/packages/sheets-ui/src/services/clipboard/html-to-usm/__tests__/converter.spec.ts
@@ -15,15 +15,110 @@
*/
import type { ISheetSkeletonManagerParam } from '@univerjs/sheets';
+import { DocumentDataModel } from '@univerjs/core';
+import { convertBodyToHtml } from '@univerjs/docs-ui';
import { describe, expect, it } from 'vitest';
import { HtmlToUSMService } from '../converter';
import { LarkPastePlugin } from '../paste-plugins/plugin-lark';
+import { UniverPastePlugin } from '../paste-plugins/plugin-univer';
import { WordPastePlugin } from '../paste-plugins/plugin-word';
+HtmlToUSMService.use(UniverPastePlugin);
HtmlToUSMService.use(WordPastePlugin);
HtmlToUSMService.use(LarkPastePlugin);
describe('HtmlToUSMService', () => {
+ it('preserves colors and offsets when importing a copied rich text selection with Word metadata', () => {
+ const source = new DocumentDataModel({
+ id: 'rich-text-selection',
+ body: {
+ dataStream: 'xABCDy\r\n',
+ textRuns: [
+ { st: 1, ed: 3, ts: { cl: { rgb: '#ff0000' } } },
+ { st: 3, ed: 5, ts: { cl: { rgb: '#0000ff' } } },
+ ],
+ },
+ });
+ const fragment = convertBodyToHtml({
+ id: 'copied-selection',
+ body: source.sliceBody(1, 5)!,
+ documentStyle: {},
+ });
+ const converter = new HtmlToUSMService({
+ getCurrentSkeleton: () => ({ skeleton: {} } as ISheetSkeletonManagerParam),
+ });
+ const { cellMatrix } = converter.convert(`
+ <html><head><meta name="ProgId" content="Word.Document"></head>
+ <body>${fragment}<p class="UniverNormal">next row</p></body></html>
+ `);
+
+ expect(cellMatrix.getValue(0, 0)?.v).toBe('ABCD');
+ expect(cellMatrix.getValue(0, 0)?.p?.body?.textRuns).toEqual([
+ expect.objectContaining({ st: 0, ed: 2, ts: expect.objectContaining({ cl: { rgb: 'rgb(255,0,0)' } }) }),
+ expect.objectContaining({ st: 2, ed: 4, ts: expect.objectContaining({ cl: { rgb: 'rgb(0,0,255)' } }) }),
+ ]);
+ expect(cellMatrix.getValue(1, 0)?.v).toBe('next row');
+ expect(cellMatrix.getValue(2, 0)).toBeUndefined();
+ });
+
+ it.each([
+ {
+ html: '<span style="color:red">AB</span><span style="color:blue">CD</span>',
+ runs: [
+ { st: 0, ed: 2, ts: { cl: { rgb: 'rgb(255,0,0)' } } },
+ { st: 2, ed: 4, ts: { cl: { rgb: 'rgb(0,0,255)' } } },
+ ],
+ },
+ {
+ html: 'A<span style="color:red">BC</span>D',
+ runs: [{ st: 1, ed: 3, ts: { cl: { rgb: 'rgb(255,0,0)' } } }],
+ },
+ ])('preserves inline text styles without paragraph markup: $html', ({ html, runs }) => {
+ const converter = new HtmlToUSMService({
+ getCurrentSkeleton: () => ({ skeleton: {} } as ISheetSkeletonManagerParam),
+ });
+ const cell = converter.convert(html).cellMatrix.getValue(0, 0);
+
+ expect(cell?.v).toBe('ABCD');
+ expect(cell?.p?.body?.dataStream).toBe('ABCD\r\n');
+ expect(cell?.p?.body?.textRuns).toEqual(runs);
+ });
+
+ it('keeps a uniform font color as a cell style', () => {
+ const converter = new HtmlToUSMService({
+ getCurrentSkeleton: () => ({ skeleton: {} } as ISheetSkeletonManagerParam),
+ });
+ const cell = converter.convert('<span style="color:red">ABCD</span>').cellMatrix.getValue(0, 0);
+
+ expect(cell?.v).toBe('ABCD');
+ expect(cell?.s).toEqual({ cl: { rgb: 'rgb(255,0,0)' } });
+ expect(cell?.p?.body?.textRuns).toEqual([]);
+ });
+
+ it('preserves inline styles in the last row after a line break', () => {
+ const converter = new HtmlToUSMService({
+ getCurrentSkeleton: () => ({ skeleton: {} } as ISheetSkeletonManagerParam),
+ });
+ const { cellMatrix } = converter.convert('first<br>A<span style="color:red">BC</span>D');
+
+ expect(cellMatrix.getValue(0, 0)?.v).toBe('first');
+ expect(cellMatrix.getValue(1, 0)?.v).toBe('ABCD');
+ expect(cellMatrix.getValue(1, 0)?.p?.body?.textRuns).toEqual([
+ { st: 1, ed: 3, ts: { cl: { rgb: 'rgb(255,0,0)' } } },
+ ]);
+ });
+
+ it('uses Word paragraph rules when UniverNormal appears only in a stylesheet', () => {
+ const converter = new HtmlToUSMService({ getCurrentSkeleton: () => null });
+ const { cellMatrix } = converter.convert(`
+ <html><head><style>p.UniverNormal { color: red; }</style></head>
+ <body><p class="MsoNormal">first</p><p class="MsoNormal">second</p></body></html>
+ `);
+
+ expect(cellMatrix.getValue(0, 0)?.v).toBe('first');
+ expect(cellMatrix.getValue(1, 0)?.v).toBe('second');
+ });
+
it('preserves Excel borders that use the legacy windowtext system color', () => {
const converter = new HtmlToUSMService({ getCurrentSkeleton: () => null });
const { cellMatrix } = converter.convert(`
diff --git a/packages/sheets-ui/src/services/clipboard/html-to-usm/converter.ts b/packages/sheets-ui/src/services/clipboard/html-to-usm/converter.ts
index 45b711e14c..70d11aedb2 100644
--- a/packages/sheets-ui/src/services/clipboard/html-to-usm/converter.ts
+++ b/packages/sheets-ui/src/services/clipboard/html-to-usm/converter.ts
@@ -26,7 +26,19 @@ import type {
IUniverSheetCopyDataModel,
} from '../type';
import type { IAfterProcessRule, IPastePlugin } from './paste-plugins/type';
-import { createDocumentModelWithStyle, createParagraphId, CustomRangeType, DEFAULT_WORKSHEET_ROW_HEIGHT, generateRandomId, getNumfmtParseValueFilter, isDefaultFormat, isSafeUrl, numfmt, ObjectMatrix, skipParseTagNames } from '@univerjs/core';
+import {
+ createDocumentModelWithStyle,
+ createParagraphId,
+ CustomRangeType,
+ DEFAULT_WORKSHEET_ROW_HEIGHT,
+ generateRandomId,
+ getNumfmtParseValueFilter,
+ isDefaultFormat,
+ isSafeUrl,
+ numfmt,
+ ObjectMatrix,
+ skipParseTagNames,
+} from '@univerjs/core';
import { handleStringToStyle, textTrim } from '@univerjs/ui';
import { extractNodeStyle } from './parse-node-style';
import parseToDom, { convertToCellStyle, generateParagraphs } from './utils';
@@ -190,9 +202,10 @@ export class HtmlToUSMService {
} else {
cellDataStream = `${dataStream.substring(starts[i], starts[i + 1] - 1)}\r\n`;
}
+ const end = starts[i + 1] ?? dataStream.length;
const cellTextRuns: ITextRun[] = [];
textRuns?.forEach((t) => {
- if (t.st >= starts[i] && t.ed <= starts[i + 1]) {
+ if (t.st >= starts[i] && t.ed <= end) {
cellTextRuns.push({
st: t.st - starts[i],
ed: t.ed - starts[i],
@@ -202,7 +215,7 @@ export class HtmlToUSMService {
});
const cellCustomRanges: ICustomRange[] = [];
customRanges?.forEach((c) => {
- if (c.startIndex >= starts[i] && c.endIndex <= starts[i + 1]) {
+ if (c.startIndex >= starts[i] && c.endIndex <= end) {
cellCustomRanges.push({
...c,
startIndex: c.startIndex - starts[i],
@@ -238,14 +251,13 @@ export class HtmlToUSMService {
customRanges,
};
- if (!customRanges?.length) {
- valueMatrix.setValue(0, 0, convertToCellStyle({ v: dataStream }, dataStream, textRuns));
- } else {
- const p = this._generateDocumentDataModelSnapshot({
+ const cell: ICellDataWithSpanInfo = { v: dataStream };
+ if (textRuns?.length || customRanges?.length) {
+ cell.p = this._generateDocumentDataModelSnapshot({
body: singleDocBody,
});
- valueMatrix.setValue(0, 0, convertToCellStyle({ v: dataStream, p }, dataStream, textRuns));
}
+ valueMatrix.setValue(0, 0, convertToCellStyle(cell, dataStream, textRuns));
rowProperties.push({}); // TODO@yuhongz
}
diff --git a/packages/sheets-ui/src/services/clipboard/html-to-usm/paste-plugins/plugin-univer.ts b/packages/sheets-ui/src/services/clipboard/html-to-usm/paste-plugins/plugin-univer.ts
index 950b91e556..16f3a38e6a 100644
--- a/packages/sheets-ui/src/services/clipboard/html-to-usm/paste-plugins/plugin-univer.ts
+++ b/packages/sheets-ui/src/services/clipboard/html-to-usm/paste-plugins/plugin-univer.ts
@@ -22,7 +22,7 @@ import { getParagraphStyle } from '../utils';
export const UniverPastePlugin: IPastePlugin = {
name: 'univer-sheet-paste-plugin-univer',
checkPasteType(html: string) {
- return /UniverNormal/i.test(html);
+ return /<p\b[^>]*\sclass\s*=\s*["'](?:[^"']*\s)?UniverNormal(?:\s[^"']*)?["']/i.test(html);
},
stylesRules: [],
diff --git a/packages/sheets-ui/src/services/editor/__tests__/cell-editor-resize.service.spec.ts b/packages/sheets-ui/src/services/editor/__tests__/cell-editor-resize.service.spec.ts
index 98c2bc8c1e..ad0d34c9b4 100644
--- a/packages/sheets-ui/src/services/editor/__tests__/cell-editor-resize.service.spec.ts
+++ b/packages/sheets-ui/src/services/editor/__tests__/cell-editor-resize.service.spec.ts
@@ -14,6 +14,8 @@
* limitations under the License.
*/
+import type { DocumentDataModel, IDocumentData, IWorkbookData, Workbook } from '@univerjs/core';
+import type { RenderUnit } from '@univerjs/engine-render';
import {
CommandService,
ConfigService,
@@ -28,20 +30,45 @@ import {
Injector,
IUndoRedoService,
IUniverInstanceService,
+ LocaleService,
+ LocaleType,
LocalUndoRedoService,
ThemeService,
+ Univer,
UniverInstanceService,
UniverInstanceType,
VerticalAlign,
WrapStrategy,
} from '@univerjs/core';
-import { DocSelectionManagerService, DocSkeletonManagerService } from '@univerjs/docs';
-import { EditorService, IEditorService } from '@univerjs/docs-ui';
-import { IRenderManagerService, RenderManagerService } from '@univerjs/engine-render';
-import { SheetInterceptorService, SheetSkeletonService } from '@univerjs/sheets';
+import {
+ DocLayoutExecutorService,
+ DocSelectionManagerService,
+ DocSkeletonManagerService,
+ DocStateEmitService,
+ RichTextEditingMutation,
+} from '@univerjs/docs';
+import { EditorService, IEditorService, ReplaceSnapshotCommand } from '@univerjs/docs-ui';
+import {
+ CanvasColorService,
+ DeviceInputEventType,
+ Documents,
+ ICanvasColorService,
+ IRenderManagerService,
+ RenderManagerService,
+ SHEET_VIEWPORT_KEY,
+ Viewport,
+} from '@univerjs/engine-render';
+import {
+ SetWorksheetColWidthMutation,
+ SetWorksheetRowHeightMutation,
+ SheetInterceptorService,
+ SheetSkeletonService,
+ SheetsSelectionsService,
+} from '@univerjs/sheets';
import { DesktopLayoutService, ILayoutService } from '@univerjs/ui';
import { BehaviorSubject } from 'rxjs';
import { afterEach, describe, expect, it, onTestFinished, vi } from 'vitest';
+import { SetCellEditVisibleOperation } from '../../../commands/operations/cell-edit.operation';
import { EditorBridgeService, IEditorBridgeService } from '../../editor-bridge.service';
import { EmbedFloatingGeometryService, ISheetEmbedFloatingGeometryService } from '../../sheet-embed-integration.service';
import { SheetSkeletonManagerService } from '../../sheet-skeleton-manager.service';
@@ -304,6 +331,268 @@ function createResizeTestInjector() {
return injector;
}
+function createRealResizeTestBed(
+ alignment: HorizontalAlign,
+ scale: number,
+ wrapStrategy = WrapStrategy.UNSPECIFIED,
+ text = 'short'
+) {
+ vi.useFakeTimers();
+ vi.spyOn(HTMLCanvasElement.prototype, 'getContext').mockImplementation(function (this: HTMLCanvasElement) {
+ return {
+ canvas: this,
+ setTransform: vi.fn(),
+ clearRect: vi.fn(),
+ measureText: (text: string) => ({
+ width: text.length * 7,
+ fontBoundingBoxAscent: 10,
+ fontBoundingBoxDescent: 4,
+ actualBoundingBoxAscent: 10,
+ actualBoundingBoxDescent: 4,
+ }),
+ } as unknown as CanvasRenderingContext2D;
+ });
+ const univer = new Univer();
+ onTestFinished(() => {
+ vi.clearAllTimers();
+ univer.dispose();
+ vi.restoreAllMocks();
+ vi.useRealTimers();
+ });
+ const injector = univer.__getInjector();
+ injector.add([ICanvasColorService, { useClass: CanvasColorService }]);
+ injector.add([IRenderManagerService, { useClass: RenderManagerService }]);
+ injector.add([ILayoutService, { useClass: DesktopLayoutService }]);
+ injector.add([ICellEditorManagerService, { useClass: CellEditorManagerService }]);
+ injector.add([IEditorBridgeService, { useClass: EditorBridgeService }]);
+ injector.add([IEditorService, { useClass: EditorService }]);
+ injector.add([SheetSkeletonService]);
+ injector.add([SheetInterceptorService]);
+ injector.add([SheetsSelectionsService]);
+ injector.add([DocSelectionManagerService]);
+ injector.add([DocLayoutExecutorService]);
+ injector.add([DocStateEmitService]);
+ injector.add([SheetCellEditorResizeService]);
+ injector.get(LocaleService).setLocale(LocaleType.EN_US);
+ const content = document.createElement('div');
+ injector.get(ILayoutService).registerContentElement(content);
+ const workbook = univer.createUnit<IWorkbookData, Workbook>(UniverInstanceType.UNIVER_SHEET, {
+ id: 'resizing-workbook',
+ sheetOrder: ['sheet1'],
+ sheets: {
+ sheet1: {
+ id: 'sheet1',
+ rowCount: 20,
+ columnCount: 10,
+ defaultColumnWidth: 100,
+ defaultRowHeight: 28,
+ cellData: { 1: { 1: { v: text, s: { ht: alignment, tb: wrapStrategy } } } },
+ },
+ },
+ });
+ const renders = injector.get(IRenderManagerService);
+ renders.registerRenderModule(UniverInstanceType.UNIVER_SHEET, [SheetSkeletonManagerService]);
+ const sheetRender = renders.createRender(workbook.getUnitId()) as RenderUnit;
+ sheetRender.deactivate();
+ sheetRender.engine.resizeBySize(1200, 900);
+ const canvas = sheetRender.engine.getCanvasElement();
+ vi.spyOn(canvas, 'getBoundingClientRect').mockReturnValue({
+ left: 0,
+ top: 0,
+ width: 1200,
+ height: 900,
+ } as DOMRect);
+ sheetRender.scene.transformByState({ scaleX: scale, scaleY: scale });
+ injector.createInstance(Viewport, SHEET_VIEWPORT_KEY.VIEW_MAIN, sheetRender.scene, {
+ left: 0,
+ top: 0,
+ right: 0,
+ bottom: 0,
+ });
+ const skeletons = sheetRender.with(SheetSkeletonManagerService);
+ skeletons.setCurrent({ sheetId: 'sheet1' });
+ const bridge = injector.get(IEditorBridgeService);
+ bridge.setEditCell({
+ unitId: workbook.getUnitId(),
+ sheetId: 'sheet1',
+ scene: sheetRender.scene,
+ engine: sheetRender.engine,
+ primary: workbook.getActiveSheet()!.getCellInfoInMergeData(1, 1),
+ });
+ const editor = univer.createUnit<IDocumentData, DocumentDataModel>(UniverInstanceType.UNIVER_DOC, {
+ ...bridge.getEditCellState()!.documentLayoutObject.documentModel!.getSnapshot(),
+ id: DOCS_NORMAL_EDITOR_UNIT_ID_KEY,
+ });
+ const editorRender = renders.createRender(editor.getUnitId()) as RenderUnit;
+ editorRender.deactivate();
+ editorRender.addRenderDependencies([[DocSkeletonManagerService]]);
+ const documents = new Documents(editor.getUnitId(), editorRender.with(DocSkeletonManagerService).getSkeleton());
+ editorRender.mainComponent = documents;
+ editorRender.scene.addObject(documents);
+ const commands = injector.get(ICommandService);
+ [
+ SetWorksheetColWidthMutation,
+ SetWorksheetRowHeightMutation,
+ SetCellEditVisibleOperation,
+ ReplaceSnapshotCommand,
+ RichTextEditingMutation,
+ ]
+ .forEach((command) => commands.registerCommand(command));
+ commands.syncExecuteCommand(SetCellEditVisibleOperation.id, {
+ visible: true,
+ eventType: DeviceInputEventType.Keyboard,
+ unitId: workbook.getUnitId(),
+ });
+ const resize = injector.get(SheetCellEditorResizeService);
+ resize.fitTextSize();
+ const resizeCell = (width: number, height: number) => {
+ const params = {
+ unitId: workbook.getUnitId(),
+ subUnitId: 'sheet1',
+ ranges: [{ startRow: 1, endRow: 1, startColumn: 1, endColumn: 1 }],
+ };
+ commands.syncExecuteCommand(SetWorksheetColWidthMutation.id, { ...params, colWidth: width });
+ commands.syncExecuteCommand(SetWorksheetRowHeightMutation.id, { ...params, rowHeight: height });
+ skeletons.makeDirty({ sheetId: 'sheet1' });
+ skeletons.setCurrent({ sheetId: 'sheet1' });
+ resize.resizeCellEditor();
+ };
+ const getSize = () => {
+ const state = injector.get(ICellEditorManagerService).getState()!;
+ return { width: (state.endX! - state.startX!) / scale, height: (state.endY! - state.startY!) / scale };
+ };
+ const setText = (text: string) => {
+ expect(commands.syncExecuteCommand(ReplaceSnapshotCommand.id, {
+ unitId: editor.getUnitId(),
+ snapshot: { ...editor.getSnapshot(), body: { dataStream: `${text}\r\n` } },
+ textRanges: [],
+ options: {},
+ })).toBe(true);
+ resize.fitTextSize();
+ };
+ const setVisible = (visible: boolean) => {
+ commands.syncExecuteCommand(SetCellEditVisibleOperation.id, {
+ visible,
+ eventType: DeviceInputEventType.Keyboard,
+ unitId: workbook.getUnitId(),
+ });
+ if (visible) {
+ bridge.refreshEditCellPosition(true);
+ resize.fitTextSize();
+ }
+ };
+ return { bridge, editor, getSize, resizeCell, setText, setVisible, workbook };
+}
+
+describe('SheetCellEditorResizeService with real editor and worksheet providers', () => {
+ it.each([HorizontalAlign.LEFT, HorizontalAlign.CENTER, HorizontalAlign.RIGHT])(
+ 'follows repeated column and row growth and shrinkage with alignment %s',
+ (alignment) => {
+ const { bridge, editor, getSize, resizeCell } = createRealResizeTestBed(alignment, 1);
+ const body = editor.getBody()!.dataStream;
+ for (const [width, height] of [[300, 28], [140, 28], [140, 160], [140, 40], [300, 160], [60, 20], [100, 28]]) {
+ resizeCell(width, height);
+ expect(getSize()).toEqual({ width: Math.max(100, width), height: Math.max(28, height) });
+ expect(bridge.isVisible().visible).toBe(true);
+ expect(editor.getBody()!.dataStream).toBe(body);
+ }
+ }
+ );
+
+ it.each([0.75, 1.5])('synchronizes resized cell dimensions at zoom %s', (scale) => {
+ const { getSize, resizeCell } = createRealResizeTestBed(HorizontalAlign.LEFT, scale);
+ resizeCell(300, 160);
+ expect(getSize()).toEqual({ width: 300, height: 160 });
+ resizeCell(100, 28);
+ expect(getSize()).toEqual({ width: 100, height: 28 });
+ });
+
+ it.each([HorizontalAlign.LEFT, HorizontalAlign.CENTER, HorizontalAlign.RIGHT])(
+ 'keeps overflowing text visible when a larger cell shrinks with alignment %s',
+ (alignment) => {
+ const text = 'This text is wider than the cell';
+ const { editor, getSize, resizeCell } = createRealResizeTestBed(alignment, 1, WrapStrategy.UNSPECIFIED, text);
+ const textSize = getSize();
+ expect(textSize.width).toBeGreaterThan(100);
+ resizeCell(400, 180);
+ expect(getSize()).toEqual({ width: 400, height: 180 });
+ resizeCell(100, 28);
+ expect(getSize()).toEqual(textSize);
+ expect(editor.getBody()!.dataStream).toContain(text);
+ }
+ );
+
+ it('keeps multiline text visible when the row shrinks below the text height', () => {
+ const text = 'one\ntwo\nthree\nfour';
+ const { getSize, resizeCell } = createRealResizeTestBed(HorizontalAlign.LEFT, 1, WrapStrategy.WRAP, text);
+ const textSize = getSize();
+ expect(textSize.height).toBeGreaterThan(28);
+ resizeCell(300, 180);
+ expect(getSize()).toEqual({ width: 300, height: 180 });
+ resizeCell(100, 28);
+ expect(getSize()).toEqual(textSize);
+ });
+
+ it.each([HorizontalAlign.LEFT, HorizontalAlign.CENTER, HorizontalAlign.RIGHT])(
+ 'covers the original worksheet text after deleting and resizing with alignment %s',
+ (alignment) => {
+ const text = 'Original overflowing text';
+ const { editor, getSize, resizeCell, setText, workbook } = createRealResizeTestBed(
+ alignment,
+ 1,
+ WrapStrategy.UNSPECIFIED,
+ text
+ );
+ const initialSize = getSize();
+ expect(initialSize.width).toBeGreaterThan(100);
+ setText('x');
+ resizeCell(400, 180);
+ expect(getSize()).toEqual({ width: 400, height: 180 });
+ resizeCell(60, 20);
+ expect(getSize()).toEqual(initialSize);
+ expect(editor.getBody()!.dataStream).toBe('x\r\n');
+ expect(workbook.getActiveSheet()!.getCell(1, 1)!.v).toBe(text);
+ }
+ );
+
+ it.each([0.75, 1, 1.5])('retains the initial multiline editor height after deleting and resizing at zoom %s', (scale) => {
+ const text = 'one\ntwo\nthree\nfour';
+ const { getSize, resizeCell, setText } = createRealResizeTestBed(HorizontalAlign.LEFT, scale, WrapStrategy.WRAP, text);
+ const initialSize = getSize();
+ expect(initialSize.height).toBeGreaterThan(28);
+ setText('x');
+ resizeCell(300, 180);
+ expect(getSize()).toEqual({ width: 300, height: 180 });
+ resizeCell(60, 20);
+ expect(getSize()).toEqual(initialSize);
+ });
+
+ it('captures a new minimum size after closing and reopening the editor', () => {
+ const { getSize, resizeCell, setVisible } = createRealResizeTestBed(HorizontalAlign.LEFT, 1);
+ resizeCell(300, 160);
+ setVisible(false);
+ resizeCell(60, 28);
+ setVisible(true);
+ expect(getSize()).toEqual({ width: 60, height: 28 });
+ resizeCell(300, 160);
+ resizeCell(40, 20);
+ expect(getSize()).toEqual({ width: 60, height: 28 });
+ });
+
+ it('recalculates wrapped text height without shrinking below the initial editor height', () => {
+ const text = 'one two three four five six seven eight';
+ const { getSize, resizeCell } = createRealResizeTestBed(HorizontalAlign.LEFT, 1, WrapStrategy.WRAP, text);
+ const initialSize = getSize();
+ resizeCell(320, 28);
+ const wideSize = getSize();
+ expect(wideSize.height).toBe(initialSize.height);
+ resizeCell(60, 28);
+ expect(getSize().height).toBeGreaterThan(wideSize.height);
+ resizeCell(320, 28);
+ expect(getSize()).toEqual(wideSize);
+ });
+});
+
describe('SheetCellEditorResizeService', () => {
afterEach(() => {
vi.unstubAllGlobals();
diff --git a/packages/sheets-ui/src/services/editor/cell-editor-resize.service.ts b/packages/sheets-ui/src/services/editor/cell-editor-resize.service.ts
index 5adfb64808..c1149bd734 100644
--- a/packages/sheets-ui/src/services/editor/cell-editor-resize.service.ts
+++ b/packages/sheets-ui/src/services/editor/cell-editor-resize.service.ts
@@ -58,6 +58,10 @@ export class SheetCellEditorResizeService extends Disposable {
private _editorHeight = 0;
+ private _initialEditorSize: Nullable<{ width: number; height: number }> = null;
+
+ private _cellSize: Nullable<{ width: number; height: number }> = null;
+
constructor(
@ILayoutService private readonly _layoutService: ILayoutService,
@ICellEditorManagerService private readonly _cellEditorManagerService: ICellEditorManagerService,
@@ -73,6 +77,8 @@ export class SheetCellEditorResizeService extends Disposable {
if (!visible) {
this._editorWidth = 0;
this._editorHeight = 0;
+ this._initialEditorSize = null;
+ this._cellSize = null;
}
}));
}
@@ -107,6 +113,8 @@ export class SheetCellEditorResizeService extends Disposable {
const { position, documentLayoutObject, canvasOffset, scaleX, scaleY } = param;
const { startX, startY, endX, endY } = position;
+ const cellWidth = endX - startX;
+ const cellHeight = endY - startY;
const documentDataModel = this._univerInstanceService.getUnit<DocumentDataModel>(DOCS_NORMAL_EDITOR_UNIT_ID_KEY, UniverInstanceType.UNIVER_DOC);
if (documentDataModel == null) {
@@ -115,6 +123,7 @@ export class SheetCellEditorResizeService extends Disposable {
const documentSkeleton = this._getEditorSkeleton();
if (!documentSkeleton) return;
+ this._syncCellSize(cellWidth / scaleX, cellHeight / scaleY);
// Cell editors are embedded docs with unspecified compatibility mode. Reset before
// measuring so stale page width from a previous resize does not leak into this editor.
documentSkeleton.resetInitialWidth();
@@ -132,8 +141,6 @@ export class SheetCellEditorResizeService extends Disposable {
const { verticalAlign, horizontalAlign, paddingData, fill } = documentLayoutObject;
actualWidth = actualWidth + (paddingData.l ?? 0) * scaleX + (paddingData.r ?? 0) * scaleX;
actualHeight = actualHeight + (paddingData.t ?? 0) * scaleY + (paddingData.b ?? 0) * scaleY;
- const cellWidth = endX - startX;
- const cellHeight = endY - startY;
const contentWidth = cellWidth < actualWidth ? Math.ceil(actualWidth) : cellWidth;
const contentHeight = cellHeight < actualHeight ? Math.ceil(actualHeight) : cellHeight;
const editorWidth = Math.max(contentWidth, Math.min(this._editorWidth * scaleX, info.maxSize.width));
@@ -177,6 +184,18 @@ export class SheetCellEditorResizeService extends Disposable {
);
}
+ private _syncCellSize(width: number, height: number) {
+ if (this._cellSize && (
+ Math.abs(this._cellSize.width - width) > 1e-6 ||
+ Math.abs(this._cellSize.height - height) > 1e-6
+ )) {
+ // Refit resized cells while still covering the original worksheet text until the edit is submitted.
+ this._editorWidth = this._initialEditorSize?.width ?? 0;
+ this._editorHeight = this._initialEditorSize?.height ?? 0;
+ }
+ this._cellSize = { width, height };
+ }
+
/**
* Mainly used to pre-calculate the width of the editor,
* to determine whether it needs to be automatically widened.
@@ -200,9 +219,10 @@ export class SheetCellEditorResizeService extends Disposable {
const maxSize = this._getEditorMaxSize(actualRangeWithCoord, canvasOffset, documentLayoutObject.horizontalAlign);
if (!maxSize) return;
+ // Measure content without alignment margins left over from the previous editor size.
+ documentDataModel?.updateDocumentDataMargin({ l: paddingData.l, t: paddingData.t });
if (wrapStrategy === WrapStrategy.WRAP && angle === 0) {
documentDataModel?.updateDocumentDataPageSize((endX - startX) / scaleX);
- documentDataModel?.updateDocumentDataMargin({ l: paddingData.l, t: paddingData.t });
documentSkeleton.calculate();
const { actualWidth, actualHeight } = documentSkeleton.getActualSize();
// The skeleton obtains the original volume, which needs to be multiplied by the magnification factor.
@@ -331,6 +351,9 @@ export class SheetCellEditorResizeService extends Disposable {
// Keep the visible extent for this edit only; skeleton measurements must still discard stale layout width.
this._editorWidth = Math.max(this._editorWidth, editorWidth / scaleX);
this._editorHeight = Math.max(this._editorHeight, physicHeight / scaleY);
+ if (!this._initialEditorSize && this._editorBridgeService.isVisible().visible) {
+ this._initialEditorSize = { width: editorWidth / scaleX, height: physicHeight / scaleY };
+ }
this._addBackground(editorScene, editorWidth / scaleX, editorHeight / scaleY, fill);
diff --git a/packages/sheets-ui/src/views/defined-name/DefinedName.tsx b/packages/sheets-ui/src/views/defined-name/DefinedName.tsx
index c84b5b8e4f..c92b20c1de 100644
--- a/packages/sheets-ui/src/views/defined-name/DefinedName.tsx
+++ b/packages/sheets-ui/src/views/defined-name/DefinedName.tsx
@@ -109,7 +109,9 @@ export function DefinedName({ disable }: { disable: boolean }) {
const subUnitId = worksheet.getSheetId();
getSelections(worksheet, refString).then((selections) => {
- if (!selections) return;
+ if (!selections) {
+ return;
+ }
commandService.executeCommand(SetSelectionsOperation.id, {
unitId,
@@ -168,7 +170,9 @@ export function DefinedName({ disable }: { disable: boolean }) {
setIsInputEvent(true);
if (!value) {
- if (open) setOpen(false);
+ if (open) {
+ setOpen(false);
+ }
return;
}
@@ -239,7 +243,9 @@ export function DefinedName({ disable }: { disable: boolean }) {
}
function handleKeyDown(e: KeyboardEvent<HTMLInputElement>) {
- if (disable) return;
+ if (disable) {
+ return;
+ }
if (e.key === 'Enter') {
const handled = confirm();
@@ -260,7 +266,9 @@ export function DefinedName({ disable }: { disable: boolean }) {
}
async function getSelections(worksheet: Worksheet, formulaOrRefString: string) {
- if (!worksheet) return;
+ if (!worksheet) {
+ return;
+ }
const unitRange = deserializeRangeWithSheet(formulaOrRefString.trim());
@@ -287,6 +295,11 @@ export function DefinedName({ disable }: { disable: boolean }) {
<div
ref={nameBoxRef}
data-u-comp="defined-name"
+ onMouseDown={(e) => {
+ if (disable) {
+ e.preventDefault();
+ }
+ }}
className={`
univer-relative univer-box-border univer-flex univer-h-full univer-w-24 univer-border-r-gray-200
univer-py-1.5 univer-transition-all
@@ -303,6 +316,7 @@ export function DefinedName({ disable }: { disable: boolean }) {
'univer-cursor-not-allowed': disable,
})}
type="text"
+ disabled={disable}
value={inputValue}
onChange={handleChangeSelection}
onKeyDown={handleKeyDown}
@@ -322,7 +336,7 @@ export function DefinedName({ disable }: { disable: boolean }) {
</div>
)}
disabled={disable}
- open={open}
+ open={!disable && open}
onOpenChange={setOpen}
onOpenAutoFocus={(e) => e.preventDefault()}
>
diff --git a/packages/sheets-ui/src/views/formula-bar/FormulaBar.tsx b/packages/sheets-ui/src/views/formula-bar/FormulaBar.tsx
index cd49cafae0..93c8119779 100644
--- a/packages/sheets-ui/src/views/formula-bar/FormulaBar.tsx
+++ b/packages/sheets-ui/src/views/formula-bar/FormulaBar.tsx
@@ -310,7 +310,7 @@ export function FormulaBar(props: IProps) {
})}
>
<div className="univer-relative univer-box-border univer-h-full univer-w-[100px]">
- <DefinedName disable={disableDefinedName ?? editDisable} />
+ <DefinedName disable={iconActivated || (disableDefinedName ?? editDisable)} />
</div>
<div className="univer-flex univer-size-full">
diff --git a/packages/sheets-ui/src/views/formula-bar/__tests__/FormulaBar.spec.tsx b/packages/sheets-ui/src/views/formula-bar/__tests__/FormulaBar.spec.tsx
index 8cc5262dd0..8e61f8db48 100644
--- a/packages/sheets-ui/src/views/formula-bar/__tests__/FormulaBar.spec.tsx
+++ b/packages/sheets-ui/src/views/formula-bar/__tests__/FormulaBar.spec.tsx
@@ -35,7 +35,8 @@ import {
Univer,
UniverInstanceType,
} from '@univerjs/core';
-import { IEditorService } from '@univerjs/docs-ui';
+import { DocSelectionManagerService } from '@univerjs/docs';
+import { EditorService, IEditorService } from '@univerjs/docs-ui';
import {
DefinedNamesService,
FunctionService,
@@ -45,15 +46,27 @@ import {
LexerTreeBuilder,
SuperTableService,
} from '@univerjs/engine-formula';
-import { DeviceInputEventType } from '@univerjs/engine-render';
+import { DeviceInputEventType, IRenderManagerService, RenderManagerService } from '@univerjs/engine-render';
import {
RangeProtectionCache,
RangeProtectionRuleModel,
+ SheetInterceptorService,
SheetPermissionCheckController,
+ SheetSkeletonService,
SheetsSelectionsService,
WorksheetProtectionRuleModel,
} from '@univerjs/sheets';
-import { ComponentManager, ILayoutService, IUIPartsService, KeyCode, RediContext, UIPartsService } from '@univerjs/ui';
+import {
+ ComponentManager,
+ DesktopLayoutService,
+ DesktopSidebarService,
+ ILayoutService,
+ ISidebarService,
+ IUIPartsService,
+ KeyCode,
+ RediContext,
+ UIPartsService,
+} from '@univerjs/ui';
import { act } from 'react';
import { createRoot } from 'react-dom/client';
import { BehaviorSubject, EMPTY } from 'rxjs';
@@ -63,7 +76,7 @@ import { EMBEDDING_FORMULA_EDITOR_COMPONENT_KEY } from '../../../common/keys';
import { SHEETS_UI_PLUGIN_CONFIG_KEY } from '../../../config/config';
import { MOBILE_FORMULA_BAR_SUBMIT_COMMAND_ID } from '../../../consts/mobile-context';
import enUS from '../../../locale/en-US';
-import { IEditorBridgeService } from '../../../services/editor-bridge.service';
+import { EditorBridgeService, IEditorBridgeService } from '../../../services/editor-bridge.service';
import { FormulaEditorManagerService, IFormulaEditorManagerService } from '../../../services/editor/formula-editor-manager.service';
import { MobileFormulaBar } from '../../mobile/formula-bar/MobileFormulaBar';
import { MobileFormulaBarOverlays } from '../../mobile/formula-bar/MobileFormulaBarControls';
@@ -257,7 +270,7 @@ function createCellEditState(): ICellEditorState {
};
}
-function createFormulaBarTestBed(cellStyle?: IStyleData) {
+function createFormulaBarTestBed(cellStyle?: IStyleData, realEditorServices = false) {
const originalResizeObserver = globalThis.ResizeObserver;
globalThis.ResizeObserver = TestResizeObserver as typeof ResizeObserver;
@@ -279,9 +292,20 @@ function createFormulaBarTestBed(cellStyle?: IStyleData) {
injector.add([RangeProtectionCache, { useClass: RangeProtectionCache }]);
injector.add([SheetPermissionCheckController, { useClass: SheetPermissionCheckController }]);
injector.add([IFormulaEditorManagerService, { useClass: FormulaEditorManagerService }]);
- injector.add([IEditorBridgeService, { useClass: TestEditorBridgeService as never }]);
- injector.add([ILayoutService, { useClass: TestLayoutService as never }]);
- injector.add([IEditorService, { useClass: TestEditorService as never }]);
+ if (realEditorServices) {
+ injector.add([SheetInterceptorService]);
+ injector.add([SheetSkeletonService]);
+ injector.add([IRenderManagerService, { useClass: RenderManagerService }]);
+ injector.add([DocSelectionManagerService]);
+ injector.add([IEditorBridgeService, { useClass: EditorBridgeService }]);
+ injector.add([ILayoutService, { useClass: DesktopLayoutService }]);
+ injector.add([IEditorService, { useClass: EditorService }]);
+ injector.add([ISidebarService, { useClass: DesktopSidebarService }]);
+ } else {
+ injector.add([IEditorBridgeService, { useClass: TestEditorBridgeService as never }]);
+ injector.add([ILayoutService, { useClass: TestLayoutService as never }]);
+ injector.add([IEditorService, { useClass: TestEditorService as never }]);
+ }
const workbook = univer.createUnit<IWorkbookData, Workbook>(
UniverInstanceType.UNIVER_SHEET,
createWorkbookData(cellStyle)
@@ -302,12 +326,19 @@ function createFormulaBarTestBed(cellStyle?: IStyleData) {
});
const editorBridgeService = injector.get(IEditorBridgeService) as TestEditorBridgeService;
- editorBridgeService.setCurrentEditCell(createCellEditState());
- editorBridgeService.changeVisible({
+ if (!realEditorServices) {
+ editorBridgeService.setCurrentEditCell(createCellEditState());
+ }
+ const visibleParams: IEditorBridgeServiceVisibleParam = {
visible: true,
eventType: DeviceInputEventType.PointerDown,
unitId: UNIT_ID,
- });
+ };
+ if (realEditorServices) {
+ commandService.syncExecuteCommand(SetCellEditVisibleOperation.id, visibleParams);
+ } else {
+ editorBridgeService.changeVisible(visibleParams);
+ }
return {
univer,
@@ -379,6 +410,57 @@ describe('FormulaBar', () => {
vi.unstubAllGlobals();
});
+ it.each([
+ DeviceInputEventType.Dblclick,
+ DeviceInputEventType.Keyboard,
+ DeviceInputEventType.PointerDown,
+ ])('disables the name box during editing and restores it afterwards (%s)', async (eventType) => {
+ currentBed = createFormulaBarTestBed(undefined, true);
+ const commandService = currentBed.injector.get(ICommandService);
+ commandService.syncExecuteCommand(SetCellEditVisibleOperation.id, { visible: true, eventType, unitId: UNIT_ID });
+ const rendered = renderWithDependencies(<FormulaBar disableDefinedName={false} />, currentBed.injector);
+ root = rendered.root;
+ container = rendered.container;
+ const nameBox = rendered.container.querySelector('[data-u-comp="defined-name"]');
+ const input = nameBox?.querySelector('input');
+ const trigger = nameBox?.querySelector('a');
+ if (!(input instanceof HTMLInputElement) || !(trigger instanceof HTMLElement)) {
+ throw new TypeError('Name box controls not rendered');
+ }
+
+ expect(input.disabled).toBe(true);
+ const editorInput = document.createElement('textarea');
+ rendered.container.appendChild(editorInput);
+ editorInput.focus();
+ input.focus();
+ expect(document.activeElement).toBe(editorInput);
+
+ const mouseDown = new MouseEvent('mousedown', { bubbles: true, cancelable: true });
+ await act(async () => {
+ trigger.dispatchEvent(mouseDown);
+ trigger.click();
+ input.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter', bubbles: true }));
+ });
+ expect(mouseDown.defaultPrevented).toBe(true);
+ expect(document.activeElement).toBe(editorInput);
+ expect(document.querySelector('[data-u-comp="defined-name-overlay"]')).toBeNull();
+ expect(currentBed.injector.get(IEditorBridgeService).isVisible().visible).toBe(true);
+
+ await act(async () => {
+ commandService.syncExecuteCommand(SetCellEditVisibleOperation.id, {
+ visible: false,
+ eventType: DeviceInputEventType.Keyboard,
+ keycode: KeyCode.ENTER,
+ unitId: UNIT_ID,
+ });
+ });
+ expect(input.disabled).toBe(false);
+ input.focus();
+ expect(document.activeElement).toBe(input);
+ await clickElement(trigger);
+ expect(document.querySelector('[data-u-comp="defined-name-overlay"]')).not.toBeNull();
+ });
+
it('replays the selected cell after the lazy mobile formula editor mounts', async () => {
vi.stubGlobal('requestAnimationFrame', (callback: FrameRequestCallback) => {
callback(0);
diff --git a/packages/thread-comment-ui/src/locale/ar-SA.ts b/packages/thread-comment-ui/src/locale/ar-SA.ts
index 3a058e0f4c..3afa0b3474 100644
--- a/packages/thread-comment-ui/src/locale/ar-SA.ts
+++ b/packages/thread-comment-ui/src/locale/ar-SA.ts
@@ -33,6 +33,8 @@ const locale: typeof enUS = {
save: 'حفظ',
},
item: {
+ markResolved: 'وضع علامة كمحلول',
+ markUnresolved: 'وضع علامة كغير محلول',
edit: 'تحرير',
delete: 'حذف هذا التعليق',
more: 'المزيد',
diff --git a/packages/thread-comment-ui/src/locale/ca-ES.ts b/packages/thread-comment-ui/src/locale/ca-ES.ts
index b9141fe9ec..c593116390 100644
--- a/packages/thread-comment-ui/src/locale/ca-ES.ts
+++ b/packages/thread-comment-ui/src/locale/ca-ES.ts
@@ -33,6 +33,8 @@ const locale: typeof enUS = {
save: 'Desa',
},
item: {
+ markResolved: 'Marca com a resolt',
+ markUnresolved: 'Marca com a no resolt',
edit: 'Edita',
delete: 'Elimina aquest comentari',
more: 'Més',
diff --git a/packages/thread-comment-ui/src/locale/de-DE.ts b/packages/thread-comment-ui/src/locale/de-DE.ts
index 288f0d99f2..6d02844962 100644
--- a/packages/thread-comment-ui/src/locale/de-DE.ts
+++ b/packages/thread-comment-ui/src/locale/de-DE.ts
@@ -33,6 +33,8 @@ const locale: typeof enUS = {
save: 'Speichern',
},
item: {
+ markResolved: 'Als gelöst markieren',
+ markUnresolved: 'Als ungelöst markieren',
edit: 'Bearbeiten',
delete: 'Diesen Kommentar löschen',
more: 'Mehr',
diff --git a/packages/thread-comment-ui/src/locale/en-US.ts b/packages/thread-comment-ui/src/locale/en-US.ts
index f310e12c06..88171d986e 100644
--- a/packages/thread-comment-ui/src/locale/en-US.ts
+++ b/packages/thread-comment-ui/src/locale/en-US.ts
@@ -31,6 +31,8 @@ const locale = {
save: 'Save',
},
item: {
+ markResolved: 'Mark as resolved',
+ markUnresolved: 'Mark as unresolved',
edit: 'Edit',
delete: 'Delete This Comment',
more: 'More',
diff --git a/packages/thread-comment-ui/src/locale/es-ES.ts b/packages/thread-comment-ui/src/locale/es-ES.ts
index e2d18e2caa..2a5b8b3e3e 100644
--- a/packages/thread-comment-ui/src/locale/es-ES.ts
+++ b/packages/thread-comment-ui/src/locale/es-ES.ts
@@ -33,6 +33,8 @@ const locale: typeof enUS = {
save: 'Guardar',
},
item: {
+ markResolved: 'Marcar como resuelto',
+ markUnresolved: 'Marcar como no resuelto',
edit: 'Editar',
delete: 'Eliminar este comentario',
more: 'Más',
diff --git a/packages/thread-comment-ui/src/locale/fa-IR.ts b/packages/thread-comment-ui/src/locale/fa-IR.ts
index fdbe21de39..c87cc774d3 100644
--- a/packages/thread-comment-ui/src/locale/fa-IR.ts
+++ b/packages/thread-comment-ui/src/locale/fa-IR.ts
@@ -33,6 +33,8 @@ const locale: typeof enUS = {
save: 'ذخیره',
},
item: {
+ markResolved: 'علامت‌گذاری به‌عنوان حل‌شده',
+ markUnresolved: 'علامت‌گذاری به‌عنوان حل‌نشده',
edit: 'ویرایش',
delete: 'حذف این نظر',
more: 'بیشتر',
diff --git a/packages/thread-comment-ui/src/locale/fr-FR.ts b/packages/thread-comment-ui/src/locale/fr-FR.ts
index b810e3c881..95186e6a4b 100644
--- a/packages/thread-comment-ui/src/locale/fr-FR.ts
+++ b/packages/thread-comment-ui/src/locale/fr-FR.ts
@@ -33,6 +33,8 @@ const locale: typeof enUS = {
save: 'Enregistrer',
},
item: {
+ markResolved: 'Marquer comme résolu',
+ markUnresolved: 'Marquer comme non résolu',
edit: 'Modifier',
delete: 'Supprimer ce commentaire',
more: 'Plus',
diff --git a/packages/thread-comment-ui/src/locale/id-ID.ts b/packages/thread-comment-ui/src/locale/id-ID.ts
index c7b65b90fe..52af10529f 100644
--- a/packages/thread-comment-ui/src/locale/id-ID.ts
+++ b/packages/thread-comment-ui/src/locale/id-ID.ts
@@ -33,6 +33,8 @@ const locale: typeof enUS = {
save: 'Simpan',
},
item: {
+ markResolved: 'Tandai sebagai terselesaikan',
+ markUnresolved: 'Tandai sebagai belum terselesaikan',
edit: 'Edit',
delete: 'Hapus Komentar Ini',
more: 'Lebih Banyak',
diff --git a/packages/thread-comment-ui/src/locale/it-IT.ts b/packages/thread-comment-ui/src/locale/it-IT.ts
index 46fc131e22..75b0add32c 100644
--- a/packages/thread-comment-ui/src/locale/it-IT.ts
+++ b/packages/thread-comment-ui/src/locale/it-IT.ts
@@ -33,6 +33,8 @@ const locale: typeof enUS = {
save: 'Salva',
},
item: {
+ markResolved: 'Segna come risolto',
+ markUnresolved: 'Segna come non risolto',
edit: 'Modifica',
delete: 'Elimina questo commento',
more: 'Altro',
diff --git a/packages/thread-comment-ui/src/locale/ja-JP.ts b/packages/thread-comment-ui/src/locale/ja-JP.ts
index ab63d4627b..c08242395d 100644
--- a/packages/thread-comment-ui/src/locale/ja-JP.ts
+++ b/packages/thread-comment-ui/src/locale/ja-JP.ts
@@ -33,6 +33,8 @@ const locale: typeof enUS = {
save: '保存',
},
item: {
+ markResolved: '解決済みにする',
+ markUnresolved: '未解決にする',
edit: '編集',
delete: 'コメントを削除',
more: 'もっと見る',
diff --git a/packages/thread-comment-ui/src/locale/ko-KR.ts b/packages/thread-comment-ui/src/locale/ko-KR.ts
index 173fb8e75e..feb1269502 100644
--- a/packages/thread-comment-ui/src/locale/ko-KR.ts
+++ b/packages/thread-comment-ui/src/locale/ko-KR.ts
@@ -33,6 +33,8 @@ const locale: typeof enUS = {
save: '저장',
},
item: {
+ markResolved: '해결됨으로 표시',
+ markUnresolved: '미해결로 표시',
edit: '편집',
delete: '댓글 삭제',
more: '더 보기',
diff --git a/packages/thread-comment-ui/src/locale/pl-PL.ts b/packages/thread-comment-ui/src/locale/pl-PL.ts
index c0f3daf1e3..6838d80026 100644
--- a/packages/thread-comment-ui/src/locale/pl-PL.ts
+++ b/packages/thread-comment-ui/src/locale/pl-PL.ts
@@ -33,6 +33,8 @@ const locale: typeof enUS = {
save: 'Zapisz',
},
item: {
+ markResolved: 'Oznacz jako rozwiązane',
+ markUnresolved: 'Oznacz jako nierozwiązane',
edit: 'Edytuj',
delete: 'Usuń ten komentarz',
more: 'Więcej',
diff --git a/packages/thread-comment-ui/src/locale/pt-BR.ts b/packages/thread-comment-ui/src/locale/pt-BR.ts
index 7cbc878a5c..4ea54b97fa 100644
--- a/packages/thread-comment-ui/src/locale/pt-BR.ts
+++ b/packages/thread-comment-ui/src/locale/pt-BR.ts
@@ -33,6 +33,8 @@ const locale: typeof enUS = {
save: 'Salvar',
},
item: {
+ markResolved: 'Marcar como resolvido',
+ markUnresolved: 'Marcar como não resolvido',
edit: 'Editar',
delete: 'Excluir Este Comentário',
more: 'Mais',
diff --git a/packages/thread-comment-ui/src/locale/ru-RU.ts b/packages/thread-comment-ui/src/locale/ru-RU.ts
index 87cf90dabc..a8d80d0a54 100644
--- a/packages/thread-comment-ui/src/locale/ru-RU.ts
+++ b/packages/thread-comment-ui/src/locale/ru-RU.ts
@@ -33,6 +33,8 @@ const locale: typeof enUS = {
save: 'Сохранить',
},
item: {
+ markResolved: 'Отметить как решённое',
+ markUnresolved: 'Отметить как нерешённое',
edit: 'Редактировать',
delete: 'Удалить',
more: 'Больше',
diff --git a/packages/thread-comment-ui/src/locale/sk-SK.ts b/packages/thread-comment-ui/src/locale/sk-SK.ts
index 1120c41cc4..d5b020a372 100644
--- a/packages/thread-comment-ui/src/locale/sk-SK.ts
+++ b/packages/thread-comment-ui/src/locale/sk-SK.ts
@@ -33,6 +33,8 @@ const locale: typeof enUS = {
save: 'Uložiť',
},
item: {
+ markResolved: 'Označiť ako vyriešené',
+ markUnresolved: 'Označiť ako nevyriešené',
edit: 'Upraviť',
delete: 'Odstrániť tento komentár',
more: 'Viac',
diff --git a/packages/thread-comment-ui/src/locale/vi-VN.ts b/packages/thread-comment-ui/src/locale/vi-VN.ts
index 1f14045ae0..ef16fd4ad6 100644
--- a/packages/thread-comment-ui/src/locale/vi-VN.ts
+++ b/packages/thread-comment-ui/src/locale/vi-VN.ts
@@ -33,6 +33,8 @@ const locale: typeof enUS = {
save: 'Lưu',
},
item: {
+ markResolved: 'Đánh dấu là đã giải quyết',
+ markUnresolved: 'Đánh dấu là chưa giải quyết',
edit: 'Chỉnh sửa',
delete: 'Xóa',
more: 'Thêm',
diff --git a/packages/thread-comment-ui/src/locale/zh-CN.ts b/packages/thread-comment-ui/src/locale/zh-CN.ts
index 0606867e9d..53568781b4 100644
--- a/packages/thread-comment-ui/src/locale/zh-CN.ts
+++ b/packages/thread-comment-ui/src/locale/zh-CN.ts
@@ -33,6 +33,8 @@ const locale: typeof enUS = {
save: '保存',
},
item: {
+ markResolved: '标记为已解决',
+ markUnresolved: '标记为未解决',
edit: '编辑',
delete: '删除',
more: '更多',
diff --git a/packages/thread-comment-ui/src/locale/zh-HK.ts b/packages/thread-comment-ui/src/locale/zh-HK.ts
index 038d44db2b..bf88cfa9ed 100644
--- a/packages/thread-comment-ui/src/locale/zh-HK.ts
+++ b/packages/thread-comment-ui/src/locale/zh-HK.ts
@@ -33,6 +33,8 @@ const locale: typeof enUS = {
save: '儲存',
},
item: {
+ markResolved: '標記為已解決',
+ markUnresolved: '標記為未解決',
edit: '編輯',
delete: '刪除',
more: '更多',
diff --git a/packages/thread-comment-ui/src/locale/zh-TW.ts b/packages/thread-comment-ui/src/locale/zh-TW.ts
index 038d44db2b..bf88cfa9ed 100644
--- a/packages/thread-comment-ui/src/locale/zh-TW.ts
+++ b/packages/thread-comment-ui/src/locale/zh-TW.ts
@@ -33,6 +33,8 @@ const locale: typeof enUS = {
save: '儲存',
},
item: {
+ markResolved: '標記為已解決',
+ markUnresolved: '標記為未解決',
edit: '編輯',
delete: '刪除',
more: '更多',
diff --git a/packages/thread-comment-ui/src/views/ThreadCommentTree.tsx b/packages/thread-comment-ui/src/views/ThreadCommentTree.tsx
index 6062014773..75025b02ba 100644
--- a/packages/thread-comment-ui/src/views/ThreadCommentTree.tsx
+++ b/packages/thread-comment-ui/src/views/ThreadCommentTree.tsx
@@ -516,6 +516,10 @@ export const ThreadCommentTree = (props: IThreadCommentTreeProps) => {
const subUnitName = getSubUnitName(comments?.root.subUnitId ?? subUnitId);
const editorVisible = showEdit && !editingId && !resolved;
const title = `${displayRef ?? refStr ?? comments?.root.ref ?? ''}${subUnitName ? ' · ' : ''}${subUnitName}`;
+ const resolveLabel = localeService.t<LocaleKey>(resolved
+ ? 'thread-comment-ui.item.markUnresolved'
+ : 'thread-comment-ui.item.markResolved');
+ const deleteLabel = localeService.t<LocaleKey>('thread-comment-ui.item.delete');
const threadCommentEditorId = getThreadCommentEditorId({
location,
unitId,
@@ -585,42 +589,44 @@ export const ThreadCommentTree = (props: IThreadCommentTreeProps) => {
</div>
{!!comments && (
<div className="univer-flex univer-flex-shrink-0 univer-flex-grow-0 univer-flex-row">
- <button
- type="button"
- aria-label={localeService.t<LocaleKey>(resolved
- ? 'thread-comment-ui.filter.status.unsolved'
- : 'thread-comment-ui.filter.status.resolved')}
- className={clsx(`
- univer-ml-1 univer-inline-flex univer-size-6 univer-cursor-pointer univer-items-center
- univer-justify-center univer-rounded-[3px] univer-border-0 univer-bg-transparent
- univer-p-0 univer-text-base
- hover:univer-bg-gray-50
- rtl:univer-ml-0 rtl:univer-mr-1
- dark:hover:!univer-bg-gray-800
- `, {
- 'univer-text-green-500': resolved,
- })}
- onClick={handleResolve}
- >
- {resolved ? <SuccessIcon /> : <SuccessOutlineIcon />}
- </button>
+ <Tooltip title={resolveLabel}>
+ <button
+ type="button"
+ aria-label={resolveLabel}
+ className={clsx(`
+ univer-ml-1 univer-inline-flex univer-size-6 univer-cursor-pointer univer-items-center
+ univer-justify-center univer-rounded-[3px] univer-border-0 univer-bg-transparent
+ univer-p-0 univer-text-base
+ hover:univer-bg-gray-50
+ rtl:univer-ml-0 rtl:univer-mr-1
+ dark:hover:!univer-bg-gray-800
+ `, {
+ 'univer-text-green-500': resolved,
+ })}
+ onClick={handleResolve}
+ >
+ {resolved ? <SuccessIcon /> : <SuccessOutlineIcon />}
+ </button>
+ </Tooltip>
{currentUser?.userID === comments.root.personId
? (
- <button
- type="button"
- aria-label={localeService.t<LocaleKey>('thread-comment-ui.item.delete')}
- className={`
- univer-ml-1 univer-inline-flex univer-size-6 univer-cursor-pointer
- univer-items-center univer-justify-center univer-rounded-[3px] univer-border-0
- univer-bg-transparent univer-p-0 univer-text-base
- hover:univer-bg-gray-50
- rtl:univer-ml-0 rtl:univer-mr-1
- dark:hover:!univer-bg-gray-800
- `}
- onClick={handleDeleteRoot}
- >
- <DeleteIcon />
- </button>
+ <Tooltip title={deleteLabel}>
+ <button
+ type="button"
+ aria-label={deleteLabel}
+ className={`
+ univer-ml-1 univer-inline-flex univer-size-6 univer-cursor-pointer
+ univer-items-center univer-justify-center univer-rounded-[3px] univer-border-0
+ univer-bg-transparent univer-p-0 univer-text-base
+ hover:univer-bg-gray-50
+ rtl:univer-ml-0 rtl:univer-mr-1
+ dark:hover:!univer-bg-gray-800
+ `}
+ onClick={handleDeleteRoot}
+ >
+ <DeleteIcon />
+ </button>
+ </Tooltip>
)
: null}
</div>
diff --git a/packages/thread-comment-ui/src/views/__tests__/ThreadCommentTree.spec.tsx b/packages/thread-comment-ui/src/views/__tests__/ThreadCommentTree.spec.tsx
index bd0b5df975..d23e1a6b07 100644
--- a/packages/thread-comment-ui/src/views/__tests__/ThreadCommentTree.spec.tsx
+++ b/packages/thread-comment-ui/src/views/__tests__/ThreadCommentTree.spec.tsx
@@ -486,14 +486,14 @@ function getButton(container: HTMLElement, text: string): HTMLButtonElement {
function getResolveAction(container: HTMLElement, commentId: string) {
const tree = getTree(container, commentId);
- const header = tree.firstElementChild as HTMLElement | null;
- const controls = header?.lastElementChild as HTMLElement | null;
- const action = controls?.firstElementChild;
+ const action = tree.querySelector<HTMLButtonElement>(
+ 'button[aria-label="thread-comment-ui.item.markResolved"], button[aria-label="thread-comment-ui.item.markUnresolved"]'
+ );
if (!action) {
throw new Error('Resolve action was not found.');
}
- return action as HTMLElement;
+ return action;
}
function getRootCommentItem(container: HTMLElement, commentId: string) {
@@ -776,7 +776,7 @@ describe('ThreadCommentTree', () => {
container = rendered.container;
expect(container.querySelector('button[aria-label="thread-comment-ui.item.more"]')).not.toBeNull();
- expect(container.querySelector('button[aria-label="thread-comment-ui.filter.status.resolved"]')).not.toBeNull();
+ expect(container.querySelector('button[aria-label="thread-comment-ui.item.markResolved"]')).not.toBeNull();
expect(container.querySelector('button[aria-label="thread-comment-ui.item.delete"]')).not.toBeNull();
});
diff --git a/packages/ui/src/views/components/ribbon/ToolbarItem.tsx b/packages/ui/src/views/components/ribbon/ToolbarItem.tsx
index 3d70cb1c41..ceae85f67c 100644
--- a/packages/ui/src/views/components/ribbon/ToolbarItem.tsx
+++ b/packages/ui/src/views/components/ribbon/ToolbarItem.tsx
@@ -161,7 +161,10 @@ const toolbarSelectorRootVariants = cva(
`,
},
active: {
- true: 'univer-bg-gray-200',
+ true: `
+ univer-bg-gray-200
+ dark:!univer-bg-gray-500
+ `,
false: '',
},
},