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(sheets-find-replace): preserve whitespace in searches (#7820)
白熱b4193b1a9825
diff --git a/packages/sheets-find-replace/src/controllers/__tests__/hit-cell.spec.ts b/packages/sheets-find-replace/src/controllers/__tests__/hit-cell.spec.tsdeleted file mode 100644index 612e9cac6b..0000000000--- a/packages/sheets-find-replace/src/controllers/__tests__/hit-cell.spec.ts+++ /dev/null@@ -1,118 +0,0 @@-/**- * Copyright 2023-present DreamNum Co., Ltd.- *- * Licensed under the Apache License, Version 2.0 (the "License");- * you may not use this file except in compliance with the License.- * You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */--import type { IFindQuery } from '@univerjs/find-replace';-import { FindBy, FindDirection, FindScope } from '@univerjs/find-replace';-import { describe, expect, it } from 'vitest';-import { hitCell } from '../sheet-find-replace.controller';--describe('hitCell', () => {- const baseQuery: IFindQuery = {- replaceRevealed: false,- findString: 'abc',- caseSensitive: false,- matchesTheWholeCell: false,- matchesTheWholeWord: false,- findDirection: FindDirection.ROW,- findScope: FindScope.SUBUNIT,- findBy: FindBy.VALUE,- };-- it('should mark formula matches replaceable only in formula mode', () => {- const worksheet = {- getCellRaw: () => ({ f: '=ABC()' }),- };-- const formulaQuery: IFindQuery = { ...baseQuery, findBy: FindBy.FORMULA, findString: '=abc' };- const res1 = hitCell(worksheet as any, 0, 0, formulaQuery, { v: 'xxx' } as any);- expect(res1.hit).toBe(true);- expect(res1.replaceable).toBe(true);- expect(res1.isFormula).toBe(true);-- const valueQuery: IFindQuery = { ...baseQuery, findBy: FindBy.VALUE, findString: 'xxx' };- const res2 = hitCell(worksheet as any, 0, 0, valueQuery, { v: 'xxx' } as any);- expect(res2.hit).toBe(true);- expect(res2.replaceable).toBe(false);- expect(res2.isFormula).toBe(true);- });-- it('should mark non-formula matches replaceable only when rawData exists', () => {- const worksheetWithRaw = {- getCellRaw: () => ({ v: 'abc' }),- };-- const res1 = hitCell(worksheetWithRaw as any, 0, 0, baseQuery, { v: 'abc' } as any);- expect(res1.hit).toBe(true);- expect(res1.replaceable).toBe(true);-- const worksheetNoRaw = {- getCellRaw: () => null,- };-- const res2 = hitCell(worksheetNoRaw as any, 0, 0, baseQuery, { v: 'abc' } as any);- expect(res2.hit).toBe(true);- expect(res2.replaceable).toBe(false);- });-- it('should support whole-cell matching with edge spaces', () => {- const worksheet = {- getCellRaw: () => ({ v: ' abc ' }),- };-- const res = hitCell(worksheet as any, 0, 0, {- ...baseQuery,- matchesTheWholeCell: true,- findString: 'abc',- }, { v: ' abc ' } as any);-- expect(res.hit).toBe(true);- expect(res.replaceable).toBe(true);- });-- it('should extract number and boolean cell values for matching', () => {- const worksheet = {- getCellRaw: (_row: number, col: number) => (col === 0 ? { v: 123 } : { v: true }),- };-- expect(hitCell(worksheet as any, 0, 0, { ...baseQuery, findString: '23' }, { v: 123 } as any).hit).toBe(true);- expect(hitCell(worksheet as any, 0, 1, { ...baseQuery, findString: '1' }, { v: true } as any).hit).toBe(true);- });-- it('should report misses for empty values and unmatched formula display values', () => {- const formulaWorksheet = {- getCellRaw: () => ({ f: '=SUM(1)' }),- };- const formulaRawMiss = hitCell(formulaWorksheet as any, 0, 0, {- ...baseQuery,- findBy: FindBy.FORMULA,- findString: '=missing',- }, { v: 'alpha' } as any);- expect(formulaRawMiss.hit).toBe(false);- expect(formulaRawMiss.replaceable).toBe(false);-- const formulaMiss = hitCell(formulaWorksheet as any, 0, 0, { ...baseQuery, findString: 'missing' }, { v: 'alpha' } as any);- expect(formulaMiss.hit).toBe(false);- expect(formulaMiss.replaceable).toBe(false);- expect(formulaMiss.isFormula).toBe(true);-- const emptyWorksheet = {- getCellRaw: () => ({ v: '' }),- };- const emptyMiss = hitCell(emptyWorksheet as any, 0, 0, baseQuery, { v: '' } as any);- expect(emptyMiss.hit).toBe(false);- expect(emptyMiss.replaceable).toBe(false);- });-});diff --git a/packages/sheets-find-replace/src/controllers/__tests__/sheet-find-model.navigation.spec.ts b/packages/sheets-find-replace/src/controllers/__tests__/sheet-find-model.navigation.spec.tsdeleted file mode 100644index 427d283c3d..0000000000--- a/packages/sheets-find-replace/src/controllers/__tests__/sheet-find-model.navigation.spec.ts+++ /dev/null@@ -1,116 +0,0 @@-/**- * Copyright 2023-present DreamNum Co., Ltd.- *- * Licensed under the Apache License, Version 2.0 (the "License");- * you may not use this file except in compliance with the License.- * You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */--import type { IFindQuery } from '@univerjs/find-replace';-import { CloseFindDialogOperation, FindBy, FindDirection, FindScope } from '@univerjs/find-replace';-import { Subject } from 'rxjs';-import { describe, expect, it, vi } from 'vitest';-import { SheetFindModel, SheetsFindReplaceController } from '../sheet-find-replace.controller';--describe('SheetFindModel navigation', () => {- it('should move to next match based on current selection (no focus)', () => {- const activeSheet = { getSheetId: () => 's1', getRowCount: () => 10, getColumnCount: () => 10, iterateByRow: () => [], iterateByColumn: () => [], isSheetHidden: () => false };- const workbook = {- getUnitId: () => 'u1',- getActiveSheet: () => activeSheet,- activeSheet$: new Subject<any>(),- };-- const skeletonService = {- currentSkeleton$: new Subject<any>(),- getCurrent: () => null,- };-- const renderManagerService = { getRenderUnitById: vi.fn(() => null) };- const commandService = { executeCommand: vi.fn(), onCommandExecuted: vi.fn(() => ({ dispose: vi.fn() })) };- const contextService = { setContextValue: vi.fn() };- const themeService = { getColorFromTheme: vi.fn(() => '#fff') };-- const selections = [{ range: { startRow: 0, startColumn: 0, endRow: 0, endColumn: 0 } }];- const workbookSelections = {- getCurrentSelections: () => selections,- getCurrentLastSelection: () => selections[0],- };-- const selectionService = {- getWorkbookSelections: vi.fn(() => workbookSelections),- };-- const model = new SheetFindModel(- workbook as any,- skeletonService as any,- {} as any,- renderManagerService as any,- commandService as any,- contextService as any,- themeService as any,- selectionService as any- );-- (model as any)._matches = [- { unitId: 'u1', provider: 'sheets-find-replace-provider', isFormula: false, replaceable: true, range: { subUnitId: 's1', range: { startRow: 1, startColumn: 1, endRow: 1, endColumn: 1 } } },- { unitId: 'u1', provider: 'sheets-find-replace-provider', isFormula: false, replaceable: true, range: { subUnitId: 's1', range: { startRow: 2, startColumn: 1, endRow: 2, endColumn: 1 } } },- ];-- (model as any)._query = {- replaceRevealed: false,- findString: 'a',- caseSensitive: false,- matchesTheWholeCell: false,- matchesTheWholeWord: false,- findDirection: FindDirection.ROW,- findScope: FindScope.SUBUNIT,- findBy: FindBy.VALUE,- } satisfies IFindQuery;-- const match = model.moveToNextMatch({ noFocus: true });- expect(match?.range.range.startRow).toBe(1);- expect(commandService.executeCommand).not.toHaveBeenCalled();-- model.dispose();- });-});--describe('SheetsFindReplaceController', () => {- it('should register provider and close on editor activated', () => {- const injector = { createInstance: vi.fn(() => ({ dispose: vi.fn() })) };- const subscribeContextValue$ = vi.fn(() => ({ pipe: () => ({ subscribe: (fn: any) => {- fn(true);- return { unsubscribe: vi.fn() };- } }) }));- const contextService = { subscribeContextValue$ };- const findReplaceService = {- registerFindReplaceProvider: vi.fn(() => ({ dispose: vi.fn() })),- terminate: vi.fn(),- };- const commandService = {- executeCommand: vi.fn(() => Promise.resolve(true)),- registerCommand: vi.fn(() => ({ dispose: vi.fn() })),- };-- new SheetsFindReplaceController(- injector as any,- contextService as any,- findReplaceService as any,- commandService as any- );-- expect(commandService.executeCommand).toHaveBeenCalledWith(CloseFindDialogOperation.id);- // Do not call `dispose` here: the controller stores rx subscriptions in a DisposableCollection,- // and our simplified stubs don't fully implement the IDisposable contract.- expect(findReplaceService.registerFindReplaceProvider).toHaveBeenCalled();- });-});diff --git a/packages/sheets-find-replace/src/controllers/__tests__/sheet-find-replace.controller.spec.ts b/packages/sheets-find-replace/src/controllers/__tests__/sheet-find-replace.controller.spec.tsindex ecffe2ad7c..1f4bd5b0cf 100644--- a/packages/sheets-find-replace/src/controllers/__tests__/sheet-find-replace.controller.spec.ts+++ b/packages/sheets-find-replace/src/controllers/__tests__/sheet-find-replace.controller.spec.ts@@ -14,17 +14,19 @@* limitations under the License.*/-import type { ICellData, IRange } from '@univerjs/core';-import type { IFindQuery } from '@univerjs/find-replace';-import { UniverInstanceType } from '@univerjs/core';-import { RENDER_RAW_FORMULA_KEY } from '@univerjs/engine-render';-import { CloseFindDialogOperation, FindBy, FindDirection, FindScope } from '@univerjs/find-replace';-import { SelectRangeCommand, SetRangeValuesCommand, SetWorksheetActivateCommand } from '@univerjs/sheets';+import type { ICellData, IRange, IWorkbookData, Workbook } from '@univerjs/core';+import type { IFindQuery, IFindReplaceProvider } from '@univerjs/find-replace';+import type { ISheetCellMatch } from '../sheet-find-replace.controller';+import { ICommandService, IContextService, Injector, IUniverInstanceService, ThemeService, Univer, UniverInstanceType } from '@univerjs/core';+import { IRenderManagerService, RENDER_RAW_FORMULA_KEY } from '@univerjs/engine-render';+import { CloseFindDialogOperation, FindBy, FindDirection, FindScope, IFindReplaceService } from '@univerjs/find-replace';+import { SelectRangeCommand, SetRangeValuesCommand, SetWorksheetActivateCommand, SheetsSelectionsService } from '@univerjs/sheets';import { ScrollToCellCommand } from '@univerjs/sheets-ui';import { Subject } from 'rxjs';-import { describe, expect, it, vi } from 'vitest';++import { describe, expect, it, onTestFinished, vi } from 'vitest';import { SheetReplaceCommand } from '../../commands/commands/sheet-replace.command';-import { SheetFindModel, SheetsFindReplaceController } from '../sheet-find-replace.controller';+import { hitCell, SheetFindModel, SheetsFindReplaceController } from '../sheet-find-replace.controller';vi.mock('@univerjs/sheets-ui', async (importOriginal) => {const actual = await importOriginal<typeof import('@univerjs/sheets-ui')>();@@ -112,16 +114,9 @@ function createModel(currentSkeleton$: new Subject<any>(),getCurrentSkeleton: vi.fn(() => null),};- const commandCallbacks: Array<(command: any, options?: any) => void> = [];const commandService = {executeCommand: vi.fn(() => Promise.resolve(true)),- onCommandExecuted: vi.fn((callback: (command: any, options?: any) => void) => {- commandCallbacks.push(callback);- return { dispose: vi.fn() };- }),- emitCommand(command: any, options?: any) {- commandCallbacks.forEach((callback) => callback(command, options));- },+ onCommandExecuted: vi.fn(() => ({ dispose: vi.fn() })),};const contextService = { setContextValue: vi.fn() };const selectionService = {@@ -131,20 +126,63 @@ function createModel(})),};- const model = new SheetFindModel(- workbook,- skeletonService as any,- {} as any,- (overrides.renderManagerService ?? { getRenderUnitById: vi.fn(() => null) }) as any,- commandService as any,- contextService as any,- (overrides.themeService ?? { getColorFromTheme: vi.fn(() => '#ff0') }) as any,- selectionService as any- );+ const injector = new Injector([+ [IUniverInstanceService, { useValue: {} }],+ [IRenderManagerService, { useValue: overrides.renderManagerService ?? { getRenderUnitById: vi.fn(() => null) } }],+ [ICommandService, { useValue: commandService }],+ [IContextService, { useValue: contextService }],+ [ThemeService, { useValue: overrides.themeService ?? { getColorFromTheme: vi.fn(() => '#ff0') } }],+ [SheetsSelectionsService, { useValue: selectionService }],+ ]);+ const model = injector.createInstance(SheetFindModel, workbook, skeletonService as any);+ onTestFinished(() => {+ model.dispose();+ injector.dispose();+ });return { model, commandService, contextService, skeletonService };}+function createProvider(workbook: Workbook | null) {+ const skeletonService = {+ currentSkeleton$: new Subject<unknown>(),+ getCurrentSkeleton: vi.fn(() => null),+ };+ const commandService = {+ registerCommand: vi.fn(() => ({ dispose: vi.fn() })),+ executeCommand: vi.fn(() => Promise.resolve(true)),+ onCommandExecuted: vi.fn(() => ({ dispose: vi.fn() })),+ };+ const contextValue$ = new Subject<boolean>();+ let provider!: IFindReplaceProvider;+ const terminate = vi.fn();+ const injector = new Injector([+ [IUniverInstanceService, { useValue: { getCurrentUnitOfType: () => workbook } }],+ [IRenderManagerService, { useValue: { getRenderUnitById: () => ({ with: () => skeletonService }) } }],+ [ICommandService, { useValue: commandService }],+ [IContextService, { useValue: { subscribeContextValue$: () => contextValue$, setContextValue: vi.fn() } }],+ [IFindReplaceService, { useValue: {+ registerFindReplaceProvider: (registeredProvider: IFindReplaceProvider) => {+ provider = registeredProvider;+ return { dispose: vi.fn() };+ },+ terminate,+ } }],+ [ThemeService, { useValue: { getColorFromTheme: () => '#ff0' } }],+ [SheetsSelectionsService, { useValue: { getWorkbookSelections: () => ({+ getCurrentSelections: () => [],+ getCurrentLastSelection: () => null,+ }) } }],+ [SheetsFindReplaceController],+ ]);+ const controller = injector.get(SheetsFindReplaceController);+ onTestFinished(() => {+ provider.terminate();+ injector.dispose();+ });+ return { provider, controller, commandService, contextValue$, terminate };+}+describe('SheetsFindReplaceController integration', () => {it('registers a real sheets provider, preprocesses queries and closes on editor activation', async () => {const activeSheet = createWorksheet('sheet-1', {@@ -153,107 +191,100 @@ describe('SheetsFindReplaceController integration', () => {'1,0': { f: '=SUM(1)', v: 'alpha result' },'2,0': { v: 'alpha filtered' },}, { filteredRows: [2] });- const workbook = createWorkbook(activeSheet);- const skeletonService = {- currentSkeleton$: new Subject<any>(),- getCurrentSkeleton: vi.fn(() => null),- };- const renderManagerService = {- getRenderUnitById: vi.fn(() => ({ with: vi.fn(() => skeletonService) })),- };- const commandService = {- registerCommand: vi.fn(() => ({ dispose: vi.fn() })),- executeCommand: vi.fn(() => Promise.resolve(true)),- onCommandExecuted: vi.fn(() => ({ dispose: vi.fn() })),- };- const contextValue$ = new Subject<boolean>();- const contextService = {- subscribeContextValue$: vi.fn(() => contextValue$),- setContextValue: vi.fn(),- };- const selectionService = {- getWorkbookSelections: vi.fn(() => ({- getCurrentSelections: vi.fn(() => [{ range: { startRow: 0, startColumn: 0, endRow: 0, endColumn: 0 } }]),- getCurrentLastSelection: vi.fn(() => ({ range: { startRow: 0, startColumn: 0, endRow: 0, endColumn: 0 } })),- })),- };- const univerInstanceService = {- getCurrentUnitOfType: vi.fn(() => workbook),- };- const injector = {- createInstance: vi.fn((Ctor: any, ...args: any[]) => {- if (Ctor.name === 'SheetsFindReplaceProvider') {- return new Ctor(univerInstanceService, renderManagerService, injector);- }-- return new Ctor(- args[0],- args[1],- univerInstanceService,- renderManagerService,- commandService,- contextService,- { getColorFromTheme: vi.fn(() => '#ff0') },- selectionService- );- }),- };- let provider: any;- const terminate = vi.fn();- const findReplaceService = {- registerFindReplaceProvider: vi.fn((registeredProvider) => {- provider = registeredProvider;- return { dispose: vi.fn() };- }),- terminate,- };-- const controller = new SheetsFindReplaceController(- injector as any,- contextService as any,- findReplaceService as any,- commandService as any- );+ const { provider, controller, commandService, contextValue$, terminate } = createProvider(createWorkbook(activeSheet));contextValue$.next(true);- const [model] = await provider.find({ ...baseQuery, findString: ' ALPHA ' });+ const [model] = await provider.find({ ...baseQuery, findString: 'ALPHA' });expect(commandService.registerCommand).toHaveBeenCalledWith(SheetReplaceCommand);expect(commandService.executeCommand).toHaveBeenCalledWith(CloseFindDialogOperation.id);- expect(model).toBeInstanceOf(SheetFindModel);- expect(model.matchesCount).toBe(2);- expect(model.getMatches().map((match: any) => match.range.range.startRow)).toEqual([0, 1]);- expect(model.getMatches().map((match: any) => match.replaceable)).toEqual([true, false]);+ expect(model.getMatches().map((match) => (match as ISheetCellMatch).range.range.startRow)).toEqual([0, 1]);+ expect(model.getMatches().map((match) => match.replaceable)).toEqual([true, false]);controller.dispose();expect(terminate).toHaveBeenCalledOnce();});it('returns no models when the provider has no active workbook', async () => {- const injector = {- createInstance: vi.fn((Ctor: any) => new Ctor(- { getCurrentUnitOfType: vi.fn(() => null) },- { getRenderUnitById: vi.fn() },- injector- )),- };- let provider: any;- const controller = new SheetsFindReplaceController(- injector as any,- { subscribeContextValue$: vi.fn(() => new Subject<boolean>()) } as any,- {- registerFindReplaceProvider: vi.fn((registeredProvider) => {- provider = registeredProvider;- return { dispose: vi.fn() };- }),- terminate: vi.fn(),- } as any,- { registerCommand: vi.fn(() => ({ dispose: vi.fn() })) } as any- );-+ const { provider } = createProvider(null);await expect(provider.find(baseQuery)).resolves.toEqual([]);- provider.terminate();- controller.dispose();+ });++ it.each([+ { name: 'single spaces', findString: ' ', columns: [1, 2, 3, 4, 5, 6, 8] },+ { name: 'consecutive spaces', findString: ' ', columns: [4] },+ { name: 'tabs', findString: '\t', columns: [9] },+ { name: 'nonbreaking spaces', findString: '\u00A0', columns: [10] },+ { name: 'leading spaces', findString: ' Alpha', columns: [2] },+ { name: 'trailing spaces ignoring case', findString: 'alpha ', columns: [1, 3, 6, 8] },+ { name: 'trailing spaces matching case', findString: 'alpha ', caseSensitive: true, columns: [] },+ { name: 'spaces in raw formulas', findString: ' ', findBy: FindBy.FORMULA, columns: [1, 2, 3, 4, 5, 6, 7] },+ { name: 'a cell containing one space', findString: ' ', matchesTheWholeCell: true, columns: [5] },+ { name: 'a cell containing two spaces', findString: ' ', matchesTheWholeCell: true, columns: [4] },+ { name: 'whole cells with leading spaces', findString: ' Alpha', matchesTheWholeCell: true, columns: [2] },+ { name: 'whole cells with trailing spaces', findString: 'Alpha ', matchesTheWholeCell: true, columns: [3] },+ { name: 'whole cells without spaces', findString: 'Alpha', matchesTheWholeCell: true, columns: [0] },+ ])('preserves whitespace when finding $name', async ({ columns, name: _name, ...query }) => {+ const univer = new Univer();+ onTestFinished(() => univer.dispose());+ const workbook = univer.createUnit<IWorkbookData, Workbook>(UniverInstanceType.UNIVER_SHEET, {+ id: 'unit-1',+ sheetOrder: ['sheet-1'],+ sheets: {+ 'sheet-1': {+ id: 'sheet-1',+ rowCount: 1,+ columnCount: 11,+ cellData: {+ 0: {+ 0: { v: 'Alpha' },+ 1: { v: 'Alpha Beta' },+ 2: { v: ' Alpha' },+ 3: { v: 'Alpha ' },+ 4: { v: ' ' },+ 5: { v: ' ' },+ 6: { p: { id: 'rich-text', documentStyle: {}, body: { dataStream: 'Alpha Beta\r\n' } } },+ 7: { f: '="Alpha Beta"', v: 'AlphaBeta' },+ 8: { f: '="AlphaBeta"', v: 'Alpha Beta' },+ 9: { v: '\t' },+ 10: { v: 'Alpha\u00A0Beta' },+ },+ },+ },+ },+ });+ const { provider } = createProvider(workbook);+ const [model] = await provider.find({ ...baseQuery, ...query });++ expect(model.getMatches().map((match) => (match as ISheetCellMatch).range.range.startColumn)).toEqual(columns);+ });++ it.each([FindBy.VALUE, FindBy.FORMULA])('replaces literal spaces without changing unrelated cells in mode %s', async (findBy) => {+ const activeSheet = createWorksheet('sheet-1', {+ '0,0': { v: 'Alpha' },+ '0,1': { v: 'Alpha Beta' },+ '1,0': { p: { body: { dataStream: 'Alpha Beta\r\n' } } as any },+ '1,1': { f: '="Alpha Beta"', v: 'AlphaBeta' },+ });+ const { provider, commandService } = createProvider(createWorkbook(activeSheet));+ const [model] = await provider.find({ ...baseQuery, findString: ' ', findBy });++ await model.replaceAll('-');++ expect(commandService.executeCommand).toHaveBeenCalledWith(SheetReplaceCommand.id, {+ unitId: 'unit-1',+ replacements: [{+ count: findBy === FindBy.FORMULA ? 3 : 2,+ subUnitId: 'sheet-1',+ value: {+ 0: { 1: { v: 'Alpha-Beta' } },+ 1: {+ 0: { p: { body: expect.objectContaining({ dataStream: 'Alpha-Beta\r\n' }) } },+ ...(findBy === FindBy.FORMULA ? { 1: { f: '="Alpha-Beta"', v: null } } : {}),+ },+ },+ }],+ });});});@@ -548,3 +579,125 @@ describe('SheetFindModel search and replace', () => {model.dispose();});});++describe('SheetFindModel navigation', () => {+ it('moves to the next match from the selection without focusing it', () => {+ const activeSheet = createWorksheet('sheet-1', { '1,1': { v: 'alpha' }, '2,1': { v: 'alpha' } });+ const { model, commandService } = createModel(createWorkbook(activeSheet));+ model.start(baseQuery);++ expect(model.moveToNextMatch({ noFocus: true })?.range.range.startRow).toBe(1);+ expect(commandService.executeCommand).not.toHaveBeenCalled();+ });+});++describe('hitCell', () => {+ const baseQuery: IFindQuery = {+ replaceRevealed: false,+ findString: 'abc',+ caseSensitive: false,+ matchesTheWholeCell: false,+ matchesTheWholeWord: false,+ findDirection: FindDirection.ROW,+ findScope: FindScope.SUBUNIT,+ findBy: FindBy.VALUE,+ };++ it('should mark formula matches replaceable only in formula mode', () => {+ const worksheet = {+ getCellRaw: () => ({ f: '=ABC()' }),+ };++ const formulaQuery: IFindQuery = { ...baseQuery, findBy: FindBy.FORMULA, findString: '=abc' };+ const res1 = hitCell(worksheet as any, 0, 0, formulaQuery, { v: 'xxx' } as any);+ expect(res1.hit).toBe(true);+ expect(res1.replaceable).toBe(true);+ expect(res1.isFormula).toBe(true);++ const valueQuery: IFindQuery = { ...baseQuery, findBy: FindBy.VALUE, findString: 'xxx' };+ const res2 = hitCell(worksheet as any, 0, 0, valueQuery, { v: 'xxx' } as any);+ expect(res2.hit).toBe(true);+ expect(res2.replaceable).toBe(false);+ expect(res2.isFormula).toBe(true);+ });++ it('should mark non-formula matches replaceable only when rawData exists', () => {+ const worksheetWithRaw = {+ getCellRaw: () => ({ v: 'abc' }),+ };++ const res1 = hitCell(worksheetWithRaw as any, 0, 0, baseQuery, { v: 'abc' } as any);+ expect(res1.hit).toBe(true);+ expect(res1.replaceable).toBe(true);++ const worksheetNoRaw = {+ getCellRaw: () => null,+ };++ const res2 = hitCell(worksheetNoRaw as any, 0, 0, baseQuery, { v: 'abc' } as any);+ expect(res2.hit).toBe(true);+ expect(res2.replaceable).toBe(false);+ });++ it('requires literal edge spaces when matching the whole cell', () => {+ const worksheet = {+ getCellRaw: () => ({ v: ' abc ' }),+ };++ const res = hitCell(worksheet as any, 0, 0, {+ ...baseQuery,+ matchesTheWholeCell: true,+ findString: ' abc ',+ }, { v: ' abc ' } as any);++ expect(res.hit).toBe(true);+ expect(res.replaceable).toBe(true);+ });++ it('should extract number and boolean cell values for matching', () => {+ const worksheet = {+ getCellRaw: (_row: number, col: number) => (col === 0 ? { v: 123 } : { v: true }),+ };++ expect(hitCell(worksheet as any, 0, 0, { ...baseQuery, findString: '23' }, { v: 123 } as any).hit).toBe(true);+ expect(hitCell(worksheet as any, 0, 1, { ...baseQuery, findString: '1' }, { v: true } as any).hit).toBe(true);+ });++ it('should report misses for empty values and unmatched formula display values', () => {+ const formulaWorksheet = {+ getCellRaw: () => ({ f: '=SUM(1)' }),+ };+ const formulaRawMiss = hitCell(formulaWorksheet as any, 0, 0, {+ ...baseQuery,+ findBy: FindBy.FORMULA,+ findString: '=missing',+ }, { v: 'alpha' } as any);+ expect(formulaRawMiss.hit).toBe(false);+ expect(formulaRawMiss.replaceable).toBe(false);++ const formulaMiss = hitCell(formulaWorksheet as any, 0, 0, { ...baseQuery, findString: 'missing' }, { v: 'alpha' } as any);+ expect(formulaMiss.hit).toBe(false);+ expect(formulaMiss.replaceable).toBe(false);+ expect(formulaMiss.isFormula).toBe(true);++ const emptyWorksheet = {+ getCellRaw: () => ({ v: '' }),+ };+ const emptyMiss = hitCell(emptyWorksheet as any, 0, 0, baseQuery, { v: '' } as any);+ expect(emptyMiss.hit).toBe(false);+ expect(emptyMiss.replaceable).toBe(false);+ });+});++describe('hitCell formula case sensitivity', () => {+ it.each([+ { findString: 'sum', caseSensitive: true, hit: false },+ { findString: 'SUM', caseSensitive: true, hit: true },+ { findString: 'sum', caseSensitive: false, hit: true },+ ])('matches formula query $findString with caseSensitive=$caseSensitive', ({ findString, caseSensitive, hit }) => {+ const cell = { f: '=SUM(6, 3)', v: 9 };+ const worksheet = createWorksheet('sheet-1', { '0,0': cell });+ expect(hitCell(worksheet, 0, 0, { ...baseQuery, findBy: FindBy.FORMULA, findString, caseSensitive }, cell))+ .toMatchObject({ hit, replaceable: hit });+ });+});diff --git a/packages/sheets-find-replace/src/controllers/__tests__/utils.spec.ts b/packages/sheets-find-replace/src/controllers/__tests__/utils.spec.tsindex fb9dd5274c..dbd4e6b99d 100644--- a/packages/sheets-find-replace/src/controllers/__tests__/utils.spec.ts+++ b/packages/sheets-find-replace/src/controllers/__tests__/utils.spec.ts@@ -14,12 +14,8 @@* limitations under the License.*/-import type { Dependency, IWorkbookData, Workbook, Worksheet } from '@univerjs/core';-import type { IFindQuery } from '@univerjs/find-replace';-import { ILogService, IUniverInstanceService, LocaleType, LogLevel, Univer, UniverInstanceType } from '@univerjs/core';-import { FindBy, FindDirection, FindScope } from '@univerjs/find-replace';-import { afterEach, beforeEach, describe, expect, it } from 'vitest';-import { hitCell } from '../sheet-find-replace.controller';+import { describe, expect, it } from 'vitest';+import {isBeforePositionWithColumnPriority,isBeforePositionWithRowPriority,@@ -213,127 +209,3 @@ describe('Test sheet find replace utils', () => {} as any, worksheet)).toBe(false);});});--describe('test "hitCell" method', () => {- let univer: Univer;- let worksheet: Worksheet;-- beforeEach(() => {- const testBed = createTestBed();- univer = testBed.univer;- worksheet = testBed.sheet.getActiveSheet()!;- });-- afterEach(() => {- univer.dispose();- });-- describe('hitting formulas', () => {- describe('replaceable if only searching for raw formulas', () => {- it('should be replaceable when searching for formulas and formula string matches', () => {- const query: IFindQuery = {- findString: '6',- caseSensitive: false,- findBy: FindBy.FORMULA,- findDirection: FindDirection.COLUMN,- findScope: FindScope.SUBUNIT,- matchesTheWholeCell: false,- matchesTheWholeWord: false,- replaceRevealed: false,- };-- // If search by formula, when the formula string failed to match, the cell should not be hit.- const result1 = hitCell(worksheet, 0, 0, query, TEST_WORKBOOK_DATA.sheets.sheet1.cellData![0][0]);- expect(result1.hit).toBeFalsy();- expect(result1.replaceable).toBeFalsy();-- const result2 = hitCell(worksheet, 0, 1, query, TEST_WORKBOOK_DATA.sheets.sheet1.cellData![0][1]);- expect(result2.hit).toBeTruthy();- expect(result2.replaceable).toBeTruthy();- });- });-- it('formula string should support "caseSensitive" option', () => {- const query: IFindQuery = {- findString: 'sum',- caseSensitive: true,- findBy: FindBy.FORMULA,- findDirection: FindDirection.COLUMN,- findScope: FindScope.SUBUNIT,- matchesTheWholeCell: false,- matchesTheWholeWord: false,- replaceRevealed: false,- };-- const result1 = hitCell(worksheet, 0, 1, query, TEST_WORKBOOK_DATA.sheets.sheet1.cellData![0][1]);- expect(result1.hit).toBeFalsy();- expect(result1.replaceable).toBeFalsy();-- const result2 = hitCell(worksheet, 0, 2, query, TEST_WORKBOOK_DATA.sheets.sheet1.cellData![0][2]);- expect(result2.hit).toBeTruthy();- expect(result2.replaceable).toBeTruthy();-- // If we unset 'caseSensitive' and [0][1] should match!- query.caseSensitive = false;- const result3 = hitCell(worksheet, 0, 1, query, TEST_WORKBOOK_DATA.sheets.sheet1.cellData![0][1]);- expect(result3.hit).toBeTruthy();- expect(result3.replaceable).toBeTruthy();- });- });-});--const TEST_WORKBOOK_DATA: IWorkbookData = {- id: 'test',- appVersion: '3.0.0-alpha',- sheets: {- sheet1: {- id: 'sheet1',- cellData: {- 0: {- 0: {- v: 6,- f: '=SUM(3, 3)',- },- 1: {- v: 9,- f: '=SUM(6, 3)',- },- 2: {- v: 9,- f: '=sum(6, 3)', // test case sensitive- },- 3: {- v: 66,- },- },- },- name: 'Sheet-001',- },- },- locale: LocaleType.ZH_CN,- name: '',- sheetOrder: [],- styles: {},-};--function createTestBed(dependencies?: Dependency[]) {- const univer = new Univer();-- const injector = univer.__getInjector();- const get = injector.get.bind(injector);-- dependencies?.forEach((d) => injector.add(d));-- const sheet = univer.createUnit<IWorkbookData, Workbook>(UniverInstanceType.UNIVER_SHEET, TEST_WORKBOOK_DATA);- const univerInstanceService = get(IUniverInstanceService);- univerInstanceService.focusUnit(TEST_WORKBOOK_DATA.id);-- const logService = get(ILogService);- logService.setLogLevel(LogLevel.SILENT);-- return {- univer,- get,- sheet,- };-}diff --git a/packages/sheets-find-replace/src/controllers/sheet-find-replace.controller.ts b/packages/sheets-find-replace/src/controllers/sheet-find-replace.controller.tsindex 2379b4b658..ea759188ed 100644--- a/packages/sheets-find-replace/src/controllers/sheet-find-replace.controller.ts+++ b/packages/sheets-find-replace/src/controllers/sheet-find-replace.controller.ts@@ -81,6 +81,7 @@ import {SetWorksheetActiveOperation,SheetsSelectionsService,} from '@univerjs/sheets';+import { getCoordByCell, getSheetObject, ScrollToCellCommand, SheetSkeletonManagerService } from '@univerjs/sheets-ui';import { debounceTime, filter, merge, skip, Subject, throttleTime } from 'rxjs';import { SheetReplaceCommand } from '../commands/commands/sheet-replace.command';@@ -1056,12 +1057,10 @@ class SheetsFindReplaceProvider extends Disposable implements IFindReplaceProvid* @returns the parsed query object*/private _preprocessQuery(query: Readonly<IFindQuery>): IFindQuery {- let findString = query.caseSensitive+ const findString = query.caseSensitive? query.findString: query.findString.toLowerCase();- findString = findString.trim();-return {...query,findString,@@ -1140,14 +1139,12 @@ export function hitCell(worksheet: Worksheet, row: number, col: number, query: I}function matchCellData(cellData: ICellData, query: IFindQuery): boolean {- let value = extractPureValue(cellData);+ const value = extractPureValue(cellData);if (!value) {return false;}if (query.matchesTheWholeCell) {- // Only need to trim the next when we want to match the whole cell.- value = trimLeadingTrailingWhitespace(value);return query.caseSensitive? value === query.findString: value.toLowerCase() === query.findString;@@ -1170,11 +1167,3 @@ function extractPureValue(cell: ICellData): Nullable<string> {return rawValue;}--/**- * Trim only white spaces but not line breaks from the start and end of a string.- * @param value the string to be trimmed- */-function trimLeadingTrailingWhitespace(value: string): string {- return value.replace(/^ +/g, '').replace(/ +$/g, ''); // be careful there are two spaces in the regex-}