Build your own AI office with Univer Office SDK. Bring editing, calculation, collaboration, and file processing into your product for people and AI agents. Built on an extensible open-source core.
TypeScript boardcollaborationdocdocxexceloffce365officepdfpptpptxpresentationsdksheetslidesspreadsheetuniverwordwordprocessorworkspacexlsx
feat(sheet): force string adds popup (#1934)
Dushusiradd121435f52
diff --git a/packages/engine-render/src/components/sheets/sheet-skeleton.ts b/packages/engine-render/src/components/sheets/sheet-skeleton.tsindex a461d7a2b4..395cfc6998 100644--- a/packages/engine-render/src/components/sheets/sheet-skeleton.ts+++ b/packages/engine-render/src/components/sheets/sheet-skeleton.ts@@ -1117,7 +1117,15 @@ export class SpreadsheetSkeleton extends Skeleton {const textStyle = this._getFontFormat(style);fontString = getFontStyleString(textStyle, this._localService).fontCache;- documentModel = this._getDocumentDataByStyle(extractPureTextFromCell(cell), textStyle, {+ let cellText = extractPureTextFromCell(cell);++ // Add a single quotation mark to the force string type. Don't add single quotation mark in extractPureTextFromCell, because copy and paste will be affected.+ // edit mode when displayRawFormula is true+ if (cell.t === CellValueType.FORCE_STRING && displayRawFormula) {+ cellText = `'${cellText}`;+ }++ documentModel = this._getDocumentDataByStyle(cellText, textStyle, {...cellOtherConfig,textRotation,cellValueType: cell.t!,diff --git a/packages/sheets-ui/src/controllers/editor/__tests__/end-edit.controller.spec.ts b/packages/sheets-ui/src/controllers/editor/__tests__/end-edit.controller.spec.tsindex ef8220b018..49f1296bf1 100644--- a/packages/sheets-ui/src/controllers/editor/__tests__/end-edit.controller.spec.ts+++ b/packages/sheets-ui/src/controllers/editor/__tests__/end-edit.controller.spec.ts@@ -14,8 +14,8 @@* limitations under the License.*/-import type { IDocumentData, Univer, Workbook } from '@univerjs/core';-import { IContextService, LocaleService } from '@univerjs/core';+import type { ICellData, IDocumentData, Univer, Workbook } from '@univerjs/core';+import { CellValueType, IContextService, LocaleService } from '@univerjs/core';import { LexerTreeBuilder } from '@univerjs/engine-formula';import { SpreadsheetSkeleton } from '@univerjs/engine-render';import type { Injector } from '@wendellhu/redi';@@ -77,6 +77,7 @@ describe('Test EndEditController', () => {let contextService: IContextService;let lexerTreeBuilder: LexerTreeBuilder;let spreadsheetSkeleton: SpreadsheetSkeleton;+ let getCellDataByInputCell: (cell: ICellData, inputCell: ICellData) => ICellData | null;beforeEach(() => {const testBed = createTestBed();@@ -99,14 +100,23 @@ describe('Test EndEditController', () => {localeService,contextService);++ getCellDataByInputCell = (cell: ICellData, inputCell: ICellData) => {+ const documentLayoutObject = spreadsheetSkeleton.getCellDocumentModelWithFormula(inputCell);+ if (!documentLayoutObject) {+ throw new Error('documentLayoutObject is undefined');+ }++ return getCellDataByInput(cell, documentLayoutObject, lexerTreeBuilder);+ };});afterEach(() => {univer.dispose();});- describe('getCellDataByInput', () => {- it('normal cell', () => {+ describe('Function getCellDataByInput', () => {+ it('Normal cell', () => {const cell = {v: 1,};@@ -115,16 +125,10 @@ describe('Test EndEditController', () => {v: 2,};- const documentLayoutObject = spreadsheetSkeleton.getCellDocumentModelWithFormula(inputCell);- if (!documentLayoutObject) {- expect(documentLayoutObject).not.toBeUndefined();- return;- }-- const cellData = getCellDataByInput(cell, documentLayoutObject, lexerTreeBuilder);+ const cellData = getCellDataByInputCell(cell, inputCell);expect(cellData).toEqual({ v: '2', f: null, si: null, p: null });});- it('rich text cell', () => {+ it('Rich text cell', () => {const cell = {v: 1,};@@ -132,16 +136,10 @@ describe('Test EndEditController', () => {p: richTextDemo,};- const documentLayoutObject = spreadsheetSkeleton.getCellDocumentModelWithFormula(inputCell);- if (!documentLayoutObject) {- expect(documentLayoutObject).not.toBeUndefined();- return;- }-- const cellData = getCellDataByInput(cell, documentLayoutObject, lexerTreeBuilder);+ const cellData = getCellDataByInputCell(cell, inputCell);expect(cellData).toEqual({ v: null, f: null, si: null, p: richTextDemo });});- it('formula cell', () => {+ it('Formula cell', () => {const cell = {v: 1,};@@ -149,16 +147,10 @@ describe('Test EndEditController', () => {f: '=SUM(1)',};- const documentLayoutObject = spreadsheetSkeleton.getCellDocumentModelWithFormula(inputCell);- if (!documentLayoutObject) {- expect(documentLayoutObject).not.toBeUndefined();- return;- }-- const cellData = getCellDataByInput(cell, documentLayoutObject, lexerTreeBuilder);+ const cellData = getCellDataByInputCell(cell, inputCell);expect(cellData).toEqual({ v: null, f: '=SUM(1)', p: null });});- it('clear formula cell', () => {+ it('Clear formula cell', () => {const cell = {f: '=H18:H25',v: 0,@@ -169,14 +161,38 @@ describe('Test EndEditController', () => {v: '',};- const documentLayoutObject = spreadsheetSkeleton.getCellDocumentModelWithFormula(inputCell);- if (!documentLayoutObject) {- expect(documentLayoutObject).not.toBeUndefined();- return;- }-- const cellData = getCellDataByInput(cell, documentLayoutObject, lexerTreeBuilder);+ const cellData = getCellDataByInputCell(cell, inputCell);expect(cellData).toEqual({ v: '', f: null, si: null, p: null, t: undefined });});++ it('Clear formula cell with rich text', () => {+ const cell = {+ f: '=H18:H25',+ v: 0,+ t: 2,+ };++ const inputCell = {+ p: richTextDemo,+ };++ const cellData = getCellDataByInputCell(cell, inputCell);+ expect(cellData).toEqual({ v: null, f: null, si: null, p: richTextDemo, t: undefined });+ });++ it('Input force string, normal string', () => {+ const cell = {+ v: null,+ };++ let cellData = getCellDataByInputCell(cell, { v: "'test" });+ expect(cellData).toEqual({ v: 'test', t: CellValueType.FORCE_STRING, f: null, si: null, p: null });++ cellData = getCellDataByInputCell(cell, { v: "'1" });+ expect(cellData).toEqual({ v: '1', t: CellValueType.FORCE_STRING, f: null, si: null, p: null });++ cellData = getCellDataByInputCell(cell, { v: "'=SUM" });+ expect(cellData).toEqual({ v: '=SUM', t: CellValueType.FORCE_STRING, f: null, si: null, p: null });+ });});});diff --git a/packages/sheets-ui/src/controllers/editor/end-edit.controller.ts b/packages/sheets-ui/src/controllers/editor/end-edit.controller.tsindex 4053e9d14b..3043d82001 100644--- a/packages/sheets-ui/src/controllers/editor/end-edit.controller.ts+++ b/packages/sheets-ui/src/controllers/editor/end-edit.controller.ts@@ -15,7 +15,7 @@*/import type { ICellData, ICommandInfo, IDocumentBody, Nullable, Observer } from '@univerjs/core';-import {+import { CellValueType,DEFAULT_EMPTY_DOCUMENT_VALUE,Direction,Disposable,@@ -54,6 +54,7 @@ import { ICellEditorManagerService } from '../../services/editor/cell-editor-manimport type { IEditorBridgeServiceVisibleParam } from '../../services/editor-bridge.service';import { IEditorBridgeService } from '../../services/editor-bridge.service';import { MOVE_SELECTION_KEYCODE_LIST } from '../shortcuts/editor.shortcut';+import { extractStringFromForceString, isForceString } from '../utils/cell-tools';function isRichText(body: IDocumentBody) {const { textRuns = [], paragraphs = [] } = body;@@ -430,6 +431,13 @@ export function getCellDataByInput(cellData.f = newDataStream;cellData.v = null;cellData.p = null;+ } else if (isForceString(newDataStream)) {+ const v = extractStringFromForceString(newDataStream);+ cellData.v = v;+ cellData.f = null;+ cellData.si = null;+ cellData.p = null;+ cellData.t = CellValueType.FORCE_STRING;} else if (isRichText(body)) {if (body.dataStream === '\r\n') {cellData.v = '';diff --git a/packages/sheets-ui/src/controllers/force-string-alert.controller.ts b/packages/sheets-ui/src/controllers/force-string-alert.controller.tsnew file mode 100644index 0000000000..539d84b3f1--- /dev/null+++ b/packages/sheets-ui/src/controllers/force-string-alert.controller.ts@@ -0,0 +1,78 @@+/**+ * Copyright 2023-present DreamNum Inc.+ *+ * 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 { Workbook } from '@univerjs/core';+import { CellValueType, Disposable, isRealNum, IUniverInstanceService, LifecycleStages, LocaleService, OnLifecycle, UniverInstanceType } from '@univerjs/core';++import { Inject } from '@wendellhu/redi';+import { HoverManagerService } from '../services/hover-manager.service';+import { CellAlertManagerService, CellAlertType } from '../services/cell-alert-manager.service';++const ALERT_KEY = 'SHEET_FORCE_STRING_ALERT';++@OnLifecycle(LifecycleStages.Rendered, ForceStringAlertController)+export class ForceStringAlertController extends Disposable {+ constructor(+ @Inject(HoverManagerService) private readonly _hoverManagerService: HoverManagerService,+ @Inject(CellAlertManagerService) private readonly _cellAlertManagerService: CellAlertManagerService,+ @IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService,+ @Inject(LocaleService) private readonly _localeService: LocaleService+ ) {+ super();+ this._init();+ }++ private _init() {+ this._initCellAlertPopup();+ }++ private _initCellAlertPopup() {+ this.disposeWithMe(this._hoverManagerService.currentCell$.subscribe((cellPos) => {+ if (cellPos) {+ const workbook = this._univerInstanceService.getCurrentUnitForType<Workbook>(UniverInstanceType.SHEET)!;+ const worksheet = workbook.getActiveSheet();+ const cellData = worksheet.getCell(cellPos.location.row, cellPos.location.col);++ if (cellData?.t === CellValueType.FORCE_STRING && cellData.v && isRealNum(cellData.v)) {+ 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+ ) {+ return;+ }++ this._cellAlertManagerService.showAlert({+ type: CellAlertType.ERROR,+ title: this._localeService.t('info.error'),+ message: this._localeService.t('info.forceStringInfo'),+ location: cellPos.location,+ width: 200,+ height: 74,+ key: ALERT_KEY,+ });+ return;+ }+ }++ this._cellAlertManagerService.removeAlert(ALERT_KEY);+ }));+ }+}diff --git a/packages/sheets-ui/src/controllers/force-string-render.controller.ts b/packages/sheets-ui/src/controllers/force-string-render.controller.tsnew file mode 100644index 0000000000..fdee39451a--- /dev/null+++ b/packages/sheets-ui/src/controllers/force-string-render.controller.ts@@ -0,0 +1,84 @@+/**+ * Copyright 2023-present DreamNum Inc.+ *+ * 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 { CellValueType, isRealNum, LifecycleStages, OnLifecycle, RxDisposable, ThemeService } from '@univerjs/core';+import { Inject } from '@wendellhu/redi';+import { INTERCEPTOR_POINT, SheetInterceptorService } from '@univerjs/sheets';+import { SheetSkeletonManagerService } from '../services/sheet-skeleton-manager.service';++/**+ * @todo RenderUnit+ */+@OnLifecycle(LifecycleStages.Rendered, ForceStringRenderController)+export class ForceStringRenderController extends RxDisposable {+ constructor(+ @Inject(SheetSkeletonManagerService) private readonly _sheetSkeletonManagerService: SheetSkeletonManagerService,+ @Inject(SheetInterceptorService) private readonly _sheetInterceptorService: SheetInterceptorService,+ @Inject(ThemeService) private readonly _themeService: ThemeService+ ) {+ super();+ this._init();+ }++ private _init() {+ this._initViewModelIntercept();+ }+++ private _initViewModelIntercept() {+ const color = this._themeService.getCurrentTheme().errorColor;+ const FORCE_STRING_MARK = {+ tr: {+ size: 6,+ color,+ },+ };++ this.disposeWithMe(+ this._sheetInterceptorService.intercept(+ INTERCEPTOR_POINT.CELL_CONTENT,+ {++ handler: (cell, pos, next) => {+ const skeleton = this._sheetSkeletonManagerService.getCurrent()?.skeleton;+ if (!skeleton) {+ return next(cell);+ }++ const cellRaw = pos.worksheet.getCellRaw(pos.row, pos.col);++ if (!cellRaw || cellRaw.v === null || cellRaw.v === undefined) {+ return next(cell);+ }++ if (cell?.t === CellValueType.FORCE_STRING && isRealNum(cellRaw.v)) {+ return next({+ ...cell,+ markers: {+ ...cell?.markers,+ ...FORCE_STRING_MARK,+ },+ });+ }++ return next(cell);+ },+ }+ )+ );+ }+}diff --git a/packages/sheets-ui/src/controllers/utils/__tests__/cell-tools.spec.ts b/packages/sheets-ui/src/controllers/utils/__tests__/cell-tools.spec.tsnew file mode 100644index 0000000000..cf17585ce7--- /dev/null+++ b/packages/sheets-ui/src/controllers/utils/__tests__/cell-tools.spec.ts@@ -0,0 +1,70 @@+/**+ * Copyright 2023-present DreamNum Inc.+ *+ * 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 { describe, expect, it } from 'vitest';+import { extractStringFromForceString, isForceString } from '../cell-tools';++describe('Test cell tools', () => {+ it('Function isForceString', () => {+ let str = "'test";+ expect(isForceString(str)).toBeTruthy();+ expect(extractStringFromForceString(str)).toBe('test');++ str = "'1";+ expect(isForceString(str)).toBeTruthy();+ expect(extractStringFromForceString(str)).toBe('1');++ str = "'=SUM";+ expect(isForceString(str)).toBeTruthy();+ expect(extractStringFromForceString(str)).toBe('=SUM');++ str = "''";+ expect(isForceString(str)).toBeTruthy();+ expect(extractStringFromForceString(str)).toBe("'");++ str = "'1e+3";+ expect(isForceString(str)).toBeTruthy();+ expect(extractStringFromForceString(str)).toBe('1e+3');++ str = "'-1";+ expect(isForceString(str)).toBeTruthy();+ expect(extractStringFromForceString(str)).toBe('-1');++ str = '\'"2"';+ expect(isForceString(str)).toBeTruthy();+ expect(extractStringFromForceString(str)).toBe('"2"');++ str = "'0";+ expect(isForceString(str)).toBeTruthy();+ expect(extractStringFromForceString(str)).toBe('0');++ str = "'null";+ expect(isForceString(str)).toBeTruthy();+ expect(extractStringFromForceString(str)).toBe('null');++ str = "'1e";+ expect(isForceString(str)).toBeTruthy();+ expect(extractStringFromForceString(str)).toBe('1e');++ str = "'.2";+ expect(isForceString(str)).toBeTruthy();+ expect(extractStringFromForceString(str)).toBe('.2');++ expect(isForceString('=sum')).toBeFalsy();+ expect(isForceString('1')).toBeFalsy();+ expect(isForceString('test')).toBeFalsy();+ });+});diff --git a/packages/sheets-ui/src/controllers/utils/cell-tools.ts b/packages/sheets-ui/src/controllers/utils/cell-tools.tsnew file mode 100644index 0000000000..ab80d7d54e--- /dev/null+++ b/packages/sheets-ui/src/controllers/utils/cell-tools.ts@@ -0,0 +1,23 @@+/**+ * Copyright 2023-present DreamNum Inc.+ *+ * 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.+ */++export function isForceString(str: string): boolean {+ return str.startsWith("'");+}++export function extractStringFromForceString(str: string): string {+ return str.slice(1);+}diff --git a/packages/sheets-ui/src/locale/en-US.ts b/packages/sheets-ui/src/locale/en-US.tsindex d9e1d2915a..265fcf02d6 100644--- a/packages/sheets-ui/src/locale/en-US.ts+++ b/packages/sheets-ui/src/locale/en-US.ts@@ -395,6 +395,7 @@ const locale: typeof zhCN = {},info: {tooltip: 'Tooltip',+ error: 'Error',notChangeMerge: 'You cannot make partial changes to the merged cells',detailUpdate: 'New opened',detailSave: 'Local cache restored',@@ -424,6 +425,7 @@ const locale: typeof zhCN = {// eslint-disable-next-line no-template-curly-in-stringpageInfoFull: 'Total ${total}, ${totalPage} page, All data displayed',problem: 'There was a problem',+ forceStringInfo: 'Number stored as text',},clipboard: {paste: {diff --git a/packages/sheets-ui/src/locale/zh-CN.ts b/packages/sheets-ui/src/locale/zh-CN.tsindex 725f5ac022..7fc06859a6 100644--- a/packages/sheets-ui/src/locale/zh-CN.ts+++ b/packages/sheets-ui/src/locale/zh-CN.ts@@ -393,6 +393,7 @@ const locale = {},info: {tooltip: '提示',+ error: '错误',notChangeMerge: '不能对合并单元格做部分更改',detailUpdate: '新打开',detailSave: '已恢复本地缓存',@@ -422,6 +423,7 @@ const locale = {// eslint-disable-next-line no-template-curly-in-stringpageInfoFull: '共${total}条,${totalPage}页,已显示全部数据',problem: '出现了一个问题',+ forceStringInfo: '以文本形式存储的数字',},clipboard: {paste: {diff --git a/packages/sheets-ui/src/sheets-ui-plugin.ts b/packages/sheets-ui/src/sheets-ui-plugin.tsindex e240f9f8e8..957a7fea97 100644--- a/packages/sheets-ui/src/sheets-ui-plugin.ts+++ b/packages/sheets-ui/src/sheets-ui-plugin.ts@@ -68,6 +68,8 @@ import { CellAlertManagerService } from './services/cell-alert-manager.service';import { CellAlertController } from './controllers/cell-alert.controller';import { CellCustomRenderController } from './controllers/cell-custom-render.controller';import { SheetCanvasPopManagerService } from './services/canvas-pop-manager.service';+import { ForceStringRenderController } from './controllers/force-string-render.controller';+import { ForceStringAlertController } from './controllers/force-string-alert.controller';export class UniverSheetsUIPlugin extends Plugin {static override pluginName = 'SHEET_UI_PLUGIN_NAME';@@ -144,6 +146,8 @@ export class UniverSheetsUIPlugin extends Plugin {[HoverController],[CellAlertController],[CellCustomRenderController],+ [ForceStringRenderController],+ [ForceStringAlertController],] as Dependency[]).forEach((d) => injector.add(d));}