Skip to content

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

feat(sheets): add text-to-number cell alerts (#7426)

wpxp1234567c20c355b405
diff --git a/packages/sheets-numfmt-ui/src/controllers/numfmt-alert-render.controller.ts b/packages/sheets-numfmt-ui/src/controllers/numfmt-alert-render.controller.ts
index 2237a76f75..05ae5e572c 100644
--- a/packages/sheets-numfmt-ui/src/controllers/numfmt-alert-render.controller.ts
+++ b/packages/sheets-numfmt-ui/src/controllers/numfmt-alert-render.controller.ts
@@ -14,26 +14,28 @@
* limitations under the License.
*/
-import type { CellValue, Workbook } from '@univerjs/core';
+import type { CellValue, Nullable, Workbook, Worksheet } from '@univerjs/core';
import type { IRenderContext, IRenderModule } from '@univerjs/engine-render';
+import type { ISelectionWithStyle } from '@univerjs/sheets';
import type { IUniverSheetsNumfmtConfig } from '@univerjs/sheets-numfmt';
import type { LocaleKey } from '../locale/types';
-import { Disposable, IConfigService, Inject, isRealNum, isTextFormat, LocaleService, Tools } from '@univerjs/core';
-import { INumfmtService } from '@univerjs/sheets';
+import { Disposable, getNumfmtParseValueFilter, ICommandService, IConfigService, Inject, isRealNum, isTextFormat, IUniverInstanceService, LocaleService, Tools, UniverInstanceType } from '@univerjs/core';
+import { INumfmtService, SheetsSelectionsService, TextToNumberCommand } from '@univerjs/sheets';
import { SHEETS_NUMFMT_PLUGIN_CONFIG_KEY } from '@univerjs/sheets-numfmt';
-import { CellAlertManagerService, CellAlertType, HoverManagerService } from '@univerjs/sheets-ui';
-import { debounceTime } from 'rxjs';
+import { CellAlertManagerService, CellAlertType } from '@univerjs/sheets-ui';
const ALERT_KEY = 'SHEET_NUMFMT_ALERT';
export class NumfmtAlertRenderController extends Disposable implements IRenderModule {
constructor(
private readonly _context: IRenderContext<Workbook>,
- @Inject(HoverManagerService) private readonly _hoverManagerService: HoverManagerService,
+ @Inject(SheetsSelectionsService) private readonly _selectionManagerService: SheetsSelectionsService,
@Inject(CellAlertManagerService) private readonly _cellAlertManagerService: CellAlertManagerService,
@Inject(LocaleService) private readonly _localeService: LocaleService,
@Inject(INumfmtService) private _numfmtService: INumfmtService,
- @IConfigService private readonly _configService: IConfigService
+ @IConfigService private readonly _configService: IConfigService,
+ @ICommandService private readonly _commandService: ICommandService,
+ @IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService
) {
super();
this._init();
@@ -44,73 +46,97 @@ export class NumfmtAlertRenderController extends Disposable implements IRenderMo
}
private _initCellAlertPopup() {
- this.disposeWithMe(this._hoverManagerService.currentCell$.pipe(debounceTime(100)).subscribe((cellPos) => {
- if (cellPos) {
- const location = cellPos.location;
- const workbook = this._context.unit;
- const worksheet = workbook.getActiveSheet();
- if (!worksheet) return this._hideAlert();
-
- const unitId = location.unitId;
- const sheetId = location.subUnitId;
- let numfmtValue;
-
- const cellData = worksheet.getCell(location.row, location.col);
-
- if (cellData?.s) {
- const style = workbook.getStyles().get(cellData.s);
- if (style?.n) {
- numfmtValue = style.n;
- }
- }
-
- if (!numfmtValue) {
- numfmtValue = this._numfmtService.getValue(unitId, sheetId, location.row, location.col);
- }
-
- if (!numfmtValue) {
- this._hideAlert();
- return;
- }
-
- // Preventing blank object
- if (isTextFormat(numfmtValue.pattern) && Tools.isDefine(cellData?.v) && isRealNum(cellData.v as CellValue)) {
- // If the user has disabled the text format alert, do not show it
- if (this._configService.getConfig<IUniverSheetsNumfmtConfig>(SHEETS_NUMFMT_PLUGIN_CONFIG_KEY)?.disableTextFormatAlert) {
- return;
- }
+ this.disposeWithMe(this._selectionManagerService.selectionChanged$.subscribe((selections) => this._updateAlert(selections)));
+ this.disposeWithMe(this._context.unit.activeSheet$.subscribe(() => this._updateAlert(this._selectionManagerService.getCurrentSelections())));
+ this.disposeWithMe(
+ this._univerInstanceService.getCurrentTypeOfUnit$(UniverInstanceType.UNIVER_SHEET).subscribe(() =>
+ this._updateAlert(this._selectionManagerService.getCurrentSelections())
+ )
+ );
+ }
- const currentAlert = this._cellAlertManagerService.currentAlert.get(ALERT_KEY);
- const currentLoc = currentAlert?.alert?.location;
- if (
- currentLoc &&
- currentLoc.row === location.row &&
- currentLoc.col === location.col &&
- currentLoc.subUnitId === location.subUnitId &&
- currentLoc.unitId === location.unitId
- ) {
- this._hideAlert();
- return;
- }
+ private _isCurrentSheet(worksheet: Nullable<Worksheet>): worksheet is Worksheet {
+ const selectionParam = this._selectionManagerService.currentSelectionParam;
+ return Boolean(
+ worksheet &&
+ selectionParam?.unitId === this._context.unit.getUnitId() &&
+ selectionParam.sheetId === worksheet.getSheetId()
+ );
+ }
+
+ private _updateAlert(selections: Nullable<Readonly<ISelectionWithStyle[]>>) {
+ this._hideAlert();
+ const workbook = this._context.unit;
+ const worksheet = workbook.getActiveSheet();
+ if (!this._isCurrentSheet(worksheet)) {
+ return;
+ }
+
+ if (selections?.length !== 1) {
+ return;
+ }
- this._cellAlertManagerService.showAlert({
- type: CellAlertType.ERROR,
- title: this._localeService.t<LocaleKey>('sheets-numfmt-ui.info.error'),
- message: this._localeService.t<LocaleKey>('sheets-numfmt-ui.info.forceStringInfo'),
- location,
- width: 200,
- height: 74,
- key: ALERT_KEY,
+ if (this._configService.getConfig<IUniverSheetsNumfmtConfig>(SHEETS_NUMFMT_PLUGIN_CONFIG_KEY)?.disableTextFormatAlert) {
+ return;
+ }
+
+ const selection = selections[0];
+ const primary = selection.primary;
+ if (!primary) {
+ return;
+ }
+
+ const row = primary.actualRow;
+ const col = primary.actualColumn;
+ const unitId = workbook.getUnitId();
+ const subUnitId = worksheet.getSheetId();
+ const cellData = worksheet.getCell(row, col);
+ let numfmtValue;
+
+ if (cellData?.s) {
+ numfmtValue = workbook.getStyles().get(cellData.s)?.n;
+ }
+ if (!numfmtValue) {
+ numfmtValue = this._numfmtService.getValue(unitId, subUnitId, row, col);
+ }
+
+ const cellValue = cellData?.v;
+ const isConvertibleNumber = isRealNum(cellValue as CellValue) ||
+ (typeof cellValue === 'string' && typeof getNumfmtParseValueFilter(cellValue)?.v === 'number');
+ if (!isTextFormat(numfmtValue?.pattern) || !Tools.isDefine(cellValue) || !isConvertibleNumber) {
+ return;
+ }
+
+ const range = { ...selection.range };
+ this._cellAlertManagerService.showAlert({
+ type: CellAlertType.WARNING,
+ title: this._localeService.t<LocaleKey>('sheets-numfmt-ui.info.error'),
+ message: this._localeService.t<LocaleKey>('sheets-numfmt-ui.info.forceStringInfo'),
+ location: { unitId, subUnitId, row, col },
+ width: 200,
+ height: 74,
+ key: this._alertKey,
+ menu: [{
+ label: this._localeService.t<LocaleKey>('sheets-numfmt-ui.info.convertToNumber'),
+ onSelect: () => {
+ const result = this._commandService.syncExecuteCommand(TextToNumberCommand.id, {
+ unitId,
+ subUnitId,
+ ranges: [range],
});
- return;
- }
- }
+ if (result) {
+ this._hideAlert();
+ }
+ },
+ }],
+ });
+ }
- this._hideAlert();
- }));
+ private get _alertKey() {
+ return `${ALERT_KEY}:${this._context.unit.getUnitId()}`;
}
private _hideAlert() {
- this._cellAlertManagerService.removeAlert(ALERT_KEY);
+ this._cellAlertManagerService.removeAlert(this._alertKey);
}
}
diff --git a/packages/sheets-numfmt-ui/src/locale/ar-SA.ts b/packages/sheets-numfmt-ui/src/locale/ar-SA.ts
index e9bc5974e6..b66e1c72a6 100644
--- a/packages/sheets-numfmt-ui/src/locale/ar-SA.ts
+++ b/packages/sheets-numfmt-ui/src/locale/ar-SA.ts
@@ -54,6 +54,7 @@ const locale: typeof enUS = {
info: {
error: 'خطأ',
forceStringInfo: 'رقم مخزن كنص',
+ convertToNumber: 'تحويل إلى رقم',
},
},
};
diff --git a/packages/sheets-numfmt-ui/src/locale/ca-ES.ts b/packages/sheets-numfmt-ui/src/locale/ca-ES.ts
index 7dff58cc19..279e28bb4c 100644
--- a/packages/sheets-numfmt-ui/src/locale/ca-ES.ts
+++ b/packages/sheets-numfmt-ui/src/locale/ca-ES.ts
@@ -54,6 +54,7 @@ const locale: typeof enUS = {
info: {
error: 'Error',
forceStringInfo: 'Número emmagatzemat com a text',
+ convertToNumber: 'Converteix en número',
},
},
};
diff --git a/packages/sheets-numfmt-ui/src/locale/de-DE.ts b/packages/sheets-numfmt-ui/src/locale/de-DE.ts
index db68abf53d..04d6d8054b 100644
--- a/packages/sheets-numfmt-ui/src/locale/de-DE.ts
+++ b/packages/sheets-numfmt-ui/src/locale/de-DE.ts
@@ -54,6 +54,7 @@ const locale: typeof enUS = {
info: {
error: 'Fehler',
forceStringInfo: 'Zahl als Text gespeichert',
+ convertToNumber: 'In Zahl konvertieren',
},
},
};
diff --git a/packages/sheets-numfmt-ui/src/locale/en-US.ts b/packages/sheets-numfmt-ui/src/locale/en-US.ts
index 82bb11ed58..fc107d7afe 100644
--- a/packages/sheets-numfmt-ui/src/locale/en-US.ts
+++ b/packages/sheets-numfmt-ui/src/locale/en-US.ts
@@ -52,6 +52,7 @@ const locale = {
info: {
error: 'Error',
forceStringInfo: 'Number stored as text',
+ convertToNumber: 'Convert to Number',
},
},
};
diff --git a/packages/sheets-numfmt-ui/src/locale/es-ES.ts b/packages/sheets-numfmt-ui/src/locale/es-ES.ts
index 8587af02f7..596c6b734c 100644
--- a/packages/sheets-numfmt-ui/src/locale/es-ES.ts
+++ b/packages/sheets-numfmt-ui/src/locale/es-ES.ts
@@ -54,6 +54,7 @@ const locale: typeof enUS = {
info: {
error: 'Error',
forceStringInfo: 'Número almacenado como texto',
+ convertToNumber: 'Convertir en número',
},
},
};
diff --git a/packages/sheets-numfmt-ui/src/locale/fa-IR.ts b/packages/sheets-numfmt-ui/src/locale/fa-IR.ts
index 16dca8ee2a..324ffc1f37 100644
--- a/packages/sheets-numfmt-ui/src/locale/fa-IR.ts
+++ b/packages/sheets-numfmt-ui/src/locale/fa-IR.ts
@@ -54,6 +54,7 @@ const locale: typeof enUS = {
info: {
error: 'خطا',
forceStringInfo: 'عدد به عنوان متن ذخیره شده',
+ convertToNumber: 'تبدیل به عدد',
},
},
};
diff --git a/packages/sheets-numfmt-ui/src/locale/fr-FR.ts b/packages/sheets-numfmt-ui/src/locale/fr-FR.ts
index 0068d8cfbf..288aa46d61 100644
--- a/packages/sheets-numfmt-ui/src/locale/fr-FR.ts
+++ b/packages/sheets-numfmt-ui/src/locale/fr-FR.ts
@@ -54,6 +54,7 @@ const locale: typeof enUS = {
info: {
error: 'Erreur',
forceStringInfo: 'Nombre stocké en tant que texte',
+ convertToNumber: 'Convertir en nombre',
},
},
};
diff --git a/packages/sheets-numfmt-ui/src/locale/id-ID.ts b/packages/sheets-numfmt-ui/src/locale/id-ID.ts
index afa7723074..8571c891c7 100644
--- a/packages/sheets-numfmt-ui/src/locale/id-ID.ts
+++ b/packages/sheets-numfmt-ui/src/locale/id-ID.ts
@@ -54,6 +54,7 @@ const locale: typeof enUS = {
info: {
error: 'Kesalahan',
forceStringInfo: 'Angka disimpan sebagai teks',
+ convertToNumber: 'Konversi ke angka',
},
},
};
diff --git a/packages/sheets-numfmt-ui/src/locale/it-IT.ts b/packages/sheets-numfmt-ui/src/locale/it-IT.ts
index 1af41114af..14703c47ab 100644
--- a/packages/sheets-numfmt-ui/src/locale/it-IT.ts
+++ b/packages/sheets-numfmt-ui/src/locale/it-IT.ts
@@ -54,6 +54,7 @@ const locale: typeof enUS = {
info: {
error: 'Errore',
forceStringInfo: 'Numero memorizzato come testo',
+ convertToNumber: 'Converti in numero',
},
},
};
diff --git a/packages/sheets-numfmt-ui/src/locale/ja-JP.ts b/packages/sheets-numfmt-ui/src/locale/ja-JP.ts
index bcf17f6996..8418bf94be 100644
--- a/packages/sheets-numfmt-ui/src/locale/ja-JP.ts
+++ b/packages/sheets-numfmt-ui/src/locale/ja-JP.ts
@@ -54,6 +54,7 @@ const locale: typeof enUS = {
info: {
error: 'エラー',
forceStringInfo: '数値がテキストとして保存されました',
+ convertToNumber: '数値に変換',
},
},
};
diff --git a/packages/sheets-numfmt-ui/src/locale/ko-KR.ts b/packages/sheets-numfmt-ui/src/locale/ko-KR.ts
index b8da9fe208..f2f080704f 100644
--- a/packages/sheets-numfmt-ui/src/locale/ko-KR.ts
+++ b/packages/sheets-numfmt-ui/src/locale/ko-KR.ts
@@ -54,6 +54,7 @@ const locale: typeof enUS = {
info: {
error: '오류',
forceStringInfo: '숫자가 텍스트로 저장되었습니다',
+ convertToNumber: '숫자로 변환',
},
},
};
diff --git a/packages/sheets-numfmt-ui/src/locale/pl-PL.ts b/packages/sheets-numfmt-ui/src/locale/pl-PL.ts
index 0583d99567..99f3a0339f 100644
--- a/packages/sheets-numfmt-ui/src/locale/pl-PL.ts
+++ b/packages/sheets-numfmt-ui/src/locale/pl-PL.ts
@@ -54,6 +54,7 @@ const locale: typeof enUS = {
info: {
error: 'Błąd',
forceStringInfo: 'Liczba przechowywana jako tekst',
+ convertToNumber: 'Konwertuj na liczbę',
},
},
};
diff --git a/packages/sheets-numfmt-ui/src/locale/pt-BR.ts b/packages/sheets-numfmt-ui/src/locale/pt-BR.ts
index b139e252ef..fc413ad814 100644
--- a/packages/sheets-numfmt-ui/src/locale/pt-BR.ts
+++ b/packages/sheets-numfmt-ui/src/locale/pt-BR.ts
@@ -54,6 +54,7 @@ const locale: typeof enUS = {
info: {
error: 'Erro',
forceStringInfo: 'Número armazenado como texto',
+ convertToNumber: 'Converter em número',
},
},
};
diff --git a/packages/sheets-numfmt-ui/src/locale/ru-RU.ts b/packages/sheets-numfmt-ui/src/locale/ru-RU.ts
index e4ce3a8368..0531518d09 100644
--- a/packages/sheets-numfmt-ui/src/locale/ru-RU.ts
+++ b/packages/sheets-numfmt-ui/src/locale/ru-RU.ts
@@ -54,6 +54,7 @@ const locale: typeof enUS = {
info: {
error: 'Ошибка',
forceStringInfo: 'Число хранится как текст',
+ convertToNumber: 'Преобразовать в число',
},
},
};
diff --git a/packages/sheets-numfmt-ui/src/locale/sk-SK.ts b/packages/sheets-numfmt-ui/src/locale/sk-SK.ts
index 8cb3f7a74d..ba02e8f994 100644
--- a/packages/sheets-numfmt-ui/src/locale/sk-SK.ts
+++ b/packages/sheets-numfmt-ui/src/locale/sk-SK.ts
@@ -54,6 +54,7 @@ const locale: typeof enUS = {
info: {
error: 'Chyba',
forceStringInfo: 'Číslo uložené ako text',
+ convertToNumber: 'Konvertovať na číslo',
},
},
};
diff --git a/packages/sheets-numfmt-ui/src/locale/vi-VN.ts b/packages/sheets-numfmt-ui/src/locale/vi-VN.ts
index 6dac597d36..1456723c9a 100644
--- a/packages/sheets-numfmt-ui/src/locale/vi-VN.ts
+++ b/packages/sheets-numfmt-ui/src/locale/vi-VN.ts
@@ -54,6 +54,7 @@ const locale: typeof enUS = {
info: {
error: 'Lỗi',
forceStringInfo: 'Số được lưu trữ dưới dạng văn bản',
+ convertToNumber: 'Chuyển đổi thành số',
},
},
};
diff --git a/packages/sheets-numfmt-ui/src/locale/zh-CN.ts b/packages/sheets-numfmt-ui/src/locale/zh-CN.ts
index e1c49326d9..c11b35e935 100644
--- a/packages/sheets-numfmt-ui/src/locale/zh-CN.ts
+++ b/packages/sheets-numfmt-ui/src/locale/zh-CN.ts
@@ -54,6 +54,7 @@ const locale: typeof enUS = {
info: {
error: '错误',
forceStringInfo: '以文本形式存储的数字',
+ convertToNumber: '转换为数字',
},
},
};
diff --git a/packages/sheets-numfmt-ui/src/locale/zh-HK.ts b/packages/sheets-numfmt-ui/src/locale/zh-HK.ts
index fadfa64abc..20b812543e 100644
--- a/packages/sheets-numfmt-ui/src/locale/zh-HK.ts
+++ b/packages/sheets-numfmt-ui/src/locale/zh-HK.ts
@@ -54,6 +54,7 @@ const locale: typeof enUS = {
info: {
error: '錯誤',
forceStringInfo: '以文字形式儲存的數字',
+ convertToNumber: '轉換為數字',
},
},
};
diff --git a/packages/sheets-numfmt-ui/src/locale/zh-TW.ts b/packages/sheets-numfmt-ui/src/locale/zh-TW.ts
index fadfa64abc..20b812543e 100644
--- a/packages/sheets-numfmt-ui/src/locale/zh-TW.ts
+++ b/packages/sheets-numfmt-ui/src/locale/zh-TW.ts
@@ -54,6 +54,7 @@ const locale: typeof enUS = {
info: {
error: '錯誤',
forceStringInfo: '以文字形式儲存的數字',
+ convertToNumber: '轉換為數字',
},
},
};
diff --git a/packages/sheets-numfmt/src/controllers/__tests__/numfmt-cell-content.controller.spec.ts b/packages/sheets-numfmt/src/controllers/__tests__/numfmt-cell-content.controller.spec.ts
index 99718ff09f..b6b42004e2 100644
--- a/packages/sheets-numfmt/src/controllers/__tests__/numfmt-cell-content.controller.spec.ts
+++ b/packages/sheets-numfmt/src/controllers/__tests__/numfmt-cell-content.controller.spec.ts
@@ -74,6 +74,7 @@ function createWorkbookData(): IWorkbookData {
0: { v: '123', t: CellValueType.STRING, s: 'textStyle' },
1: { v: '1234.5', t: CellValueType.STRING },
2: { v: -12.3, t: CellValueType.NUMBER },
+ 3: { v: '20%', t: CellValueType.STRING, s: 'textStyle' },
},
},
},
@@ -196,6 +197,18 @@ describe('SheetsNumfmtCellContentController', () => {
},
});
+ expect(getInterceptedCell(worksheet, workbook, 1, 3, get)).toEqual({
+ v: '20%',
+ t: CellValueType.STRING,
+ s: 'textStyle',
+ markers: {
+ tl: {
+ size: 6,
+ color: '#409f11',
+ },
+ },
+ });
+
get(IConfigService).setConfig(SHEETS_NUMFMT_PLUGIN_CONFIG_KEY, { disableTextFormatMark: true });
expect(getInterceptedCell(worksheet, workbook, 1, 0, get)).toEqual({
@@ -203,6 +216,11 @@ describe('SheetsNumfmtCellContentController', () => {
t: CellValueType.STRING,
s: 'textStyle',
});
+ expect(getInterceptedCell(worksheet, workbook, 1, 3, get)).toEqual({
+ v: '20%',
+ t: CellValueType.STRING,
+ s: 'textStyle',
+ });
});
it('formats numeric values and clears render cache on numfmt or value mutations', async () => {
diff --git a/packages/sheets-numfmt/src/controllers/numfmt-cell-content.controller.ts b/packages/sheets-numfmt/src/controllers/numfmt-cell-content.controller.ts
index f8052e06e2..c328320e66 100644
--- a/packages/sheets-numfmt/src/controllers/numfmt-cell-content.controller.ts
+++ b/packages/sheets-numfmt/src/controllers/numfmt-cell-content.controller.ts
@@ -20,6 +20,7 @@ import type { IUniverSheetsNumfmtConfig } from '../config/config';
import {
CellValueType,
Disposable,
+ getNumfmtParseValueFilter,
ICommandService,
IConfigService,
Inject,
@@ -161,8 +162,15 @@ export class SheetsNumfmtCellContentController extends Disposable {
// If the cell not specified number type, then check the cell value type
if (cell.t !== CellValueType.NUMBER) {
const type = checkCellValueType(cell.v, cell.t);
- // just handle number or number string
- if (type !== CellValueType.NUMBER) {
+ // just handle number/number string/number string with text format, other type will not be processed
+ if (
+ type !== CellValueType.NUMBER &&
+ !(
+ isTextFormat(numfmtValue?.pattern) &&
+ typeof cell.v === 'string' &&
+ typeof getNumfmtParseValueFilter(cell.v)?.v === 'number'
+ )
+ ) {
return next(cell);
}
}
diff --git a/packages/sheets-ui/src/controllers/__tests__/checkbox-force-string-auto-width.controller.spec.ts b/packages/sheets-ui/src/controllers/__tests__/checkbox-force-string-auto-width.controller.spec.ts
index 5af85bede1..8c0d7fe6cd 100644
--- a/packages/sheets-ui/src/controllers/__tests__/checkbox-force-string-auto-width.controller.spec.ts
+++ b/packages/sheets-ui/src/controllers/__tests__/checkbox-force-string-auto-width.controller.spec.ts
@@ -16,8 +16,8 @@
import { CellValueType } from '@univerjs/core';
import { CURSOR_TYPE, getCurrentTypeOfRenderer } from '@univerjs/engine-render';
-import { INTERCEPTOR_POINT, SetWorksheetColWidthMutation, ToggleCellCheckboxCommand } from '@univerjs/sheets';
-import { Subject } from 'rxjs';
+import { INTERCEPTOR_POINT, SetWorksheetColWidthMutation, TextToNumberCommand, ToggleCellCheckboxCommand } from '@univerjs/sheets';
+import { BehaviorSubject, Subject } from 'rxjs';
import { describe, expect, it, vi } from 'vitest';
import { CellAlertType } from '../../services/cell-alert-manager.service';
import { AutoWidthController, createAutoColWidthUndoMutationsByRedos } from '../auto-width.controller';
@@ -42,8 +42,11 @@ vi.mock('@univerjs/engine-render', async (importOriginal) => {
describe('SheetCheckboxController', () => {
it('uses pointer cursor for checkbox bullets and toggles the clicked checkbox paragraph', () => {
- const currentRichText$ = new Subject<any>();
- const currentClickedCell$ = new Subject<any>();
+ const currentRichText$ = new Subject<{ bullet?: { startIndex: number } } | null>();
+ const currentClickedCell$ = new Subject<{
+ location: { unitId: string; subUnitId: string; row: number; col: number };
+ bullet?: { startIndex: number };
+ }>();
const commandService = { executeCommand: vi.fn() };
const controller = new SheetCheckboxController(
{ currentRichText$, currentClickedCell$ } as never,
@@ -81,7 +84,7 @@ describe('SheetCheckboxController', () => {
describe('ForceStringRenderController', () => {
it('marks numeric-looking string cells unless disabled or formatted as text', () => {
- let interceptor: any;
+ let interceptor: typeof INTERCEPTOR_POINT.CELL_CONTENT | undefined;
const controller = new ForceStringRenderController(
{ unitId: 'unit-1' } as never,
{ getCurrentParam: vi.fn(() => ({ skeleton: {} })) } as never,
@@ -101,26 +104,33 @@ describe('ForceStringRenderController', () => {
};
const rawCell = { v: '123', t: CellValueType.STRING };
+ if (!interceptor) {
+ throw new Error('CELL_CONTENT interceptor was not registered');
+ }
+
const result = interceptor.handler(rawCell, {
rawData: rawCell,
workbook,
- }, (cell: unknown) => cell);
+ } as never, (cell) => cell);
expect(result).not.toBe(rawCell);
- expect(result.markers.tl).toEqual({ size: 6, color: '#409f11' });
+ expect(result?.markers?.tl).toEqual({ size: 6, color: '#409f11' });
expect(interceptor.handler({ ...rawCell, s: 'text' }, {
rawData: { ...rawCell, s: 'text' },
workbook,
- }, (cell: unknown) => cell)).not.toHaveProperty('markers');
+ } as never, (cell) => cell)).not.toHaveProperty('markers');
controller.dispose();
});
});
describe('ForceStringAlertRenderController', () => {
- it('shows and hides force-string alert based on hovered cell value and format', () => {
- const currentCell$ = new Subject<any>();
+ it('shows the alert only for a numeric-text primary cell in a single selection', () => {
+ const selectionChanged$ = new Subject<Array<{
+ range: { startRow: number; endRow: number; startColumn: number; endColumn: number };
+ primary: { actualRow: number; actualColumn: number };
+ }>>();
const cellAlertManagerService = {
currentAlert: new Map(),
showAlert: vi.fn((alert) => {
@@ -129,38 +139,134 @@ describe('ForceStringAlertRenderController', () => {
removeAlert: vi.fn((key) => cellAlertManagerService.currentAlert.delete(key)),
};
const worksheet = {
+ getSheetId: vi.fn(() => 'sheet-1'),
getCell: vi.fn((row: number) => row === 1
? { v: '123', t: CellValueType.STRING }
: { v: '123', t: CellValueType.STRING, s: 'text' }),
};
const workbook = {
+ activeSheet$: new BehaviorSubject(worksheet),
+ getUnitId: vi.fn(() => 'unit-1'),
getActiveSheet: vi.fn(() => worksheet),
getStyles: vi.fn(() => ({
get: vi.fn((styleId: string) => styleId === 'text' ? { n: { pattern: '@' } } : undefined),
})),
};
+ let disableForceStringAlert = false;
+ const commandService = {
+ syncExecuteCommand: vi.fn(() => true),
+ };
+ const currentUnit$ = new BehaviorSubject(workbook);
const controller = new ForceStringAlertRenderController(
{ unit: workbook } as never,
- { currentCell$ } as never,
+ {
+ selectionChanged$,
+ currentSelectionParam: { unitId: 'unit-1', sheetId: 'sheet-1' },
+ getCurrentSelections: vi.fn(() => []),
+ } as never,
cellAlertManagerService as never,
{ t: vi.fn((key: string) => key) } as never,
- { getConfig: vi.fn(() => ({ disableForceStringAlert: false })) } as never
+ { getConfig: vi.fn(() => ({ disableForceStringAlert })) } as never,
+ commandService as never,
+ { getCurrentTypeOfUnit$: vi.fn(() => currentUnit$) } as never
);
- currentCell$.next({ location: { unitId: 'unit-1', subUnitId: 'sheet-1', row: 1, col: 2 } });
+ const selection = {
+ range: { startRow: 1, endRow: 3, startColumn: 2, endColumn: 4 },
+ primary: { actualRow: 1, actualColumn: 2 },
+ };
+ selectionChanged$.next([selection]);
expect(cellAlertManagerService.showAlert).toHaveBeenCalledWith(expect.objectContaining({
- type: CellAlertType.ERROR,
+ type: CellAlertType.WARNING,
title: 'sheets-ui.info.error',
message: 'sheets-ui.info.forceStringInfo',
- width: 200,
- height: 74,
- key: 'SHEET_FORCE_STRING_ALERT',
+ key: 'SHEET_FORCE_STRING_ALERT:unit-1',
+ location: { unitId: 'unit-1', subUnitId: 'sheet-1', row: 1, col: 2 },
+ menu: [expect.objectContaining({ label: 'sheets-ui.info.convertToNumber' })],
}));
- currentCell$.next({ location: { unitId: 'unit-1', subUnitId: 'sheet-1', row: 2, col: 2 } });
- expect(cellAlertManagerService.removeAlert).toHaveBeenCalledWith('SHEET_FORCE_STRING_ALERT');
- currentCell$.next(null);
- expect(cellAlertManagerService.removeAlert).toHaveBeenCalledTimes(2);
+ const alert = cellAlertManagerService.showAlert.mock.calls[0][0];
+ alert.menu[0].onSelect();
+ expect(commandService.syncExecuteCommand).toHaveBeenCalledWith(TextToNumberCommand.id, {
+ unitId: 'unit-1',
+ subUnitId: 'sheet-1',
+ ranges: [selection.range],
+ });
+
+ selectionChanged$.next([selection, { ...selection }]);
+ expect(cellAlertManagerService.removeAlert).toHaveBeenCalledWith('SHEET_FORCE_STRING_ALERT:unit-1');
+
+ selectionChanged$.next([{
+ range: { startRow: 2, endRow: 2, startColumn: 2, endColumn: 2 },
+ primary: { actualRow: 2, actualColumn: 2 },
+ }]);
+ expect(cellAlertManagerService.showAlert).toHaveBeenCalledTimes(1);
+
+ disableForceStringAlert = true;
+ selectionChanged$.next([selection]);
+ expect(cellAlertManagerService.showAlert).toHaveBeenCalledTimes(1);
+
+ controller.dispose();
+ });
+
+ it('scopes alerts to the current workbook and refreshes them when the active sheet changes', () => {
+ const selection = {
+ range: { startRow: 1, endRow: 1, startColumn: 2, endColumn: 2 },
+ primary: { actualRow: 1, actualColumn: 2 },
+ };
+ const selectionChanged$ = new Subject<typeof selection[]>();
+ const selectionService = {
+ selectionChanged$,
+ currentSelectionParam: { unitId: 'unit-2', sheetId: 'sheet-1' },
+ getCurrentSelections: vi.fn(() => [selection]),
+ };
+ const sheet1 = {
+ getSheetId: vi.fn(() => 'sheet-1'),
+ getCell: vi.fn(() => ({ v: '123', t: CellValueType.STRING })),
+ };
+ const sheet2 = {
+ getSheetId: vi.fn(() => 'sheet-2'),
+ getCell: vi.fn(() => ({ v: 'abc', t: CellValueType.STRING })),
+ };
+ let activeSheet = sheet1;
+ const activeSheet$ = new BehaviorSubject(activeSheet);
+ const workbook = {
+ activeSheet$,
+ getUnitId: vi.fn(() => 'unit-1'),
+ getActiveSheet: vi.fn(() => activeSheet),
+ getStyles: vi.fn(() => ({ get: vi.fn() })),
+ };
+ const cellAlertManagerService = {
+ currentAlert: new Map(),
+ showAlert: vi.fn((alert) => cellAlertManagerService.currentAlert.set(alert.key, { alert })),
+ removeAlert: vi.fn((key) => cellAlertManagerService.currentAlert.delete(key)),
+ };
+ const currentUnit$ = new BehaviorSubject<object>({ getUnitId: () => 'unit-2' });
+ const controller = new ForceStringAlertRenderController(
+ { unit: workbook } as never,
+ selectionService as never,
+ cellAlertManagerService as never,
+ { t: vi.fn((key: string) => key) } as never,
+ { getConfig: vi.fn(() => ({})) } as never,
+ { syncExecuteCommand: vi.fn(() => true) } as never,
+ { getCurrentTypeOfUnit$: vi.fn(() => currentUnit$) } as never
+ );
+
+ expect(cellAlertManagerService.showAlert).not.toHaveBeenCalled();
+
+ selectionService.currentSelectionParam = { unitId: 'unit-1', sheetId: 'sheet-1' };
+ currentUnit$.next(workbook);
+ expect(cellAlertManagerService.showAlert).toHaveBeenCalledTimes(1);
+
+ selectionService.currentSelectionParam = { unitId: 'unit-2', sheetId: 'sheet-1' };
+ currentUnit$.next({ getUnitId: () => 'unit-2' });
+ expect(cellAlertManagerService.currentAlert.size).toBe(0);
+
+ activeSheet = sheet2;
+ selectionService.currentSelectionParam = { unitId: 'unit-1', sheetId: 'sheet-2' };
+ currentUnit$.next(workbook);
+ activeSheet$.next(sheet2);
+ expect(cellAlertManagerService.currentAlert.size).toBe(0);
controller.dispose();
});
diff --git a/packages/sheets-ui/src/controllers/force-string-alert-render.controller.ts b/packages/sheets-ui/src/controllers/force-string-alert-render.controller.ts
index 1d616ec896..81a2e89bca 100644
--- a/packages/sheets-ui/src/controllers/force-string-alert-render.controller.ts
+++ b/packages/sheets-ui/src/controllers/force-string-alert-render.controller.ts
@@ -14,33 +14,39 @@
* limitations under the License.
*/
-import type { Workbook } from '@univerjs/core';
+import type { Nullable, Workbook, Worksheet } from '@univerjs/core';
import type { IRenderContext, IRenderModule } from '@univerjs/engine-render';
+import type { ISelectionWithStyle } from '@univerjs/sheets';
import type { IUniverSheetsUIConfig } from '../config/config';
import type { LocaleKey } from '../locale/types';
import {
CellValueType,
Disposable,
getNumfmtParseValueFilter,
+ ICommandService,
IConfigService,
Inject,
isRealNum,
isTextFormat,
+ IUniverInstanceService,
LocaleService,
+ UniverInstanceType,
} from '@univerjs/core';
+import { SheetsSelectionsService, TextToNumberCommand } from '@univerjs/sheets';
import { SHEETS_UI_PLUGIN_CONFIG_KEY } from '../config/config';
import { CellAlertManagerService, CellAlertType } from '../services/cell-alert-manager.service';
-import { HoverManagerService } from '../services/hover-manager.service';
const ALERT_KEY = 'SHEET_FORCE_STRING_ALERT';
export class ForceStringAlertRenderController extends Disposable implements IRenderModule {
constructor(
private readonly _context: IRenderContext<Workbook>,
- @Inject(HoverManagerService) private readonly _hoverManagerService: HoverManagerService,
+ @Inject(SheetsSelectionsService) private readonly _selectionManagerService: SheetsSelectionsService,
@Inject(CellAlertManagerService) private readonly _cellAlertManagerService: CellAlertManagerService,
@Inject(LocaleService) private readonly _localeService: LocaleService,
- @IConfigService private readonly _configService: IConfigService
+ @IConfigService private readonly _configService: IConfigService,
+ @ICommandService private readonly _commandService: ICommandService,
+ @IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService
) {
super();
this._init();
@@ -51,81 +57,97 @@ export class ForceStringAlertRenderController extends Disposable implements IRen
}
private _initCellAlertPopup() {
- this.disposeWithMe(this._hoverManagerService.currentCell$.subscribe((cellPos) => {
- if (cellPos) {
- const location = cellPos.location;
- const workbook = this._context.unit;
- const worksheet = workbook.getActiveSheet();
-
- if (!worksheet) return this._hideAlert();
-
- const cellData = worksheet.getCell(location.row, location.col);
-
- if (!cellData || cellData.v === null || cellData.v === undefined) return this._hideAlert();
-
- let numfmtValue;
+ this.disposeWithMe(this._selectionManagerService.selectionChanged$.subscribe((selections) => this._updateAlert(selections)));
+ this.disposeWithMe(this._context.unit.activeSheet$.subscribe(() => this._updateAlert(this._selectionManagerService.getCurrentSelections())));
+ this.disposeWithMe(
+ this._univerInstanceService.getCurrentTypeOfUnit$(UniverInstanceType.UNIVER_SHEET).subscribe(() =>
+ this._updateAlert(this._selectionManagerService.getCurrentSelections())
+ )
+ );
+ }
- if (cellData?.s) {
- const style = workbook.getStyles().get(cellData.s);
- if (style?.n) {
- numfmtValue = style.n;
- }
- }
-
- // If the cell has text format, follow the logic of text format and do not show the force string alert.
- if (isTextFormat(numfmtValue?.pattern)) {
- this._hideAlert();
- return;
- }
-
- /**
- * If the cell type is string or force string, and the value is a pure number or a string that can be converted to a number, show the force string alert.
- * '123 -> yes
- * '20% -> yes
- * '1,234.56 -> yes
- * 'abc -> no
- * '2025-09-17 -> no
- */
- if (
- (cellData.t === CellValueType.FORCE_STRING || cellData.t === CellValueType.STRING) &&
- (isRealNum(cellData.v) || (typeof cellData.v === 'string' && getNumfmtParseValueFilter(cellData.v)))
- ) {
- // If the user has disabled the force string alert, do not show it
- if (this._configService.getConfig<IUniverSheetsUIConfig>(SHEETS_UI_PLUGIN_CONFIG_KEY)?.disableForceStringAlert) {
- return;
- }
+ private _isCurrentSheet(worksheet: Nullable<Worksheet>): worksheet is Worksheet {
+ const selectionParam = this._selectionManagerService.currentSelectionParam;
+ return Boolean(
+ worksheet &&
+ selectionParam?.unitId === this._context.unit.getUnitId() &&
+ selectionParam.sheetId === worksheet.getSheetId()
+ );
+ }
- 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
- ) {
+ private _updateAlert(selections: Nullable<Readonly<ISelectionWithStyle[]>>) {
+ this._hideAlert();
+ const workbook = this._context.unit;
+ const worksheet = workbook.getActiveSheet();
+ if (!this._isCurrentSheet(worksheet)) {
+ return;
+ }
+
+ if (selections?.length !== 1) {
+ return;
+ }
+
+ if (this._configService.getConfig<IUniverSheetsUIConfig>(SHEETS_UI_PLUGIN_CONFIG_KEY)?.disableForceStringAlert) {
+ return;
+ }
+
+ const selection = selections[0];
+ const primary = selection.primary;
+ if (!primary) {
+ return;
+ }
+
+ const row = primary.actualRow;
+ const col = primary.actualColumn;
+ const cellData = worksheet.getCell(row, col);
+ if (!cellData || cellData.v === null || cellData.v === undefined) {
+ return;
+ }
+
+ const cellStyle = workbook.getStyles().get(cellData.s);
+ if (isTextFormat(cellStyle?.n?.pattern)) {
+ return;
+ }
+
+ if (
+ (cellData.t !== CellValueType.FORCE_STRING && cellData.t !== CellValueType.STRING) ||
+ (!isRealNum(cellData.v) && !(typeof cellData.v === 'string' && getNumfmtParseValueFilter(cellData.v)))
+ ) {
+ return;
+ }
+
+ const unitId = workbook.getUnitId();
+ const subUnitId = worksheet.getSheetId();
+ const range = { ...selection.range };
+ this._cellAlertManagerService.showAlert({
+ type: CellAlertType.WARNING,
+ title: this._localeService.t<LocaleKey>('sheets-ui.info.error'),
+ message: this._localeService.t<LocaleKey>('sheets-ui.info.forceStringInfo'),
+ location: { unitId, subUnitId, row, col },
+ width: 200,
+ height: 74,
+ key: this._alertKey,
+ menu: [{
+ label: this._localeService.t<LocaleKey>('sheets-ui.info.convertToNumber'),
+ onSelect: () => {
+ const result = this._commandService.syncExecuteCommand(TextToNumberCommand.id, {
+ unitId,
+ subUnitId,
+ ranges: [range],
+ });
+ if (result) {
this._hideAlert();
- return;
}
+ },
+ }],
+ });
+ }
- this._cellAlertManagerService.showAlert({
- type: CellAlertType.ERROR,
- title: this._localeService.t<LocaleKey>('sheets-ui.info.error'),
- message: this._localeService.t<LocaleKey>('sheets-ui.info.forceStringInfo'),
- location,
- width: 200,
- height: 74,
- key: ALERT_KEY,
- });
- return;
- }
- }
-
- this._hideAlert();
- }));
+ private get _alertKey() {
+ return `${ALERT_KEY}:${this._context.unit.getUnitId()}`;
}
private _hideAlert() {
- this._cellAlertManagerService.removeAlert(ALERT_KEY);
+ this._cellAlertManagerService.removeAlert(this._alertKey);
}
}
diff --git a/packages/sheets-ui/src/locale/ar-SA.ts b/packages/sheets-ui/src/locale/ar-SA.ts
index 20396cd055..a6b1ecd699 100644
--- a/packages/sheets-ui/src/locale/ar-SA.ts
+++ b/packages/sheets-ui/src/locale/ar-SA.ts
@@ -273,6 +273,7 @@ const locale: typeof enUS = {
problem: 'حدثت مشكلة',
error: 'خطأ',
forceStringInfo: 'رقم مخزن كنص',
+ convertToNumber: 'تحويل إلى رقم',
},
clipboard: {
paste: {
diff --git a/packages/sheets-ui/src/locale/ca-ES.ts b/packages/sheets-ui/src/locale/ca-ES.ts
index a1eb624fcc..2b7bf30cbd 100644
--- a/packages/sheets-ui/src/locale/ca-ES.ts
+++ b/packages/sheets-ui/src/locale/ca-ES.ts
@@ -273,6 +273,7 @@ const locale: typeof enUS = {
problem: 'Hi ha hagut un problema',
error: 'Error',
forceStringInfo: 'Número emmagatzemat com a text',
+ convertToNumber: 'Converteix en número',
},
clipboard: {
paste: {
diff --git a/packages/sheets-ui/src/locale/de-DE.ts b/packages/sheets-ui/src/locale/de-DE.ts
index a7ad8dac8c..7b42b60ad9 100644
--- a/packages/sheets-ui/src/locale/de-DE.ts
+++ b/packages/sheets-ui/src/locale/de-DE.ts
@@ -273,6 +273,7 @@ const locale: typeof enUS = {
problem: 'Es ist ein Problem aufgetreten',
error: 'Fehler',
forceStringInfo: 'Zahl als Text gespeichert',
+ convertToNumber: 'In Zahl konvertieren',
},
clipboard: {
paste: {
diff --git a/packages/sheets-ui/src/locale/en-US.ts b/packages/sheets-ui/src/locale/en-US.ts
index 79f49f084d..2677a1c8ca 100644
--- a/packages/sheets-ui/src/locale/en-US.ts
+++ b/packages/sheets-ui/src/locale/en-US.ts
@@ -271,6 +271,7 @@ const locale = {
problem: 'There was a problem',
error: 'Error',
forceStringInfo: 'Number stored as text',
+ convertToNumber: 'Convert to Number',
},
clipboard: {
paste: {
diff --git a/packages/sheets-ui/src/locale/es-ES.ts b/packages/sheets-ui/src/locale/es-ES.ts
index e24265baa0..bbbabccad3 100644
--- a/packages/sheets-ui/src/locale/es-ES.ts
+++ b/packages/sheets-ui/src/locale/es-ES.ts
@@ -273,6 +273,7 @@ const locale: typeof enUS = {
problem: 'Ha habido un problema',
error: 'Error',
forceStringInfo: 'Número almacenado como texto',
+ convertToNumber: 'Convertir en número',
},
clipboard: {
paste: {
diff --git a/packages/sheets-ui/src/locale/fa-IR.ts b/packages/sheets-ui/src/locale/fa-IR.ts
index 386971454e..baa5af6b35 100644
--- a/packages/sheets-ui/src/locale/fa-IR.ts
+++ b/packages/sheets-ui/src/locale/fa-IR.ts
@@ -273,6 +273,7 @@ const locale: typeof enUS = {
problem: 'مشکلی پیش آمد',
error: 'خطا',
forceStringInfo: 'عدد به عنوان متن ذخیره شده',
+ convertToNumber: 'تبدیل به عدد',
},
clipboard: {
paste: {
diff --git a/packages/sheets-ui/src/locale/fr-FR.ts b/packages/sheets-ui/src/locale/fr-FR.ts
index e878437ab5..3b1aabc112 100644
--- a/packages/sheets-ui/src/locale/fr-FR.ts
+++ b/packages/sheets-ui/src/locale/fr-FR.ts
@@ -273,6 +273,7 @@ const locale: typeof enUS = {
problem: 'Il y a eu un problème',
error: 'Erreur',
forceStringInfo: 'Nombre stocké en tant que texte',
+ convertToNumber: 'Convertir en nombre',
},
clipboard: {
paste: {
diff --git a/packages/sheets-ui/src/locale/id-ID.ts b/packages/sheets-ui/src/locale/id-ID.ts
index 5a30833652..65ca2eef88 100644
--- a/packages/sheets-ui/src/locale/id-ID.ts
+++ b/packages/sheets-ui/src/locale/id-ID.ts
@@ -273,6 +273,7 @@ const locale: typeof enUS = {
problem: 'Terjadi masalah',
error: 'Kesalahan',
forceStringInfo: 'Angka disimpan sebagai teks',
+ convertToNumber: 'Konversi ke angka',
},
clipboard: {
paste: {
diff --git a/packages/sheets-ui/src/locale/it-IT.ts b/packages/sheets-ui/src/locale/it-IT.ts
index ed5c848734..a818d9cf92 100644
--- a/packages/sheets-ui/src/locale/it-IT.ts
+++ b/packages/sheets-ui/src/locale/it-IT.ts
@@ -273,6 +273,7 @@ const locale: typeof enUS = {
problem: 'Si è verificato un problema',
error: 'Errore',
forceStringInfo: 'Numero memorizzato come testo',
+ convertToNumber: 'Converti in numero',
},
clipboard: {
paste: {
diff --git a/packages/sheets-ui/src/locale/ja-JP.ts b/packages/sheets-ui/src/locale/ja-JP.ts
index f2d7d83594..cdbc445179 100644
--- a/packages/sheets-ui/src/locale/ja-JP.ts
+++ b/packages/sheets-ui/src/locale/ja-JP.ts
@@ -273,6 +273,7 @@ const locale: typeof enUS = {
problem: '問題が発生しました',
error: 'エラー',
forceStringInfo: '数値がテキストとして保存されました',
+ convertToNumber: '数値に変換',
},
clipboard: {
paste: {
diff --git a/packages/sheets-ui/src/locale/ko-KR.ts b/packages/sheets-ui/src/locale/ko-KR.ts
index 866fd92102..0f5d8f6f52 100644
--- a/packages/sheets-ui/src/locale/ko-KR.ts
+++ b/packages/sheets-ui/src/locale/ko-KR.ts
@@ -273,6 +273,7 @@ const locale: typeof enUS = {
problem: '문제가 발생했습니다',
error: '오류',
forceStringInfo: '숫자가 텍스트로 저장되었습니다',
+ convertToNumber: '숫자로 변환',
},
clipboard: {
paste: {
diff --git a/packages/sheets-ui/src/locale/pl-PL.ts b/packages/sheets-ui/src/locale/pl-PL.ts
index e6dcb02217..aa23aed455 100644
--- a/packages/sheets-ui/src/locale/pl-PL.ts
+++ b/packages/sheets-ui/src/locale/pl-PL.ts
@@ -273,6 +273,7 @@ const locale: typeof enUS = {
problem: 'Wystąpił problem',
error: 'Błąd',
forceStringInfo: 'Liczba przechowywana jako tekst',
+ convertToNumber: 'Konwertuj na liczbę',
},
clipboard: {
paste: {
diff --git a/packages/sheets-ui/src/locale/pt-BR.ts b/packages/sheets-ui/src/locale/pt-BR.ts
index 24f7c8c2fd..f26ce7e265 100644
--- a/packages/sheets-ui/src/locale/pt-BR.ts
+++ b/packages/sheets-ui/src/locale/pt-BR.ts
@@ -273,6 +273,7 @@ const locale: typeof enUS = {
problem: 'Ocorreu um problema',
error: 'Erro',
forceStringInfo: 'Número armazenado como texto',
+ convertToNumber: 'Converter em número',
},
clipboard: {
paste: {
diff --git a/packages/sheets-ui/src/locale/ru-RU.ts b/packages/sheets-ui/src/locale/ru-RU.ts
index 867d81f891..86ef211a06 100644
--- a/packages/sheets-ui/src/locale/ru-RU.ts
+++ b/packages/sheets-ui/src/locale/ru-RU.ts
@@ -273,6 +273,7 @@ const locale: typeof enUS = {
problem: 'Произошла проблема',
error: 'Ошибка',
forceStringInfo: 'Число хранится как текст',
+ convertToNumber: 'Преобразовать в число',
},
clipboard: {
paste: {
diff --git a/packages/sheets-ui/src/locale/sk-SK.ts b/packages/sheets-ui/src/locale/sk-SK.ts
index e498377140..7ec2d2c910 100644
--- a/packages/sheets-ui/src/locale/sk-SK.ts
+++ b/packages/sheets-ui/src/locale/sk-SK.ts
@@ -273,6 +273,7 @@ const locale: typeof enUS = {
problem: 'Vyskytol sa problém',
error: 'Chyba',
forceStringInfo: 'Číslo uložené ako text',
+ convertToNumber: 'Konvertovať na číslo',
},
clipboard: {
paste: {
diff --git a/packages/sheets-ui/src/locale/vi-VN.ts b/packages/sheets-ui/src/locale/vi-VN.ts
index 2546a63f9e..ebaf777bc1 100644
--- a/packages/sheets-ui/src/locale/vi-VN.ts
+++ b/packages/sheets-ui/src/locale/vi-VN.ts
@@ -273,6 +273,7 @@ const locale: typeof enUS = {
problem: 'Đã xảy ra một vấn đề',
error: 'Lỗi',
forceStringInfo: 'Số được lưu trữ dưới dạng văn bản',
+ convertToNumber: 'Chuyển đổi thành số',
},
clipboard: {
paste: {
diff --git a/packages/sheets-ui/src/locale/zh-CN.ts b/packages/sheets-ui/src/locale/zh-CN.ts
index 3d4ffa80f6..d6533a0e57 100644
--- a/packages/sheets-ui/src/locale/zh-CN.ts
+++ b/packages/sheets-ui/src/locale/zh-CN.ts
@@ -273,6 +273,7 @@ const locale: typeof enUS = {
problem: '出现了一个问题',
error: '错误',
forceStringInfo: '以文本形式存储的数字',
+ convertToNumber: '转换为数字',
},
clipboard: {
paste: {
diff --git a/packages/sheets-ui/src/locale/zh-HK.ts b/packages/sheets-ui/src/locale/zh-HK.ts
index 1862350fa1..4cc05ef064 100644
--- a/packages/sheets-ui/src/locale/zh-HK.ts
+++ b/packages/sheets-ui/src/locale/zh-HK.ts
@@ -273,6 +273,7 @@ const locale: typeof enUS = {
problem: '出現了一個問題',
error: '錯誤',
forceStringInfo: '以文字形式儲存的數字',
+ convertToNumber: '轉換為數字',
},
clipboard: {
paste: {
diff --git a/packages/sheets-ui/src/locale/zh-TW.ts b/packages/sheets-ui/src/locale/zh-TW.ts
index 1862350fa1..4cc05ef064 100644
--- a/packages/sheets-ui/src/locale/zh-TW.ts
+++ b/packages/sheets-ui/src/locale/zh-TW.ts
@@ -273,6 +273,7 @@ const locale: typeof enUS = {
problem: '出現了一個問題',
error: '錯誤',
forceStringInfo: '以文字形式儲存的數字',
+ convertToNumber: '轉換為數字',
},
clipboard: {
paste: {
diff --git a/packages/sheets-ui/src/services/__tests__/cell-alert-manager.service.spec.ts b/packages/sheets-ui/src/services/__tests__/cell-alert-manager.service.spec.ts
index 2f8ede9bf5..33ec6c007f 100644
--- a/packages/sheets-ui/src/services/__tests__/cell-alert-manager.service.spec.ts
+++ b/packages/sheets-ui/src/services/__tests__/cell-alert-manager.service.spec.ts
@@ -43,28 +43,29 @@ describe('CellAlertManagerService', () => {
.mockReturnValueOnce(oldPopupDispose)
.mockReturnValueOnce(newPopupDispose);
const service = new CellAlertManagerService(
- { getRenderUnitById: vi.fn(() => ({ id: 'render' })) } as any,
- { showPopup } as any
+ { getRenderUnitById: vi.fn(() => ({ id: 'render' })) } as never,
+ { showPopup } as never
);
- const emitted: Array<[string, any][]> = [];
+ const emitted: Array<Array<[string, unknown]>> = [];
service.currentAlert$.subscribe((value) => emitted.push(value));
const first = createAlert('alert-1');
- service.showAlert(first as any);
+ service.showAlert(first as never);
expect(showPopup).toHaveBeenCalledWith(
first.location,
expect.objectContaining({
componentKey: 'univer.sheet.cell-alert',
direction: 'horizontal',
priority: 1,
+ showOnSelectionMoving: false,
extraProps: { alert: first },
})
);
expect(service.currentAlert.size).toBe(1);
expect(emitted.at(-1)?.map(([key]) => key)).toEqual(['alert-1']);
- service.showAlert({ ...first, message: 'updated' } as any);
+ service.showAlert({ ...first, message: 'updated' } as never);
expect(oldPopupDispose.dispose).toHaveBeenCalled();
expect(service.currentAlert.get('alert-1')?.alert.message).toBe('message');
expect(emitted.at(-1)?.map(([key]) => key)).toEqual(['alert-1']);
@@ -79,13 +80,14 @@ describe('CellAlertManagerService', () => {
const popupA = { dispose: vi.fn() };
const popupB = { dispose: vi.fn() };
const showPopup = vi.fn().mockReturnValueOnce(popupA).mockReturnValueOnce(popupB);
- const renderManager: any = {
- getRenderUnitById: vi.fn(() => ({ id: 'render' })),
+ let currentRender: { id: string } | null = { id: 'render' };
+ const renderManager = {
+ getRenderUnitById: vi.fn(() => currentRender),
};
- const service = new CellAlertManagerService(renderManager as any, { showPopup } as any);
+ const service = new CellAlertManagerService(renderManager as never, { showPopup } as never);
- service.showAlert(createAlert('a') as any);
- service.showAlert(createAlert('b') as any);
+ service.showAlert(createAlert('a') as never);
+ service.showAlert(createAlert('b') as never);
expect(service.currentAlert.size).toBe(2);
service.clearAlert();
@@ -93,11 +95,36 @@ describe('CellAlertManagerService', () => {
expect(popupA.dispose).toHaveBeenCalled();
expect(popupB.dispose).toHaveBeenCalled();
- renderManager.getRenderUnitById = vi.fn(() => null);
- service.showAlert(createAlert('no-render') as any);
+ currentRender = null;
+ service.showAlert(createAlert('no-render') as never);
expect(showPopup).toHaveBeenCalledTimes(2);
expect(service.currentAlert.has('no-render')).toBe(true);
service.removeAlert('not-found');
});
+
+ it('anchors actionable alerts to the left of the cell', () => {
+ const showPopup = vi.fn(() => ({ dispose: vi.fn() }));
+ const service = new CellAlertManagerService(
+ { getRenderUnitById: vi.fn(() => ({ id: 'render' })) } as never,
+ { showPopup } as never
+ );
+ const alert = {
+ ...createAlert('action-alert'),
+ menu: [{ label: 'Text to Number', onSelect: vi.fn() }],
+ };
+
+ service.showAlert(alert as never);
+
+ expect(showPopup).toHaveBeenCalledWith(
+ alert.location,
+ expect.objectContaining({
+ componentKey: 'univer.sheet.cell-alert',
+ direction: 'left-center',
+ autoRelayout: true,
+ showOnSelectionMoving: true,
+ extraProps: { alert },
+ })
+ );
+ });
});
diff --git a/packages/sheets-ui/src/services/__tests__/cell-popup-manager.service.spec.ts b/packages/sheets-ui/src/services/__tests__/cell-popup-manager.service.spec.ts
index a38bc05a69..8809eb3659 100644
--- a/packages/sheets-ui/src/services/__tests__/cell-popup-manager.service.spec.ts
+++ b/packages/sheets-ui/src/services/__tests__/cell-popup-manager.service.spec.ts
@@ -14,6 +14,7 @@
* limitations under the License.
*/
+import type { ICellPopupChange } from '../cell-popup-manager.service';
import { describe, expect, it, vi } from 'vitest';
import { CellPopupManagerService } from '../cell-popup-manager.service';
@@ -23,8 +24,8 @@ describe('CellPopupManagerService', () => {
const sheetPopupService = {
attachPopupToCell: vi.fn(() => popupDisposable),
};
- const service = new CellPopupManagerService(sheetPopupService as any);
- const changes: any[] = [];
+ const service = new CellPopupManagerService(sheetPopupService as never);
+ const changes: ICellPopupChange[] = [];
service.change$.subscribe((change) => changes.push(change));
const location = { unitId: 'unit-1', subUnitId: 'sheet-1', row: 4, col: 5 };
@@ -32,12 +33,12 @@ describe('CellPopupManagerService', () => {
id: 'p-low',
componentKey: 'component-a',
priority: 10,
- } as any);
+ } as never);
const disposeHigh = service.showPopup(location, {
id: 'p-high',
componentKey: 'component-b',
priority: 1,
- } as any);
+ } as never);
expect(sheetPopupService.attachPopupToCell).toHaveBeenCalledTimes(1);
expect(service.getPopups('unit-1', 'sheet-1', 4, 5, 'horizontal').map((p) => p.id)).toEqual(['p-high', 'p-low']);
@@ -52,17 +53,41 @@ describe('CellPopupManagerService', () => {
expect(popupDisposable.dispose).toHaveBeenCalledTimes(1);
});
- it('supports vertical cache and hidePopup clear logic', () => {
+ it('preserves explicit automatic relayout for dynamic cell popups', () => {
+ const sheetPopupService = {
+ attachPopupToCell: vi.fn(() => ({ dispose: vi.fn() })),
+ };
+ const service = new CellPopupManagerService(sheetPopupService as never);
+ const location = { unitId: 'unit-1', subUnitId: 'sheet-1', row: 4, col: 5 };
+
+ service.showPopup(location, {
+ componentKey: 'dynamic-popup',
+ priority: 1,
+ autoRelayout: true,
+ } as never);
+
+ expect(sheetPopupService.attachPopupToCell).toHaveBeenCalledWith(
+ location.row,
+ location.col,
+ expect.objectContaining({ autoRelayout: true }),
+ location.unitId,
+ location.subUnitId
+ );
+ });
+
+ it('supports vertical and left caches in hidePopup clear logic', () => {
const horizontalDisposable = { dispose: vi.fn() };
const verticalDisposable = { dispose: vi.fn() };
+ const leftDisposable = { dispose: vi.fn() };
const sheetPopupService = {
attachPopupToCell: vi
.fn()
.mockReturnValueOnce(horizontalDisposable)
- .mockReturnValueOnce(verticalDisposable),
+ .mockReturnValueOnce(verticalDisposable)
+ .mockReturnValueOnce(leftDisposable),
};
- const service = new CellPopupManagerService(sheetPopupService as any);
- const changes: any[] = [];
+ const service = new CellPopupManagerService(sheetPopupService as never);
+ const changes: ICellPopupChange[] = [];
service.change$.subscribe((change) => changes.push(change));
const location = { unitId: 'unit-2', subUnitId: 'sheet-2', row: 1, col: 2 };
@@ -71,22 +96,31 @@ describe('CellPopupManagerService', () => {
componentKey: 'h',
direction: 'horizontal',
priority: 1,
- } as any);
+ } as never);
service.showPopup(location, {
id: 'v1',
componentKey: 'v',
direction: 'vertical',
priority: 2,
- } as any);
+ } as never);
+ service.showPopup(location, {
+ id: 'l1',
+ componentKey: 'l',
+ direction: 'left-center',
+ priority: 3,
+ } as never);
expect(service.getPopups('unit-2', 'sheet-2', 1, 2, 'horizontal').length).toBe(1);
expect(service.getPopups('unit-2', 'sheet-2', 1, 2, 'vertical').length).toBe(1);
+ expect(service.getPopups('unit-2', 'sheet-2', 1, 2, 'left-center').length).toBe(1);
service.hidePopup('unit-2', 'sheet-2', 1, 2);
expect(horizontalDisposable.dispose).toHaveBeenCalled();
expect(verticalDisposable.dispose).toHaveBeenCalled();
+ expect(leftDisposable.dispose).toHaveBeenCalled();
expect(service.getPopups('unit-2', 'sheet-2', 1, 2, 'horizontal')).toEqual([]);
expect(service.getPopups('unit-2', 'sheet-2', 1, 2, 'vertical')).toEqual([]);
+ expect(service.getPopups('unit-2', 'sheet-2', 1, 2, 'left-center')).toEqual([]);
// No-op branch.
service.hidePopup('unit-2', 'sheet-2', 9, 9);
@@ -96,6 +130,7 @@ describe('CellPopupManagerService', () => {
.map((change) => change.direction);
expect(directions.includes('horizontal')).toBe(true);
expect(directions.includes('vertical')).toBe(true);
+ expect(directions.includes('left-center')).toBe(true);
});
it('clears all popups for a workbook unit', () => {
@@ -106,18 +141,18 @@ describe('CellPopupManagerService', () => {
.mockReturnValueOnce(disposables[0])
.mockReturnValueOnce(disposables[1]),
};
- const service = new CellPopupManagerService(sheetPopupService as any);
+ const service = new CellPopupManagerService(sheetPopupService as never);
service.showPopup({ unitId: 'unit-3', subUnitId: 'sheet-a', row: 1, col: 1 }, {
id: 'a',
componentKey: 'a',
priority: 1,
- } as any);
+ } as never);
service.showPopup({ unitId: 'unit-3', subUnitId: 'sheet-b', row: 2, col: 2 }, {
id: 'b',
componentKey: 'b',
priority: 1,
- } as any);
+ } as never);
service.hidePopupsForUnit('unit-3');
diff --git a/packages/sheets-ui/src/services/cell-alert-manager.service.ts b/packages/sheets-ui/src/services/cell-alert-manager.service.ts
index 7ab4a881d8..3f9b70b2a1 100644
--- a/packages/sheets-ui/src/services/cell-alert-manager.service.ts
+++ b/packages/sheets-ui/src/services/cell-alert-manager.service.ts
@@ -29,6 +29,12 @@ export enum CellAlertType {
ERROR,
}
+export interface ICellAlertMenuItem {
+ label: ReactNode;
+ disabled?: boolean;
+ onSelect: () => void;
+}
+
export interface ICellAlert {
type: CellAlertType;
title: ReactNode;
@@ -37,6 +43,7 @@ export interface ICellAlert {
width: number;
height: number;
key: string;
+ menu?: ICellAlertMenuItem[];
}
export class CellAlertManagerService extends Disposable {
@@ -96,7 +103,9 @@ export class CellAlertManagerService extends Disposable {
},
{
componentKey: CELL_ALERT_KEY,
- direction: 'horizontal',
+ direction: alert.menu?.length ? 'left-center' : 'horizontal',
+ autoRelayout: Boolean(alert.menu?.length),
+ showOnSelectionMoving: Boolean(alert.menu?.length),
extraProps: {
alert,
},
diff --git a/packages/sheets-ui/src/services/cell-popup-manager.service.ts b/packages/sheets-ui/src/services/cell-popup-manager.service.ts
index 39f0d5c5cb..a43a0dee92 100644
--- a/packages/sheets-ui/src/services/cell-popup-manager.service.ts
+++ b/packages/sheets-ui/src/services/cell-popup-manager.service.ts
@@ -16,14 +16,19 @@
import type { IDisposable } from '@univerjs/core';
import type { ISheetLocationBase } from '@univerjs/sheets';
+import type { RectPopupDirection } from '@univerjs/ui';
import type { ICanvasPopup } from './canvas-pop-manager.service';
import { Disposable, generateRandomId, Inject, ObjectMatrix, toDisposable } from '@univerjs/core';
import { Subject } from 'rxjs';
import { CELL_POPUP_COMPONENT_KEY } from '../views/cell-popup/config';
import { SheetCanvasPopManagerService } from './canvas-pop-manager.service';
+export type CellPopupDirection = Extract<RectPopupDirection, 'horizontal' | 'vertical' | 'left-center'>;
+
+const CELL_POPUP_DIRECTIONS: CellPopupDirection[] = ['horizontal', 'vertical', 'left-center'];
+
export interface ICellPopup extends Omit<ICanvasPopup, 'direction' | 'offset' | 'mask'> {
- direction?: 'horizontal' | 'vertical';
+ direction?: CellPopupDirection;
id?: string;
priority: number;
}
@@ -33,13 +38,10 @@ export interface ICellPopupDirectionCache {
disposable?: IDisposable;
}
-export interface ICellPopupCache {
- horizontal?: ICellPopupDirectionCache;
- vertical?: ICellPopupDirectionCache;
-}
+export type ICellPopupCache = Partial<Record<CellPopupDirection, ICellPopupDirectionCache>>;
export interface ICellPopupChange extends ISheetLocationBase {
- direction: 'horizontal' | 'vertical';
+ direction: CellPopupDirection;
}
export class CellPopupManagerService extends Disposable {
@@ -112,7 +114,7 @@ export class CellPopupManagerService extends Disposable {
direction,
},
noPushMinimumGap: true,
- autoRelayout: false,
+ autoRelayout: popup.autoRelayout ?? false,
zIndex: 90,
},
unitId,
@@ -139,7 +141,7 @@ export class CellPopupManagerService extends Disposable {
return toDisposable(hidePopup);
}
- getPopups(unitId: string, subUnitId: string, row: number, col: number, direction: 'horizontal' | 'vertical') {
+ getPopups(unitId: string, subUnitId: string, row: number, col: number, direction: CellPopupDirection) {
const subUnitMap = this._ensureCellPopupMap(unitId, subUnitId);
return subUnitMap.getValue(row, col)?.[direction]?.popups || [];
}
@@ -151,34 +153,18 @@ export class CellPopupManagerService extends Disposable {
return;
}
- // Hide horizontal popups
- if (cache.horizontal) {
- cache.horizontal.disposable?.dispose();
- cache.horizontal = undefined;
- this._change$.next({
- unitId,
- subUnitId,
- row,
- col,
- direction: 'horizontal',
- });
- }
+ CELL_POPUP_DIRECTIONS.forEach((direction) => {
+ const directionCache = cache[direction];
+ if (!directionCache) {
+ return;
+ }
- // Hide vertical popups
- if (cache.vertical) {
- cache.vertical.disposable?.dispose();
- cache.vertical = undefined;
- this._change$.next({
- unitId,
- subUnitId,
- row,
- col,
- direction: 'vertical',
- });
- }
+ directionCache.disposable?.dispose();
+ cache[direction] = undefined;
+ this._change$.next({ unitId, subUnitId, row, col, direction });
+ });
- // Clear the cache if both directions are empty
- if (!cache.horizontal && !cache.vertical) {
+ if (CELL_POPUP_DIRECTIONS.every((direction) => !cache[direction])) {
subUnitMap.realDeleteValue(row, col);
}
}
diff --git a/packages/sheets-ui/src/views/CellPopup.tsx b/packages/sheets-ui/src/views/CellPopup.tsx
index 6dc1b077d8..62dec48777 100644
--- a/packages/sheets-ui/src/views/CellPopup.tsx
+++ b/packages/sheets-ui/src/views/CellPopup.tsx
@@ -16,12 +16,13 @@
import type { ISheetLocationBase } from '@univerjs/sheets';
import type { IPopupWithExtraProps } from '@univerjs/ui';
+import type { CellPopupDirection } from '../services/cell-popup-manager.service';
import { ComponentManager, useDependency, useObservable } from '@univerjs/ui';
import { useMemo } from 'react';
import { filter, map } from 'rxjs';
import { CellPopupManagerService } from '../services/cell-popup-manager.service';
-export const CellPopup = (props: { popup: IPopupWithExtraProps<ISheetLocationBase & { direction: 'horizontal' | 'vertical' }> }) => {
+export const CellPopup = (props: { popup: IPopupWithExtraProps<ISheetLocationBase & { direction: CellPopupDirection }> }) => {
const { popup } = props;
const location = popup.extraProps;
const { row, col, direction, unitId, subUnitId } = location;
@@ -36,7 +37,13 @@ export const CellPopup = (props: { popup: IPopupWithExtraProps<ISheetLocationBas
const componentManager = useDependency(ComponentManager);
return (
- <div data-u-comp="sheets-ui-cell-popup" className="univer-ml-px univer-flex univer-flex-col">
+ <div
+ data-u-comp="sheets-ui-cell-popup"
+ className={`
+ ${direction === 'left-center' ? 'univer-mr-px' : 'univer-ml-px'}
+ univer-flex univer-flex-col
+ `}
+ >
{popups.map((popup) => {
const Component = componentManager.get(popup.componentKey);
return Component ? <Component key={popup.id ?? popup.componentKey} popup={popup} /> : null;
diff --git a/packages/sheets-ui/src/views/cell-alert/CellAlertPopup.tsx b/packages/sheets-ui/src/views/cell-alert/CellAlertPopup.tsx
index 1e0c6b36ed..ea03a54893 100644
--- a/packages/sheets-ui/src/views/cell-alert/CellAlertPopup.tsx
+++ b/packages/sheets-ui/src/views/cell-alert/CellAlertPopup.tsx
@@ -16,7 +16,9 @@
import type { ICanvasPopup } from '../../services/canvas-pop-manager.service';
import type { ICellAlert } from '../../services/cell-alert-manager.service';
-import { ErrorIcon, InfoIcon, WarningIcon } from '@univerjs/icons';
+import { DropdownMenu } from '@univerjs/design';
+import { ErrorIcon, InfoIcon, MoreDownIcon, WarningIcon } from '@univerjs/icons';
+import { useState } from 'react';
import { CellAlertType } from '../../services/cell-alert-manager.service';
/**
@@ -25,12 +27,75 @@ import { CellAlertType } from '../../services/cell-alert-manager.service';
* @param root0.popup
*/
export function CellAlert({ popup }: { popup: ICanvasPopup }) {
+ const [visible, setVisible] = useState(false);
+ const [isHovered, setIsHovered] = useState(false);
const alert = popup.extraProps?.alert;
if (!alert) {
return null;
}
- const { type, title, message } = alert as ICellAlert;
+ const { type, title, message, menu } = alert as ICellAlert;
+
+ if (menu?.length) {
+ const accessibleLabel = [title, message]
+ .filter((value): value is string => typeof value === 'string')
+ .join(': ');
+ const showMore = visible || isHovered;
+
+ return (
+ <div
+ onMouseEnter={() => setIsHovered(true)}
+ onMouseLeave={() => setIsHovered(false)}
+ >
+ <DropdownMenu
+ align="start"
+ open={visible}
+ onOpenChange={setVisible}
+ items={[
+ {
+ type: 'custom',
+ className: `
+ univer-px-2 univer-py-1.5 univer-font-medium univer-text-gray-900
+ dark:!univer-text-white
+ `,
+ children: message,
+ },
+ {
+ type: 'separator',
+ },
+ ...menu.map((item) => ({
+ type: 'item' as const,
+ children: item.label,
+ disabled: item.disabled,
+ onSelect: item.onSelect,
+ })),
+ ]}
+ >
+ <button
+ type="button"
+ aria-label={accessibleLabel || undefined}
+ className={`
+ univer-flex univer-items-center univer-gap-1 univer-rounded univer-border univer-border-solid
+ univer-border-gray-200 univer-bg-white univer-p-1 univer-shadow
+ hover:univer-bg-gray-100
+ dark:!univer-border-gray-600 dark:!univer-bg-gray-900
+ dark:hover:!univer-bg-gray-800
+ `}
+ >
+ <WarningIcon className="univer-text-yellow-500" />
+ {showMore && (
+ <MoreDownIcon
+ className={`
+ univer-text-gray-600
+ dark:!univer-text-gray-300
+ `}
+ />
+ )}
+ </button>
+ </DropdownMenu>
+ </div>
+ );
+ }
const iconMap = {
[CellAlertType.ERROR]: <ErrorIcon className="univer-mr-1.5 univer-text-red-500" />,
diff --git a/packages/sheets/src/commands/commands/__tests__/simple-command-handlers.spec.ts b/packages/sheets/src/commands/commands/__tests__/simple-command-handlers.spec.ts
index 7d9e6d75d2..53baf9704f 100644
--- a/packages/sheets/src/commands/commands/__tests__/simple-command-handlers.spec.ts
+++ b/packages/sheets/src/commands/commands/__tests__/simple-command-handlers.spec.ts
@@ -434,6 +434,7 @@ describe('TextToNumberCommand', () => {
0: { v: '42', t: CellValueType.STRING },
1: { v: '003', t: CellValueType.NUMBER, s: 'text-style' },
2: { v: 'abc', t: CellValueType.STRING },
+ 3: { v: '20%', t: CellValueType.FORCE_STRING },
},
});
const worksheet = {
@@ -455,9 +456,9 @@ describe('TextToNumberCommand', () => {
expect(TextToNumberCommand.handler(accessor, {
unitId: 'unit-1',
subUnitId: 'sheet-1',
- ranges: [{ startRow: 0, endRow: 0, startColumn: 0, endColumn: 2 }],
+ ranges: [{ startRow: 0, endRow: 0, startColumn: 0, endColumn: 3 }],
})).toBe(true);
- expect(executed.map((call) => call.id)).toEqual([SetRangeValuesMutation.id, RemoveNumfmtMutation.id]);
+ expect(executed.map((call) => call.id)).toEqual([SetRangeValuesMutation.id, SetNumfmtMutation.id, RemoveNumfmtMutation.id]);
expect(executed[0].params).toMatchObject({
unitId: 'unit-1',
subUnitId: 'sheet-1',
@@ -465,17 +466,32 @@ describe('TextToNumberCommand', () => {
0: {
0: { v: 42, t: CellValueType.NUMBER },
1: { v: 3, t: CellValueType.NUMBER },
+ 3: { v: 0.2, t: CellValueType.NUMBER },
},
},
});
- expect(executed[1].params).toEqual({
+ expect(executed[1].params).toMatchObject({
+ unitId: 'unit-1',
+ subUnitId: 'sheet-1',
+ refMap: {
+ 0: { pattern: '0%' },
+ },
+ values: {
+ 0: { ranges: [{ startRow: 0, endRow: 0, startColumn: 3, endColumn: 3 }] },
+ },
+ });
+ expect(executed[2].params).toEqual({
unitId: 'unit-1',
subUnitId: 'sheet-1',
ranges: [{ startRow: 0, endRow: 0, startColumn: 1, endColumn: 1 }],
});
expect(undoRecords[0]).toMatchObject({
unitID: 'unit-1',
- undoMutations: [{ id: SetRangeValuesMutation.id }, { id: SetNumfmtMutation.id }],
+ undoMutations: [
+ { id: SetRangeValuesMutation.id },
+ { id: RemoveNumfmtMutation.id },
+ { id: SetNumfmtMutation.id },
+ ],
});
});
diff --git a/packages/sheets/src/commands/commands/text-to-number.command.ts b/packages/sheets/src/commands/commands/text-to-number.command.ts
index a0c9d52516..2b9c921e80 100644
--- a/packages/sheets/src/commands/commands/text-to-number.command.ts
+++ b/packages/sheets/src/commands/commands/text-to-number.command.ts
@@ -15,12 +15,13 @@
*/
import type { IAccessor, ICellData, ICommand, IRange } from '@univerjs/core';
-import type { IRemoveNumfmtMutationParams } from '../mutations/numfmt.mutation';
+import type { IRemoveNumfmtMutationParams, ISetCellsNumfmt } from '../mutations/numfmt.mutation';
import type { ISetRangeValuesMutationParams } from '../mutations/set-range-values.mutation';
import type { ISheetCommandSharedParams } from '../utils/interface';
import {
CellValueType,
CommandType,
+ getNumfmtParseValueFilter,
ICommandService,
isRealNum,
isTextFormat,
@@ -30,7 +31,13 @@ import {
sequenceExecute,
} from '@univerjs/core';
import { SheetsSelectionsService } from '../../services/selections/selection.service';
-import { factoryRemoveNumfmtUndoMutation, RemoveNumfmtMutation } from '../mutations/numfmt.mutation';
+import {
+ factoryRemoveNumfmtUndoMutation,
+ factorySetNumfmtUndoMutation,
+ RemoveNumfmtMutation,
+ SetNumfmtMutation,
+ transformCellsToRange,
+} from '../mutations/numfmt.mutation';
import { SetRangeValuesMutation, SetRangeValuesUndoMutationFactory } from '../mutations/set-range-values.mutation';
import { getSheetCommandTarget } from './utils/target-util';
@@ -61,6 +68,7 @@ export const TextToNumberCommand: ICommand = {
const { worksheet, unitId, subUnitId } = target;
const newCellValue = new ObjectMatrix<ICellData>();
+ const setNumfmtCells: ISetCellsNumfmt = [];
const removeNumfmtRanges: IRange[] = [];
for (let i = 0; i < ranges.length; i++) {
@@ -72,14 +80,24 @@ export const TextToNumberCommand: ICommand = {
const cell = worksheet.getCellRaw(r, c);
const pattern = typeof cell?.s === 'string' ? worksheet.getStyleDataByHash(cell.s)?.n?.pattern : cell?.s?.n?.pattern;
+ const parsedValue = typeof cell?.v === 'string' ? getNumfmtParseValueFilter(cell.v) : null;
+ const numberValue = isRealNum(cell?.v)
+ ? Number(cell?.v)
+ : typeof parsedValue?.v === 'number' ? parsedValue.v : null;
- if (cell && cell.v && (cell.t !== CellValueType.NUMBER || isTextFormat(pattern)) && isRealNum(cell.v)) {
+ if (cell && cell.v && (cell.t !== CellValueType.NUMBER || isTextFormat(pattern)) && numberValue !== null) {
newCellValue.setValue(r, c, {
- v: Number(cell.v),
+ v: numberValue,
t: CellValueType.NUMBER,
});
- if (isTextFormat(pattern)) {
+ if (parsedValue?.z && (!pattern || isTextFormat(pattern))) {
+ setNumfmtCells.push({
+ pattern: parsedValue.z,
+ row: r,
+ col: c,
+ });
+ } else if (isTextFormat(pattern)) {
removeNumfmtRanges.push({
startRow: r,
endRow: r,
@@ -110,6 +128,15 @@ export const TextToNumberCommand: ICommand = {
},
];
+ if (setNumfmtCells.length) {
+ const setNumfmtMutationParams = transformCellsToRange(unitId, subUnitId, setNumfmtCells);
+ redos.push({
+ id: SetNumfmtMutation.id,
+ params: setNumfmtMutationParams,
+ });
+ undos.push(...factorySetNumfmtUndoMutation(accessor, setNumfmtMutationParams));
+ }
+
if (removeNumfmtRanges.length) {
const removeNumfmtMutationParams: IRemoveNumfmtMutationParams = {
unitId,
diff --git a/packages/sheets/src/controllers/permission/sheet-permission-check.controller.ts b/packages/sheets/src/controllers/permission/sheet-permission-check.controller.ts
index 9f9b2de2b7..c8996ab9fc 100644
--- a/packages/sheets/src/controllers/permission/sheet-permission-check.controller.ts
+++ b/packages/sheets/src/controllers/permission/sheet-permission-check.controller.ts
@@ -54,6 +54,7 @@ import type {
ISetWorksheetRowIsAutoHeightCommandParams,
} from '../../commands/commands/set-worksheet-row-height.command';
import type { ISetWorksheetShowCommandParams } from '../../commands/commands/set-worksheet-show.command';
+import type { ITextToNumberCommandParams } from '../../commands/commands/text-to-number.command';
import type { LocaleKey } from '../../locale/types';
import {
CustomCommandExecutionError,
@@ -116,6 +117,7 @@ import {
SetWorksheetRowIsAutoHeightCommand,
} from '../../commands/commands/set-worksheet-row-height.command';
import { SetWorksheetShowCommand } from '../../commands/commands/set-worksheet-show.command';
+import { TextToNumberCommand } from '../../commands/commands/text-to-number.command';
import { getSheetCommandTarget } from '../../commands/commands/utils/target-util';
import { SetWorksheetNameMutation } from '../../commands/mutations/set-worksheet-name.mutation';
import { RangeProtectionRuleModel } from '../../models/range-protection-rule.model';
@@ -552,6 +554,22 @@ export class SheetPermissionCheckController extends Disposable {
errorMsg = this._localeService.t<LocaleKey>('sheets.permission.dialog.editErr');
break;
+ // text to number
+ case TextToNumberCommand.id:
+ params = commandInfo.params as ITextToNumberCommandParams | undefined;
+ permission = this.permissionCheckWithRanges(
+ {
+ workbookTypes: [WorkbookEditablePermission],
+ worksheetTypes: [WorksheetSetCellValuePermission, WorksheetSetCellStylePermission, WorksheetEditPermission],
+ rangeTypes: [RangeProtectionPermissionEditPoint],
+ },
+ params?.ranges,
+ params?.unitId,
+ params?.subUnitId
+ );
+ errorMsg = this._localeService.t<LocaleKey>('sheets.permission.dialog.editErr');
+ break;
+
default:
break;
}