Build your own AI office with Univer Office SDK. Bring editing, calculation, collaboration, and file processing into your product for people and AI agents. Built on an extensible open-source core.
TypeScript boardcollaborationdocdocxexceloffce365officepdfpptpptxpresentationsdksheetslidesspreadsheetuniverwordwordprocessorworkspacexlsx
fix(sheet): blur table name triggers slide (#2772)
Dushusirc32866205df9
diff --git a/packages/sheets-formula/src/views/prompt/help-function/index.module.less b/packages/sheets-formula/src/views/prompt/help-function/index.module.lessindex a77c1681b8..bfe186d777 100644--- a/packages/sheets-formula/src/views/prompt/help-function/index.module.less+++ b/packages/sheets-formula/src/views/prompt/help-function/index.module.less@@ -89,6 +89,7 @@font-size: var(--font-size-xxs);font-weight: 400;white-space: pre-wrap;+ word-wrap: break-word;color: rgb(var(--text-color-secondary));}}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 7d081f9884..75d2e9a34d 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@@ -18,9 +18,11 @@ import type { ICellData, IDocumentData, Injector, Univer, Workbook } from '@univimport { CellValueType, IContextService, IResourceLoaderService, LocaleService } from '@univerjs/core';import { LexerTreeBuilder } from '@univerjs/engine-formula';import { SpreadsheetSkeleton } from '@univerjs/engine-render';-import { afterEach, beforeEach, describe, expect, it } from 'vitest';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { getCellDataByInput } from '../editing.render-controller';+import { normalizeString } from '../../utils/char-tools';import { createTestBed } from './create-test-bed';+import { IMockFunctionService, MockFunctionService } from './mock-function.service';const richTextDemo: IDocumentData = {id: 'd',@@ -67,6 +69,19 @@ const richTextDemo: IDocumentData = {},};+vi.mock('@univerjs/engine-formula', async () => {+ const actual = await vi.importActual('@univerjs/engine-formula');+ const { IMockFunctionService, MockFunctionService } = await import(+ './mock-function.service'+ );++ return {+ ...actual,+ IMockFunctionService,+ MockFunctionService,+ };+});+describe('Test EndEditController', () => {let univer: Univer;let workbook: Workbook;@@ -77,9 +92,12 @@ describe('Test EndEditController', () => {let spreadsheetSkeleton: SpreadsheetSkeleton;let resourceLoaderService: IResourceLoaderService;let getCellDataByInputCell: (cell: ICellData, inputCell: ICellData) => ICellData | null;+ let normalizeStringByLexer: (str: string) => string;beforeEach(() => {- const testBed = createTestBed();+ const testBed = createTestBed(undefined, [+ [IMockFunctionService, { useClass: MockFunctionService }],+ ]);univer = testBed.univer;workbook = testBed.sheet;@@ -106,8 +124,13 @@ describe('Test EndEditController', () => {if (!documentLayoutObject) {throw new Error('documentLayoutObject is undefined');}+ // @ts-ignore+ return getCellDataByInput(cell, documentLayoutObject, lexerTreeBuilder, (model) => model.getSnapshot(), localeService, get(IMockFunctionService));+ };- return getCellDataByInput(cell, documentLayoutObject, lexerTreeBuilder, (model) => model.getSnapshot());+ normalizeStringByLexer = (str: string) => {+ // @ts-ignore+ return normalizeString(str, lexerTreeBuilder, get(IMockFunctionService));};});@@ -148,7 +171,7 @@ describe('Test EndEditController', () => {};const cellData = getCellDataByInputCell(cell, inputCell);- expect(cellData).toEqual({ v: null, f: '=SUM(1)', p: null });+ expect(cellData).toEqual({ v: null, f: '=SUM(1)', si: null, p: null, t: undefined });});it('Clear formula cell', () => {const cell = {@@ -194,5 +217,56 @@ describe('Test EndEditController', () => {cellData = getCellDataByInputCell(cell, { v: "'=SUM" });expect(cellData).toEqual({ v: '=SUM', t: CellValueType.FORCE_STRING, f: null, si: null, p: null });});++ it('Function normalizeString', () => {+ // boolean+ expect(normalizeStringByLexer('true')).toEqual('TRUE');++ // force string+ expect(normalizeStringByLexer(''true')).toEqual("'true");++ // formatted number+ expect(normalizeStringByLexer('100%')).toEqual('100%');+ expect(normalizeStringByLexer('$100')).toEqual('$100');+ expect(normalizeStringByLexer('0.11')).toEqual('0.11');+ expect(normalizeStringByLexer('2020-1-1')).toEqual('2020-1-1');+ expect(normalizeStringByLexer('10e+1')).toEqual('10e+1');++ // formula+ expect(normalizeStringByLexer('=w')).toEqual('=w');+ expect(normalizeStringByLexer('=a1')).toEqual('=A1');++ expect(normalizeStringByLexer('="1"')).toEqual('="1"');+ expect(normalizeStringByLexer('='1'')).toEqual("='1'"); // invalid in Excel+ expect(normalizeStringByLexer('=“2”')).toEqual('=“2”');+ expect(normalizeStringByLexer('=“w”')).toEqual('=“w”');+ expect(normalizeStringByLexer('=“1')).toEqual('=“1');+ expect(normalizeStringByLexer('=‘1’')).toEqual('=‘1’');+ expect(normalizeStringByLexer('=‘1')).toEqual('=‘1');++ expect(normalizeStringByLexer('=100%+2+w')).toEqual('=100%+2+w');+ expect(normalizeStringByLexer('=true+1')).toEqual('=TRUE+1');+ expect(normalizeStringByLexer('=true+w')).toEqual('=TRUE+w');+ expect(normalizeStringByLexer('=if')).toEqual('=if');+ expect(normalizeStringByLexer('=if(')).toEqual('=IF('); // invalid in Excel+ expect(normalizeStringByLexer('=@if(true=1," A$,"&"+-×=<>%$@&*#","false")')).toEqual('=@IF(TRUE=1," A$,"&"+-×=<>%$@&*#","false")');+ expect(normalizeStringByLexer('=if(0,1,”3“)')).toEqual('=IF(0,1,”3“)');+ expect(normalizeStringByLexer('=if(A1="*2?3",1,2)')).toEqual('=IF(A1="*2?3",1,2)');+ expect(normalizeStringByLexer('={1,2}')).toEqual('={1,2}');++ // normal string+ expect(normalizeStringByLexer('100%+2-×=<>%$@&*#')).toEqual('100%+2-×=<>%$@&*#');+ expect(normalizeStringByLexer('$w')).toEqual('$w');+ expect(normalizeStringByLexer('true+1')).toEqual('true+1');++ // TODO@Dushusir: Differences from Excel, pending,+ // '=@@if@s'+ // '=@@if+@s'+ // '=SUM( "1" , 2 )'+ // '=+-if'+ // eslint-disable-next-line no-irregular-whitespace+ // '=if(1,“A”,“false ”)'+ // '=A1+B2-C3*(D4>=E5)/(F6<G7)'+ });});});diff --git a/packages/sheets-ui/src/controllers/editor/__tests__/mock-function.service.ts b/packages/sheets-ui/src/controllers/editor/__tests__/mock-function.service.tsnew file mode 100644index 0000000000..ef3b7add54--- /dev/null+++ b/packages/sheets-ui/src/controllers/editor/__tests__/mock-function.service.ts@@ -0,0 +1,30 @@+/**+ * 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 { IFunctionInfo, IFunctionNames } from '@univerjs/engine-formula';+import { FunctionType } from '@univerjs/engine-formula';+import { createIdentifier } from '@univerjs/core';++export class MockFunctionService {+ getDescriptions(): Map<IFunctionNames, IFunctionInfo> {+ const map = new Map<IFunctionNames, IFunctionInfo>();+ map.set('IF', { functionName: 'IF', functionType: FunctionType.Logical, description: 'IF function', abstract: 'IF function', functionParameter: [] });++ return map;+ }+}++export const IMockFunctionService = createIdentifier<MockFunctionService>('mock.univer.formula.function.service');diff --git a/packages/sheets-ui/src/controllers/editor/editing.render-controller.ts b/packages/sheets-ui/src/controllers/editor/editing.render-controller.tsindex 68db383e00..bbacddd538 100644--- a/packages/sheets-ui/src/controllers/editor/editing.render-controller.ts+++ b/packages/sheets-ui/src/controllers/editor/editing.render-controller.ts@@ -65,7 +65,7 @@ import { IEditorService, KeyCode, SetEditorResizeOperation } from '@univerjs/ui'import type { WorkbookSelections } from '@univerjs/sheets';import { ClearSelectionFormatCommand, SetRangeValuesCommand, SetSelectionsOperation, SetWorksheetActivateCommand, SheetsSelectionsService } from '@univerjs/sheets';import { distinctUntilChanged, filter } from 'rxjs';-import { LexerTreeBuilder, matchToken } from '@univerjs/engine-formula';+import { IFunctionService, LexerTreeBuilder, matchToken } from '@univerjs/engine-formula';import { getEditorObject } from '../../basics/editor/get-editor-object';import { SetCellEditVisibleArrowOperation, SetCellEditVisibleOperation, SetCellEditVisibleWithF2Operation } from '../../commands/operations/cell-edit.operation';@@ -76,6 +76,7 @@ import styles from '../../views/sheet-container/index.module.less';import { MoveSelectionCommand, MoveSelectionEnterAndTabCommand } from '../../commands/commands/set-selection.command';import { MOVE_SELECTION_KEYCODE_LIST } from '../shortcuts/editor.shortcut';import { extractStringFromForceString, isForceString } from '../utils/cell-tools';+import { isCJKLocale, normalizeString } from '../utils/char-tools';const HIDDEN_EDITOR_POSITION = -1000;@@ -118,6 +119,7 @@ export class EditingRenderController extends Disposable implements IRenderModule@ICellEditorManagerService private readonly _cellEditorManagerService: ICellEditorManagerService,@ITextSelectionRenderManager private readonly _textSelectionRenderManager: ITextSelectionRenderManager,@Inject(LexerTreeBuilder) private readonly _lexerTreeBuilder: LexerTreeBuilder,+ @IFunctionService private readonly _functionService: IFunctionService,@Inject(TextSelectionManagerService) private readonly _textSelectionManagerService: TextSelectionManagerService,@ICommandService private readonly _commandService: ICommandService,@Inject(LocaleService) protected readonly _localService: LocaleService,@@ -837,7 +839,9 @@ export class EditingRenderController extends Disposable implements IRenderModuleworksheet.getCellRaw(row, column) || {},documentLayoutObject,this._lexerTreeBuilder,- (model) => this._resourceLoaderService.saveDoc(model)+ (model) => this._resourceLoaderService.saveDoc(model),+ this._localService,+ this._functionService);if (!cellData) {@@ -988,7 +992,9 @@ export function getCellDataByInput(cellData: ICellData,documentLayoutObject: IDocumentLayoutObject,lexerTreeBuilder: LexerTreeBuilder,- getSnapshot: (data: DocumentDataModel) => IDocumentData+ getSnapshot: (data: DocumentDataModel) => IDocumentData,+ localeService: LocaleService,+ functionService: IFunctionService) {cellData = Tools.deepClone(cellData);@@ -1010,16 +1016,23 @@ export function getCellDataByInput(const lastString = data.substring(data.length - 2, data.length);let newDataStream = lastString === DEFAULT_EMPTY_DOCUMENT_VALUE ? data.substring(0, data.length - 2) : data;+ const currentLocale = localeService.getCurrentLocale();+ if (isCJKLocale(currentLocale)) {+ newDataStream = normalizeString(newDataStream, lexerTreeBuilder, functionService);+ }+if (isFormulaString(newDataStream)) {if (cellData.f === newDataStream) {return null;}+const bracketCount = lexerTreeBuilder.checkIfAddBracket(newDataStream);for (let i = 0; i < bracketCount; i++) {newDataStream += matchToken.CLOSE_BRACKET;}cellData.f = newDataStream;+ cellData.si = null; // Disassociate from the original formulacellData.v = null;cellData.p = null;} else if (isForceString(newDataStream)) {@@ -1066,4 +1079,3 @@ function isRichText(body: IDocumentBody) {customBlocks.length > 0);}-diff --git a/packages/sheets-ui/src/controllers/utils/char-tools.ts b/packages/sheets-ui/src/controllers/utils/char-tools.tsnew file mode 100644index 0000000000..eff5bcc3ed--- /dev/null+++ b/packages/sheets-ui/src/controllers/utils/char-tools.ts@@ -0,0 +1,153 @@+/**+ * 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 { LocaleType } from '@univerjs/core';+import type { IFunctionService, ISequenceNode, LexerTreeBuilder } from '@univerjs/engine-formula';+import { matchToken, sequenceNodeType } from '@univerjs/engine-formula';+import { numfmt } from '@univerjs/engine-numfmt';++const fullWidthToHalfWidthMap: { [key: string]: string } = {+ '0': '0', '1': '1', '2': '2', '3': '3', '4': '4',+ '5': '5', '6': '6', '7': '7', '8': '8', '9': '9',+ A: 'A', B: 'B', C: 'C', D: 'D', E: 'E',+ F: 'F', G: 'G', H: 'H', I: 'I', J: 'J',+ K: 'K', L: 'L', M: 'M', N: 'N', O: 'O',+ P: 'P', Q: 'Q', R: 'R', S: 'S', T: 'T',+ U: 'U', V: 'V', W: 'W', X: 'X', Y: 'Y',+ Z: 'Z', a: 'a', b: 'b', c: 'c', d: 'd',+ e: 'e', f: 'f', g: 'g', h: 'h', i: 'i',+ j: 'j', k: 'k', l: 'l', m: 'm', n: 'n',+ o: 'o', p: 'p', q: 'q', r: 'r', s: 's',+ t: 't', u: 'u', v: 'v', w: 'w', x: 'x',+ y: 'y', z: 'z', '%': '%', '-': '-', '.': '.',+ ':': ':', '/': '/', '+': '+', '@': '@', '&': '&',+ '*': '*', '#': '#', '=': '=', '>': '>', '<': '<',+ '$': '$', '"': '"', ''': "'", '(': '(', ')': ')', ' ': ' ',+ ',': ',', '!': '!', '?': '?', ';': ';', '[': '[', ']': ']',+ '{': '{', '}': '}',+};++// Boolean conversion+const booleanMap: { [key: string]: string } = {+ true: 'TRUE',+ false: 'FALSE',+};++// TODO@Dushusir: add more locales+export function isCJKLocale(locale: LocaleType) {+ return [LocaleType.ZH_CN, LocaleType.ZH_TW].includes(locale);+}++/**+ * Convert all full-width characters to half-width characters and try to parse them. If the parsing is successful, apply them. If the parsing is not successful, return them to full-width characters.+ *+ * Convert full-width characters to half-width characters+ * 1. Formula+ * 2. Boolean+ * 3. Formatted number+ *+ * Not converted+ * 1. Force string+ * 2. Chinese single and double quotation marks+ * 3. Characters between single and double quotes in formulas+ * 4. Other text that cannot be recognized as formulas, Boolean values, or numbers+ *+ * @param str+ * @param lexerTreeBuilder+ * @returns+ */+export function normalizeString(str: string, lexerTreeBuilder: LexerTreeBuilder, functionService: IFunctionService) {+ // Check if it is a mandatory string with single quotes+ if (str.startsWith(''') || str.startsWith("'")) {+ return `'${str.slice(1)}`;+ }++ // covert all full width characters to normal characters+ const normalStr = str.split('').map(toHalfWidth).join('');++ // Check if it is a formula+ if (normalStr.startsWith('=')) {+ return normalizeFormulaString(str, normalStr, lexerTreeBuilder, functionService);+ }++ // Check if it is a boolean value+ const lowerCaseStr = normalStr.toLowerCase();+ if (booleanMap[lowerCaseStr]) {+ return booleanMap[lowerCaseStr];+ }++ // Formatting Numbers+ const parsedValue = numfmt.parseValue(normalStr);++ return parsedValue == null ? str : normalStr;+}++function normalizeFormulaString(str: string, normalStr: string, lexerTreeBuilder: LexerTreeBuilder, functionService: IFunctionService) {+ const nodes = lexerTreeBuilder.sequenceNodesBuilder(normalStr);++ if (!nodes) return str;++ nodes.forEach((node, index) => {+ if (typeof node === 'object') {+ const token = node.token;+ const lowerCaseToken = token.toLowerCase();++ // boolean or function name+ if (booleanMap[lowerCaseToken] || (node.nodeType === sequenceNodeType.FUNCTION && hasFunctionName(token, functionService, nodes, index)) || node.nodeType === sequenceNodeType.REFERENCE) {+ const startIndex = node.startIndex + 1;+ const endIndex = node.endIndex + 2;+ normalStr = replaceString(token.toLocaleUpperCase(), normalStr, startIndex, endIndex);+ } else if ((token.startsWith('"') && token.endsWith('"')) || (token.startsWith("'") && token.endsWith("'"))) {+ const startIndex = node.startIndex + 2;+ const endIndex = node.endIndex + 1;+ normalStr = replaceString(str.slice(startIndex, endIndex), normalStr, startIndex, endIndex);+ } else if (node.nodeType !== sequenceNodeType.ARRAY) {+ const parsedValue = numfmt.parseValue(token);++ if (parsedValue == null) {+ const startIndex = node.startIndex + 1;+ const endIndex = node.endIndex + 2;+ normalStr = replaceString(str.slice(startIndex, endIndex), normalStr, startIndex, endIndex);+ }+ }+ }+ });+ return normalStr;+}++function hasFunctionName(name: string, functionService: IFunctionService, nodes: (string | ISequenceNode)[], index: number) {+ const functionList = functionService.getDescriptions();++ if (nodes[index + 1] !== matchToken.OPEN_BRACKET) {+ return false;+ }++ return functionList.get(removeLeadingAtSymbols(name).toLocaleUpperCase()) !== undefined;+}++function removeLeadingAtSymbols(str: string): string {+ const regex = /^@+/;+ return str.replace(regex, '');+}++// Full-width character conversion function+function toHalfWidth(char: string): string {+ return fullWidthToHalfWidthMap[char] || char;+}++function replaceString(replacedString: string, normalStr: string, startIndex: number, endIndex: number): string {+ return normalStr.substring(0, startIndex) + replacedString + normalStr.substring(endIndex);+}diff --git a/packages/sheets-ui/src/services/auto-fill/__tests__/tool.spec.ts b/packages/sheets-ui/src/services/auto-fill/__tests__/tool.spec.tsnew file mode 100644index 0000000000..5be50469f8--- /dev/null+++ b/packages/sheets-ui/src/services/auto-fill/__tests__/tool.spec.ts@@ -0,0 +1,28 @@+/**+ * 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 { CellValueType } from '@univerjs/core';+import { needsUpdateCellValue } from '../tools';++describe('Test tool', () => {+ it('Function needsUpdateCellValue', () => {+ expect(needsUpdateCellValue({ f: '=A1' })).toBeFalsy();+ expect(needsUpdateCellValue({ si: 'id1' })).toBeFalsy();+ expect(needsUpdateCellValue({ t: CellValueType.BOOLEAN })).toBeFalsy();+ expect(needsUpdateCellValue({ v: 1, t: CellValueType.NUMBER })).toBeTruthy();+ });+});diff --git a/packages/sheets-ui/src/services/auto-fill/tools.ts b/packages/sheets-ui/src/services/auto-fill/tools.tsindex 434a314569..3731a1c8a9 100644--- a/packages/sheets-ui/src/services/auto-fill/tools.ts+++ b/packages/sheets-ui/src/services/auto-fill/tools.ts@@ -15,7 +15,7 @@*/import type { ICellData, IRange, Nullable } from '@univerjs/core';-import { CellValueType, Direction, Tools } from '@univerjs/core';+import { CellValueType, Direction, isFormulaId, isFormulaString, Tools } from '@univerjs/core';export const chnNumChar = { 零: 0, 一: 1, 二: 2, 三: 3, 四: 4, 五: 5, 六: 6, 七: 7, 八: 8, 九: 9 };export const chnNumChar2 = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九'];@@ -394,7 +394,7 @@ export function fillSeries(data: Array<Nullable<ICellData>>, len: number, directconst num = Number(data[data.length - 1]?.v) * (Number(data[1]?.v) / Number(data[0]?.v)) ** i;if (d) {- if (d.t !== CellValueType.BOOLEAN) {+ if (needsUpdateCellValue(d)) {d.v = num;}applyData.push(d);@@ -410,7 +410,7 @@ export function fillSeries(data: Array<Nullable<ICellData>>, len: number, directconst y = forecast(data.length + i, dataNumArr, xArr, forward);if (d) {- if (d.t !== CellValueType.BOOLEAN) {+ if (needsUpdateCellValue(d)) {d.v = y;}applyData.push(d);@@ -781,3 +781,20 @@ export function getAutoFillRepeatRange(sourceRange: IRange, targetRange: IRange)return repeats;}++/**+ * Formulas or Boolean values do not need to update cell.v+ * @param cell+ * @returns+ */+export function needsUpdateCellValue(cell: ICellData) {+ if (isFormulaString(cell.f) || isFormulaId(cell.si)) {+ return false;+ }++ if (cell.t === CellValueType.BOOLEAN) {+ return false;+ }++ return true;+}diff --git a/packages/sheets-ui/src/views/sheet-bar/sheet-bar-tabs/utils/slide-tab-bar.ts b/packages/sheets-ui/src/views/sheet-bar/sheet-bar-tabs/utils/slide-tab-bar.tsindex 9c3598d10b..f72f7cdd9d 100644--- a/packages/sheets-ui/src/views/sheet-bar/sheet-bar-tabs/utils/slide-tab-bar.ts+++ b/packages/sheets-ui/src/views/sheet-bar/sheet-bar-tabs/utils/slide-tab-bar.ts@@ -561,6 +561,9 @@ export class SlideTabBar {if (!this._activeTabItem) return;+ // When blurring after editing the table name, _activeTabItemIndex and _compareIndex may not be equal, causing slideEnd to be triggered+ const isFromScroll = this._autoScrollTime !== null;+this._closeAutoScroll();this._activeTabItem.disableFixed();// this._sortedItems();@@ -575,7 +578,7 @@ export class SlideTabBar {this._activeTabItem?.removeEventListener('pointermove', this._moveAction);this._activeTabItem?.removeEventListener('pointerup', this._upAction);- if (this._config.onSlideEnd && this._activeTabItemIndex !== this._compareIndex) {+ if (this._config.onSlideEnd && this._activeTabItemIndex !== this._compareIndex && isFromScroll) {this.removeListener();this._config.onSlideEnd(upEvent, this._compareIndex || 0);}