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(sheet-ui): find & replace (#1349)

Wenzhao Hu3828239d5cc8
diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS
index f8281eb9c5..179405cb58 100644
--- a/.github/CODEOWNERS
+++ b/.github/CODEOWNERS
@@ -34,10 +34,14 @@ packages/sheets-ui/src/services/clipboard @yuhongz
packages/sheets-ui/src/services/editor @Jocs
packages/sheets-ui/src/services/editor-bridge.service.ts @Jocs
-packages/sheets-find @wzhudev
+packages/sheets-find-replace @wzhudev
+
packages/sheets-numfmt @Gggpound
-packages/sheets-imoprt-xlsx @Gggpound
+
+packages/sheets-import-xlsx @Gggpound
+
packages/sheets-formula @DR-Univer @Dushusir
+
packages/sheets-zen-editor @Jocs
# slides
diff --git a/.vscode/settings.json b/.vscode/settings.json
index b4a7b73194..3aa3471099 100644
--- a/.vscode/settings.json
+++ b/.vscode/settings.json
@@ -22,6 +22,7 @@
"customd",
"Datas",
"DATEFMTLISG",
+ "Dushusir",
"endindex",
"esbuild",
"evented",
@@ -30,6 +31,7 @@
"fract",
"gainsboro",
"GANTT",
+ "Gggpound",
"Gridlines",
"Hanalei",
"hdmx",
@@ -41,6 +43,7 @@
"IRPC",
"Jamo",
"jikkai",
+ "Jocs",
"Kaiti",
"KANBAN",
"kcode",
@@ -86,7 +89,8 @@
"Xingkai",
"Xinwei",
"Xlookup",
- "XMATCH"
+ "XMATCH",
+ "yuhongz"
],
"vsicons.presets.angular": false,
diff --git a/examples/src/data/sheets/demo/default-workbook-data-demo.ts b/examples/src/data/sheets/demo/default-workbook-data-demo.ts
index 452cd1000a..6bda4be885 100644
--- a/examples/src/data/sheets/demo/default-workbook-data-demo.ts
+++ b/examples/src/data/sheets/demo/default-workbook-data-demo.ts
@@ -19428,8 +19428,8 @@ export const DEFAULT_WORKBOOK_DATA_DEMO: IWorkbookData = {
defaultRowHeight: 25,
mergeData: [
{
- startRow: 37,
- endRow: 36,
+ startRow: 36,
+ endRow: 37,
startColumn: 1,
endColumn: 2,
},
diff --git a/examples/src/data/sheets/demo/default-workbook-data-demo5.ts b/examples/src/data/sheets/demo/default-workbook-data-demo5.ts
index 869bf8c022..aa86dfafe3 100644
--- a/examples/src/data/sheets/demo/default-workbook-data-demo5.ts
+++ b/examples/src/data/sheets/demo/default-workbook-data-demo5.ts
@@ -2657,8 +2657,8 @@ export const DEFAULT_WORKBOOK_DATA_DEMO5: IWorkbookData = {
defaultRowHeight: 25,
mergeData: [
{
- startRow: 37,
- endRow: 36,
+ startRow: 36,
+ endRow: 37,
startColumn: 1,
endColumn: 2,
},
diff --git a/examples/src/sheets/main.ts b/examples/src/sheets/main.ts
index 408775086e..aada98fc87 100644
--- a/examples/src/sheets/main.ts
+++ b/examples/src/sheets/main.ts
@@ -24,7 +24,7 @@ import { UniverFindReplacePlugin } from '@univerjs/find-replace';
import type { IUniverRPCMainThreadConfig } from '@univerjs/rpc';
import { UniverRPCMainThreadPlugin } from '@univerjs/rpc';
import { UniverSheetsPlugin } from '@univerjs/sheets';
-import { UniverSheetsFindPlugin } from '@univerjs/sheets-find-replace';
+import { UniverSheetsFindReplacePlugin } from '@univerjs/sheets-find-replace';
import { UniverSheetsFormulaPlugin } from '@univerjs/sheets-formula';
import { UniverSheetsNumfmtPlugin } from '@univerjs/sheets-numfmt';
import { UniverSheetsUIPlugin } from '@univerjs/sheets-ui';
@@ -78,7 +78,7 @@ univer.registerPlugin(UniverRPCMainThreadPlugin, {
// find replace
univer.registerPlugin(UniverFindReplacePlugin);
-univer.registerPlugin(UniverSheetsFindPlugin);
+univer.registerPlugin(UniverSheetsFindReplacePlugin);
// create univer sheet instance
univer.createUniverSheet(DEFAULT_WORKBOOK_DATA_DEMO);
diff --git a/packages/core/src/common/__tests__/array.spec.ts b/packages/core/src/common/__tests__/array.spec.ts
new file mode 100644
index 0000000000..9c653d21fd
--- /dev/null
+++ b/packages/core/src/common/__tests__/array.spec.ts
@@ -0,0 +1,33 @@
+/**
+ * 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 { rotate } from '../array';
+
+describe('Test array util function', () => {
+ it('should "rotate" function work correctly', () => {
+ const raw = [1, 2, 3, 4, 5];
+
+ // The function do not mutate the original array.
+ expect(rotate(raw, 0)).toEqual([1, 2, 3, 4, 5]);
+ expect(rotate(raw, 1)).toEqual([2, 3, 4, 5, 1]);
+ expect(rotate(raw, 2)).toEqual([3, 4, 5, 1, 2]);
+ expect(rotate(raw, 3)).toEqual([4, 5, 1, 2, 3]);
+ expect(rotate(raw, 4)).toEqual([5, 1, 2, 3, 4]);
+ expect(rotate(raw, 5)).toEqual([1, 2, 3, 4, 5]);
+ expect(rotate(raw, 6)).toEqual([2, 3, 4, 5, 1]);
+ });
+});
diff --git a/packages/core/src/common/array.ts b/packages/core/src/common/array.ts
index 47f3dc1f4d..2a8b7f14a1 100644
--- a/packages/core/src/common/array.ts
+++ b/packages/core/src/common/array.ts
@@ -50,3 +50,36 @@ export function findLast<T>(arr: T[], callback: (item: T, index: number) => bool
return null;
}
+
+/**
+ * Rotate an array without mutating the original array.
+ * @param arr the array to be rotated
+ * @param steps how many steps to rotate
+ * @returns the rotated array, it is another array, the original array is not mutated.
+ */
+export function rotate<T>(arr: Readonly<T[]>, steps: number): readonly T[] {
+ if (arr.length === 0) {
+ return arr;
+ }
+
+ const offset = steps % arr.length;
+ return arr.slice(offset).concat(arr.slice(0, offset));
+}
+
+export function groupBy<T>(arr: Readonly<T[]>, keyFn: (v: T) => string): Map<string, T[]> {
+ const groups = new Map<string, T[]>();
+
+ arr.forEach((element) => {
+ const key = keyFn(element);
+
+ let group = groups.get(key);
+ if (!groups.has(key)) {
+ group = [];
+ groups.set(key, group);
+ }
+
+ group!.push(element);
+ });
+
+ return groups;
+}
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index b8f121e5f1..aeb245bb5d 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -17,7 +17,7 @@
import { installShims } from './common/shims';
export * from './basics';
-export { dedupe, remove } from './common/array';
+export { dedupe, remove, rotate, groupBy } from './common/array';
export {
DEFAULT_EMPTY_DOCUMENT_VALUE,
DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY,
@@ -100,6 +100,7 @@ export {
UndoCommandId,
} from './services/undoredo/undoredo.service';
export * from './shared';
+export { fromCallback } from './shared/rxjs';
// #region sheet
export type { IComposeInterceptors, IInterceptor, InterceptorHandler } from './common/interceptor';
diff --git a/packages/core/src/services/command/command.service.ts b/packages/core/src/services/command/command.service.ts
index 19b022f383..57f70e03ce 100644
--- a/packages/core/src/services/command/command.service.ts
+++ b/packages/core/src/services/command/command.service.ts
@@ -24,7 +24,7 @@ import type { IKeyValue } from '../../shared/types';
import { IContextService } from '../context/context.service';
import { ILogService } from '../log/log.service';
-export const enum CommandType {
+export enum CommandType {
/** Command could generate some operations or mutations. */
COMMAND = 0,
/** An operation that do not require conflict resolve. */
@@ -40,7 +40,7 @@ export interface ICommand<P extends object = object, R = boolean> {
readonly id: string;
readonly type: CommandType;
- handler(accessor: IAccessor, params?: P): Promise<R> | R;
+ handler(accessor: IAccessor, params?: P, options?: IExecutionOptions): Promise<R> | R;
/**
* When this command is unregistered, this function would be called.
@@ -131,9 +131,9 @@ export interface IExecutionOptions {
export type CommandListener = (commandInfo: Readonly<ICommandInfo>, options?: IExecutionOptions) => void;
export interface ICommandService {
- registerCommand(command: ICommand): IDisposable;
+ registerCommand(command: ICommand<object, unknown>): IDisposable;
- registerMultipleCommand(command: ICommand): IDisposable;
+ registerMultipleCommand(command: ICommand<object, unknown>): IDisposable;
executeCommand<P extends object = object, R = boolean>(
id: string,
@@ -259,7 +259,7 @@ export class CommandService implements ICommandService {
const stackItemDisposable = this._pushCommandExecutionStack(commandInfo);
this._beforeCommandExecutionListeners.forEach((listener) => listener(commandInfo, options));
- const result = await this._execute<P, R>(command as ICommand<P, R>, params);
+ const result = await this._execute<P, R>(command as ICommand<P, R>, params, options);
this._commandExecutedListeners.forEach((listener) => listener(commandInfo, options));
stackItemDisposable.dispose();
@@ -300,7 +300,7 @@ export class CommandService implements ICommandService {
const stackItemDisposable = this._pushCommandExecutionStack(commandInfo);
this._beforeCommandExecutionListeners.forEach((listener) => listener(commandInfo, options));
- const result = this._syncExecute<P, R>(command as ICommand<P, R>, params);
+ const result = this._syncExecute<P, R>(command as ICommand<P, R>, params, options);
this._commandExecutedListeners.forEach((listener) => listener(commandInfo, options));
stackItemDisposable.dispose();
@@ -353,7 +353,7 @@ export class CommandService implements ICommandService {
});
}
- private async _execute<P extends object, R = boolean>(command: ICommand<P, R>, params?: P): Promise<R> {
+ private async _execute<P extends object, R = boolean>(command: ICommand<P, R>, params?: P, options?: IExecutionOptions): Promise<R> {
this._logService.debug(
'[CommandService]',
`${'|-'.repeat(Math.max(this._commandExecutingLevel, 0))}executing command "${command.id}"`
@@ -362,7 +362,7 @@ export class CommandService implements ICommandService {
this._commandExecutingLevel++;
let result: R | boolean;
try {
- result = await this._injector.invoke(command.handler, params);
+ result = await this._injector.invoke(command.handler, params, options);
this._commandExecutingLevel--;
} catch (e) {
result = false;
@@ -373,7 +373,7 @@ export class CommandService implements ICommandService {
return result;
}
- private _syncExecute<P extends object, R = boolean>(command: ICommand<P, R>, params?: P): R {
+ private _syncExecute<P extends object, R = boolean>(command: ICommand<P, R>, params?: P, options?: IExecutionOptions): R {
this._logService.debug(
'[CommandService]',
`${'|-'.repeat(Math.max(0, this._commandExecutingLevel))}executing command "${command.id}".`
@@ -382,7 +382,7 @@ export class CommandService implements ICommandService {
this._commandExecutingLevel++;
let result: R | boolean;
try {
- result = this._injector.invoke(command.handler, params) as R;
+ result = this._injector.invoke(command.handler, params, options) as R;
if (result instanceof Promise) {
throw new TypeError('[CommandService]: Command handler should not return a promise.');
}
diff --git a/packages/core/src/services/instance/instance.service.ts b/packages/core/src/services/instance/instance.service.ts
index 428973d7d3..fdd892b983 100644
--- a/packages/core/src/services/instance/instance.service.ts
+++ b/packages/core/src/services/instance/instance.service.ts
@@ -27,9 +27,11 @@ import type { IDocumentData, ISlideData, IWorkbookData } from '../../types/inter
import { FOCUSING_DOC, FOCUSING_SHEET, FOCUSING_SLIDE } from '../context/context';
import { IContextService } from '../context/context.service';
-export const enum UniverInstanceType {
+export enum UniverInstanceType {
UNKNOWN = 0,
+
DOC = 1,
+
SHEET = 2,
SLIDE = 3,
diff --git a/packages/core/src/services/locale/locale.service.ts b/packages/core/src/services/locale/locale.service.ts
index f5e0a11cb4..774e50f2ad 100644
--- a/packages/core/src/services/locale/locale.service.ts
+++ b/packages/core/src/services/locale/locale.service.ts
@@ -38,10 +38,9 @@ export class LocaleService extends Disposable {
}
/**
- * Load more locales after init
+ * Load more locales after init.
*
* @param locales - Locale object
- *
*/
load(locales: ILocales) {
this._locales = Tools.deepMerge(this._locales ?? {}, locales);
@@ -49,9 +48,11 @@ export class LocaleService extends Disposable {
/**
* Translate a key to the current locale
+ *
* @param {string} key the key to translate
* @param {string[]} args optional arguments to replace in the translated string
* @returns {string} the translated string
+ *
* @example
* const locales = {
* [LocaleType.EN_US]: {
diff --git a/packages/core/src/services/undoredo/undoredo.service.ts b/packages/core/src/services/undoredo/undoredo.service.ts
index 73cc57cd1a..8da5174bb7 100644
--- a/packages/core/src/services/undoredo/undoredo.service.ts
+++ b/packages/core/src/services/undoredo/undoredo.service.ts
@@ -26,8 +26,7 @@ import { CommandType, ICommandService, sequenceExecute } from '../command/comman
import { EDITOR_ACTIVATED, FOCUSING_FORMULA_EDITOR, FOCUSING_SHEET } from '../context/context';
import { IContextService } from '../context/context.service';
import { IUniverInstanceService } from '../instance/instance.service';
-
-// TODO: an undo redo element may be merge-able to another undo redo element
+import type { Nullable } from '../../common/type-utils';
export interface IUndoRedoItem {
/** unitID maps to unitId for UniverSheet / UniverDoc / UniverSlide */
@@ -35,9 +34,6 @@ export interface IUndoRedoItem {
undoMutations: IMutationInfo[];
redoMutations: IMutationInfo[];
-
- undo?(mutations: IMutationInfo[]): Promise<boolean> | boolean;
- redo?(mutations: IMutationInfo[]): Promise<boolean> | boolean;
}
export interface IUndoRedoService {
@@ -45,13 +41,28 @@ export interface IUndoRedoService {
pushUndoRedo(item: IUndoRedoItem): void;
- pitchTopUndoElement(): IUndoRedoItem | null;
- pitchTopRedoElement(): IUndoRedoItem | null;
+ /** Pitch the top redo element of the currently focused Univer document instance. */
+ pitchTopUndoElement(): Nullable<IUndoRedoItem>;
+ /** Pitch the top undo element of the currently focused Univer document instance. */
+ pitchTopRedoElement(): Nullable<IUndoRedoItem>;
popUndoToRedo(): void;
popRedoToUndo(): void;
clearUndoRedo(unitID: string): void;
+
+ /**
+ * Batch undo redo elements into a single `IUndoRedoItem` util the returned `IDisposable` is called.
+ *
+ * @deprecated This is a temporary solution. We are going to refactor the undo redo service shortly.
+ * @returns a disposable to cancel batching undo redo elements
+ */
+ __tempBatchingUndoRedo(unitId: string): IDisposable;
+}
+
+enum BatchingStatus {
+ WAITING,
+ CREATED,
}
export interface IUndoRedoCommandInfos {
@@ -69,7 +80,7 @@ export interface IUndoRedoStatus {
const STACK_CAPACITY = 20;
abstract class MultiImplementationCommand implements IDisposable {
- dispose(): void {}
+ dispose(): void { }
async dispatchToHandlers(): Promise<boolean> {
return false;
@@ -92,9 +103,7 @@ export const UndoCommand = new (class extends MultiImplementationCommand impleme
}
const commandService = accessor.get(ICommandService);
- const result = element.undo
- ? await element.undo(element.undoMutations)
- : sequenceExecute(element.undoMutations, commandService);
+ const result = sequenceExecute(element.undoMutations, commandService);
if (result) {
undoRedoService.popUndoToRedo();
@@ -118,9 +127,7 @@ export const RedoCommand = new (class extends MultiImplementationCommand impleme
}
const commandService = accessor.get(ICommandService);
- const result = element.redo
- ? await element.redo(element.redoMutations)
- : sequenceExecute(element.redoMutations, commandService);
+ const result = sequenceExecute(element.redoMutations, commandService);
if (result) {
undoRedoService.popRedoToUndo();
@@ -138,9 +145,12 @@ export class LocalUndoRedoService extends Disposable implements IUndoRedoService
readonly undoRedoStatus$: Observable<IUndoRedoStatus>;
protected readonly _undoRedoStatus$ = new BehaviorSubject<{ undos: number; redos: number }>({ undos: 0, redos: 0 });
+ // Undo and redo stacks are per unit.
protected readonly _undoStacks = new Map<string, IUndoRedoItem[]>();
protected readonly _redoStacks = new Map<string, IUndoRedoItem[]>();
+ private _batchingStatus = new Map<string, BatchingStatus>();
+
constructor(
@IUniverInstanceService protected readonly _univerInstanceService: IUniverInstanceService,
@ICommandService protected readonly _commandService: ICommandService,
@@ -152,6 +162,7 @@ export class LocalUndoRedoService extends Disposable implements IUndoRedoService
this.disposeWithMe(this._commandService.registerCommand(UndoCommand));
this.disposeWithMe(this._commandService.registerCommand(RedoCommand));
+
this.disposeWithMe(toDisposable(() => this._undoRedoStatus$.complete()));
this.disposeWithMe(toDisposable(this._univerInstanceService.focused$.subscribe(() => this._updateStatus())));
}
@@ -165,11 +176,25 @@ export class LocalUndoRedoService extends Disposable implements IUndoRedoService
// redo stack should be cleared when pushing an undo
redoStack.length = 0;
- // TODO: undo redo stack should have a maximum capacity, maybe we should get the config from IConfigService?
- undoStack.push(item);
+ // should try to append first and then
+ if (this._batchingStatus.has(item.unitID)) {
+ const batchingStatus = this._batchingStatus.get(item.unitID)!;
+ const lastItem = this._pitchUndoElement(item.unitID);
+ if (batchingStatus === BatchingStatus.WAITING || !lastItem) {
+ appendNewItem(item);
+ this._batchingStatus.set(item.unitID, BatchingStatus.CREATED);
+ } else {
+ this._tryBatchingElements(lastItem, item);
+ }
+ } else {
+ appendNewItem(item);
+ }
- if (undoStack.length > STACK_CAPACITY) {
- undoStack.splice(0, 1);
+ function appendNewItem(item: IUndoRedoItem) {
+ undoStack.push(item);
+ if (undoStack.length > STACK_CAPACITY) {
+ undoStack.splice(0, 1);
+ }
}
this._updateStatus();
@@ -189,23 +214,24 @@ export class LocalUndoRedoService extends Disposable implements IUndoRedoService
this._updateStatus();
}
- pitchTopUndoElement(): IUndoRedoItem | null {
- const undoStack = this._getUndoStackForFocused();
-
- if (undoStack.length) {
- return undoStack[undoStack.length - 1];
- }
+ pitchTopUndoElement(): Nullable<IUndoRedoItem> {
+ const unitID = this._getFocusedUniverInstanceId();
+ return this._pitchUndoElement(unitID);
+ }
- return null;
+ pitchTopRedoElement(): Nullable<IUndoRedoItem> {
+ const unitID = this._getFocusedUniverInstanceId();
+ return this._pitchRedoElement(unitID);
}
- pitchTopRedoElement(): IUndoRedoItem | null {
- const redoStack = this._getRedoStackForFocused();
- if (redoStack.length) {
- return redoStack[redoStack.length - 1];
- }
+ private _pitchUndoElement(unitId: string): Nullable<IUndoRedoItem> {
+ const stack = this._getUndoStack(unitId);
+ return stack?.length ? stack[stack.length - 1] : null;
+ }
- return null;
+ private _pitchRedoElement(unitId: string): Nullable<IUndoRedoItem> {
+ const stack = this._getRedoStack(unitId);
+ return stack?.length ? stack[stack.length - 1] : null;
}
popUndoToRedo(): void {
@@ -228,6 +254,15 @@ export class LocalUndoRedoService extends Disposable implements IUndoRedoService
}
}
+ __tempBatchingUndoRedo(unitId: string): IDisposable {
+ if (this._batchingStatus.has(unitId)) {
+ throw new Error('[LocalUndoRedoService]: cannot batching undo redo twice at the same time!');
+ }
+
+ this._batchingStatus.set(unitId, BatchingStatus.WAITING);
+ return toDisposable(() => this._batchingStatus.delete(unitId));
+ }
+
protected _updateStatus(): void {
const unitID = this._getFocusedUniverInstanceId();
const undos = (unitID && this._undoStacks.get(unitID)?.length) || 0;
@@ -283,6 +318,12 @@ export class LocalUndoRedoService extends Disposable implements IUndoRedoService
return this._getRedoStack(unitID, true);
}
+ private _tryBatchingElements(item: IUndoRedoItem, newItem: IUndoRedoItem): void {
+ // this could be not that easy in other sitatuations than Find & Replace
+ item.redoMutations.push(...newItem.redoMutations);
+ item.undoMutations.push(...newItem.undoMutations);
+ }
+
private _getFocusedUniverInstanceId() {
let unitID: string = '';
diff --git a/packages/core/src/shared/color/color-kit.ts b/packages/core/src/shared/color/color-kit.ts
index 7b21c45715..d676446245 100644
--- a/packages/core/src/shared/color/color-kit.ts
+++ b/packages/core/src/shared/color/color-kit.ts
@@ -14,23 +14,17 @@
* limitations under the License.
*/
-interface IRgbColor {
+export interface IRgbColor {
b: number;
-
g: number;
-
r: number;
-
a?: number;
}
interface IHslColor {
h: number;
-
l: number;
-
s: number;
-
a?: number;
}
diff --git a/packages/core/src/shared/index.ts b/packages/core/src/shared/index.ts
index aa82ff4e57..c6203cef75 100644
--- a/packages/core/src/shared/index.ts
+++ b/packages/core/src/shared/index.ts
@@ -17,7 +17,7 @@
export * from './array-search';
export * from './blob';
export * from './color/color';
-export { ColorKit, COLORS, RGB_PAREN, RGBA_PAREN } from './color/color-kit';
+export { ColorKit, COLORS, RGB_PAREN, RGBA_PAREN, type IRgbColor } from './color/color-kit';
export * from './command-enum';
export * from './common';
export * from './compare';
diff --git a/packages/core/src/shared/object-matrix.ts b/packages/core/src/shared/object-matrix.ts
index 162a8a0520..fbc8c0824c 100644
--- a/packages/core/src/shared/object-matrix.ts
+++ b/packages/core/src/shared/object-matrix.ts
@@ -298,9 +298,13 @@ export class ObjectMatrix<T> {
return this;
}
+ /**
+ * Iterate the object matrix with row priority, which means it scan the whole range row by row.
+ */
forValue(callback: (row: number, col: number, value: T) => Nullable<boolean>): ObjectMatrix<T> {
const matrix = this._matrix;
const matrixRow = Object.keys(matrix);
+
for (const row of matrixRow) {
const rowNumber = Number(row);
const columns = matrix[rowNumber];
diff --git a/packages/sheets-find-replace/src/action/i-action-set.ts b/packages/core/src/shared/rxjs.ts
similarity index 55%
rename from packages/sheets-find-replace/src/action/i-action-set.ts
rename to packages/core/src/shared/rxjs.ts
index 3f3be7af9e..3465fc06ca 100644
--- a/packages/sheets-find-replace/src/action/i-action-set.ts
+++ b/packages/core/src/shared/rxjs.ts
@@ -14,4 +14,14 @@
* limitations under the License.
*/
-export class IActionSet {}
+import type { IDisposable } from '@wendellhu/redi';
+import { Observable } from 'rxjs';
+
+type CallbackFn<T extends readonly unknown[]> = (cb: (...args: T) => void) => IDisposable;
+
+export function fromCallback<T extends readonly unknown[]>(callback: CallbackFn<T>): Observable<T> {
+ return new Observable((subscriber) => {
+ const disposable: IDisposable | undefined = callback((...args: T) => subscriber.next(args));
+ return () => disposable?.dispose();
+ });
+};
diff --git a/packages/core/src/sheets/__tests__/create-core-test-bed.ts b/packages/core/src/sheets/__tests__/create-core-test-bed.ts
index e3243f11fa..10d8b4bd0b 100644
--- a/packages/core/src/sheets/__tests__/create-core-test-bed.ts
+++ b/packages/core/src/sheets/__tests__/create-core-test-bed.ts
@@ -51,9 +51,8 @@ export function createCoreTestBed(workbookConfig?: IWorkbookData) {
const get = injector.get.bind(injector);
const sheet = univer.createUniverSheet(workbookConfig || TEST_WORKBOOK_DATA);
-
const univerInstanceService = get(IUniverInstanceService);
- univerInstanceService.focusUniverInstance('test');
+ univerInstanceService.focusUniverInstance(workbookConfig?.id ?? 'test');
const logService = get(ILogService);
logService.setLogLevel(LogLevel.SILENT);
diff --git a/packages/core/src/sheets/row-manager.ts b/packages/core/src/sheets/row-manager.ts
index e58ffce885..b69e636ba9 100644
--- a/packages/core/src/sheets/row-manager.ts
+++ b/packages/core/src/sheets/row-manager.ts
@@ -22,8 +22,6 @@ import { RANGE_TYPE } from '../types/interfaces';
/**
* Manage configuration information of all rows, get row height, row length, set row height, etc.
- *
- * @deprecated This class is not necessary. It increases the complexity of the code and does not bring any benefits.
*/
export class RowManager {
private _rowData: IObjectArrayPrimitiveType<Partial<IRowData>>;
diff --git a/packages/core/src/sheets/workbook.ts b/packages/core/src/sheets/workbook.ts
index 4c9558c112..d5cf25e5bf 100644
--- a/packages/core/src/sheets/workbook.ts
+++ b/packages/core/src/sheets/workbook.ts
@@ -169,6 +169,10 @@ export class Workbook extends Disposable {
return this._snapshot.parentRenderUnitId;
}
+ getSheetOrders(): Readonly<string[]> {
+ return this._snapshot.sheetOrder;
+ }
+
getWorksheets(): Map<string, Worksheet> {
return this._worksheets;
}
diff --git a/packages/core/src/sheets/worksheet.ts b/packages/core/src/sheets/worksheet.ts
index bb647577ec..87dd019e74 100644
--- a/packages/core/src/sheets/worksheet.ts
+++ b/packages/core/src/sheets/worksheet.ts
@@ -27,11 +27,9 @@ import type { Styles } from './styles';
import { SheetViewModel } from './view-model';
/**
- * Worksheet instance represents a single sheet in a workbook.
+ * The model of a Worksheet.
*/
export class Worksheet {
- protected _initialized: boolean;
-
protected _sheetId: string;
protected _snapshot: IWorksheetData;
protected _cellData: ObjectMatrix<ICellData>;
@@ -49,13 +47,11 @@ export class Worksheet {
const { columnData, rowData, cellData } = this._snapshot;
this._sheetId = this._snapshot.id ?? Tools.generateRandomId(6);
- this._initialized = false;
this._cellData = new ObjectMatrix<ICellData>(cellData);
this._rowManager = new RowManager(this._snapshot, rowData);
this._columnManager = new ColumnManager(this._snapshot, columnData);
- // This view model will immediately injected with hooks from SheetViewModel service as Worksheet
- // is constructed.
+ // This view model will immediately injected with hooks from SheetViewModel service as Worksheet is constructed.
this._viewModel = new SheetViewModel();
}
@@ -212,35 +208,6 @@ export class Worksheet {
return this._snapshot.mergeData;
}
- /**
- * @deprecated use `getMergedCell` instead
- * @param row
- * @param col
- * @returns
- */
- getMergedCells(row: number, col: number): Nullable<IRange[]> {
- const _rectangleList = this._snapshot.mergeData;
- const rectList = [];
- for (let i = 0; i < _rectangleList.length; i++) {
- const range = _rectangleList[i];
- if (
- Rectangle.intersects(
- {
- startRow: row,
- startColumn: col,
- endRow: row,
- endColumn: col,
- },
- range
- )
- ) {
- rectList.push(range);
- }
- }
-
- return rectList.length ? rectList : null;
- }
-
getMergedCell(row: number, col: number): Nullable<IRange> {
const rectangleList = this._snapshot.mergeData;
for (let i = 0; i < rectangleList.length; i++) {
@@ -281,7 +248,6 @@ export class Worksheet {
* Notice that `ICellData` here is not after copying. In another word, the object matrix here should be
* considered as a slice of the original worksheet data matrix.
*/
- // PERF: we could not skip indexes with merged cells, because we have already known the merged cells' range
getMatrixWithMergedCells(
row: number,
col: number,
@@ -305,6 +271,8 @@ export class Worksheet {
}
});
+ // iterate over all merged cells in the range and remove non-top-left positions
+ // from the matrix we just created
mergedCellsInRange.forEach((mergedCell) => {
const { startColumn, startRow, endColumn, endRow } = mergedCell;
createRowColIter(startRow, endRow, startColumn, endColumn).forEach((row, col) => {
diff --git a/packages/core/src/types/interfaces/i-cell-data.ts b/packages/core/src/types/interfaces/i-cell-data.ts
index 872f39397d..809ea390db 100644
--- a/packages/core/src/types/interfaces/i-cell-data.ts
+++ b/packages/core/src/types/interfaces/i-cell-data.ts
@@ -33,16 +33,27 @@ export interface ICellData {
* the plug-in does not need to change the data, reducing the pressure on the back-end interface id?: string.
*/
p?: Nullable<IDocumentData>; // univer docs, set null for cell clear all
+
/** style id */
s?: Nullable<IStyleData | string>;
+
/**
* Origin value
*/
v?: Nullable<CellValue>;
+
// Usually the type is automatically determined based on the data, or the user directly specifies
t?: Nullable<CellValueType>; // 1 string, 2 number, 3 boolean, 4 force string, green icon, set null for cell clear all
- f?: Nullable<string>; // formula '=SUM(1)'
- si?: Nullable<string>; // formula id
+
+ /**
+ * Raw formula string. For example `=SUM(A1:B4)`.
+ */
+ f?: Nullable<string>;
+
+ /**
+ * Id of the formula.
+ */
+ si?: Nullable<string>;
}
export interface ICellDataForSheetInterceptor extends ICellData {
diff --git a/packages/core/src/types/interfaces/i-range.ts b/packages/core/src/types/interfaces/i-range.ts
index e04acd7266..bb5f308755 100644
--- a/packages/core/src/types/interfaces/i-range.ts
+++ b/packages/core/src/types/interfaces/i-range.ts
@@ -69,6 +69,7 @@ export interface IRange extends IRowRange {
* startColumn
*/
startColumn: number;
+
/**
* The end column (exclusive) of the range
* endColumn
@@ -99,6 +100,12 @@ export interface IGridRange {
range: IRange;
}
+export interface IUnitRangeName {
+ unitId: string;
+ sheetName: string;
+ range: IRange;
+}
+
/**
* Range data of Unit
*/
diff --git a/packages/core/src/types/interfaces/i-selection-data.ts b/packages/core/src/types/interfaces/i-selection-data.ts
index 524a0fcad8..1a23603bf8 100644
--- a/packages/core/src/types/interfaces/i-selection-data.ts
+++ b/packages/core/src/types/interfaces/i-selection-data.ts
@@ -43,7 +43,14 @@ export interface ISelectionCellWithCoord extends IPosition, ISingleCell {
}
export interface ISelection {
+ /**
+ * Sheet selection range.
+ */
range: IRange;
+
+ /**
+ * The highlighted cell in the selection range. If there are several selections, only one selection would have a primary cell.
+ */
primary: Nullable<ISelectionCell>;
}
diff --git a/packages/design/src/components/checkbox-group/__tests__/index.spec.tsx b/packages/design/src/components/checkbox-group/__tests__/index.spec.tsx
index 20198a44d3..78e24fe22e 100644
--- a/packages/design/src/components/checkbox-group/__tests__/index.spec.tsx
+++ b/packages/design/src/components/checkbox-group/__tests__/index.spec.tsx
@@ -62,6 +62,6 @@ describe('CheckboxGroup', () => {
fireEvent.click(getByText('y'));
fireEvent.click(getByText('y'));
- expect(result).toEqual(['0', '1']);
+ expect(result).toEqual(['0', false]);
});
});
diff --git a/packages/design/src/components/checkbox/Checkbox.tsx b/packages/design/src/components/checkbox/Checkbox.tsx
index 9124f68bf4..d142f30ff6 100644
--- a/packages/design/src/components/checkbox/Checkbox.tsx
+++ b/packages/design/src/components/checkbox/Checkbox.tsx
@@ -61,10 +61,10 @@ export function Checkbox(props: ICheckboxProps) {
if (!onChange || disabled) return;
if (typeof value !== 'undefined') {
- onChange && onChange(value);
+ onChange?.(!value);
} else {
const checked = inputRef?.current?.checked!;
- onChange && onChange(checked);
+ onChange?.(!checked);
}
}
diff --git a/packages/design/src/components/design-token/Palette.tsx b/packages/design/src/components/design-token/Palette.tsx
index 7f8adb0343..3097d8d93b 100644
--- a/packages/design/src/components/design-token/Palette.tsx
+++ b/packages/design/src/components/design-token/Palette.tsx
@@ -48,7 +48,7 @@ export function Palette(props: IProps) {
colors: ['primaryColor', 'primaryColorHover'],
},
{
- title: 'Fuctional / 功能',
+ title: 'Functional / 功能',
colors: ['infoColor', 'successColor', 'warningColor', 'errorColor'],
},
{
diff --git a/packages/design/src/components/form-layout/FormLayout.tsx b/packages/design/src/components/form-layout/FormLayout.tsx
index 68223e6b4f..2e269486c2 100644
--- a/packages/design/src/components/form-layout/FormLayout.tsx
+++ b/packages/design/src/components/form-layout/FormLayout.tsx
@@ -15,6 +15,7 @@
*/
import clsx from 'clsx';
+import type { PropsWithChildren } from 'react';
import React from 'react';
import styles from './index.module.less';
@@ -32,9 +33,23 @@ export const FormLayout = (props: IFormLayoutProps) => {
const { label, desc, children, style, className } = props;
return (
<div className={clsx(styles.formLayout, className)} style={style}>
- <div className={styles.formLayoutLabel}>{label}</div>
- {desc ? <div className={styles.formLayoutDesc}>{desc}</div> : null}
+ {label && <div className={styles.formLayoutLabel}>{label}</div>}
+ {desc && <div className={styles.formLayoutDesc}>{desc}</div>}
<div className={styles.formLayoutContent}>{children}</div>
</div>
);
};
+
+export type IFormDualColumnLayoutProps = PropsWithChildren;
+
+/**
+ * A dual columns layout component for the form.
+ * @param props props of the component
+ */
+export const FormDualColumnLayout = (props: IFormDualColumnLayoutProps) => {
+ return (
+ <div className={styles.formDualColumnLayout}>
+ {props.children}
+ </div>
+ );
+};
diff --git a/packages/design/src/components/form-layout/index.module.less b/packages/design/src/components/form-layout/index.module.less
index 5f20baed38..5d6d2178d5 100644
--- a/packages/design/src/components/form-layout/index.module.less
+++ b/packages/design/src/components/form-layout/index.module.less
@@ -4,6 +4,7 @@
&-label {
font-size: var(--font-size-sm);
+ min-height: var(--font-size-sm);
color: rgba(var(--grey-400));
}
@@ -16,5 +17,28 @@
&-content {
margin-top: var(--margin-xs);
margin-bottom: var(--margin-sm);
+
+ .input-affix-wrapper {
+ width: 100%;
+ }
+
+ .select {
+ width: 100%;
+ }
+
+ .range-selector {
+ width: 100%;
+ }
+ }
+}
+
+.form-dual-column-layout {
+ display: flex;
+ justify-content: space-between;
+
+ .form-layout {
+ flex-grow: 1;
+ flex-shrink: 1;
+ max-width: calc(50% - 8px);
}
}
diff --git a/packages/design/src/components/form-layout/index.ts b/packages/design/src/components/form-layout/index.ts
index a4e00a9757..b6e1fbd8b9 100644
--- a/packages/design/src/components/form-layout/index.ts
+++ b/packages/design/src/components/form-layout/index.ts
@@ -14,4 +14,5 @@
* limitations under the License.
*/
-export * from './FormLayout';
+export type { IFormDualColumnLayoutProps, IFormLayoutProps } from './FormLayout';
+export { FormDualColumnLayout, FormLayout } from './FormLayout';
diff --git a/packages/design/src/components/input/Input.tsx b/packages/design/src/components/input/Input.tsx
index 2395a7f933..a4e20fdd64 100644
--- a/packages/design/src/components/input/Input.tsx
+++ b/packages/design/src/components/input/Input.tsx
@@ -16,12 +16,13 @@
import { CloseSingle } from '@univerjs/icons';
import clsx from 'clsx';
+import type { InputProps } from 'rc-input';
import RcInput from 'rc-input';
import React from 'react';
import styles from './index.module.less';
-export interface IInputProps {
+export interface IInputProps extends Pick<InputProps, 'onFocus' | 'onBlur'> {
/**
* Whether the input is autoFocus
* @default false
@@ -105,6 +106,7 @@ export function Input(props: IInputProps) {
onClick,
onKeyDown,
onChange,
+ ...rest
} = props;
function handleChange(e: React.ChangeEvent<HTMLInputElement>) {
@@ -122,12 +124,8 @@ export function Input(props: IInputProps) {
return (
<RcInput
prefixCls={styles.input}
- classNames={{
- affixWrapper: _className,
- }}
- styles={{
- affixWrapper: affixWrapperStyle,
- }}
+ classNames={{ affixWrapper: _className }}
+ styles={{ affixWrapper: affixWrapperStyle }}
autoFocus={autoFocus}
type={type}
placeholder={placeholder}
@@ -136,9 +134,8 @@ export function Input(props: IInputProps) {
onClick={onClick}
onKeyDown={onKeyDown}
onChange={handleChange}
- allowClear={{
- clearIcon: allowClear ? <CloseSingle /> : <></>,
- }}
+ allowClear={{ clearIcon: allowClear ? <CloseSingle /> : <></> }}
+ {...rest}
/>
);
}
diff --git a/packages/design/src/components/pager/Pager.tsx b/packages/design/src/components/pager/Pager.tsx
index cc458c94d2..c1c2a5b4ee 100644
--- a/packages/design/src/components/pager/Pager.tsx
+++ b/packages/design/src/components/pager/Pager.tsx
@@ -15,11 +15,13 @@
*/
import { MoreLeftSingle, MoreRightSingle } from '@univerjs/icons';
-import React, { useMemo } from 'react';
+import React, { Fragment, useMemo } from 'react';
import styles from './index.module.less';
export interface IPagerProps {
+ text?: string;
+
value: number;
total: number;
loop?: boolean;
@@ -28,8 +30,9 @@ export interface IPagerProps {
}
export function Pager(props: IPagerProps) {
- const { value: current = 0, total: count = 0, loop } = props;
- const text = useMemo(() => `${current}/${count}`, [current, count]);
+ const { value: current = 0, total: count = 0, loop, text: propText } = props;
+ const text = useMemo(() => propText ?? `${current}/${count}`, [current, count, propText]);
+ const hasValue = count > 0;
const onClickLeftArrow = () => {
if (current === 1) {
@@ -53,13 +56,19 @@ export function Pager(props: IPagerProps) {
return (
<div className={styles.pager}>
- <div role="button" className={styles.pagerLeftArrow} onClick={onClickLeftArrow}>
- <MoreLeftSingle />
- </div>
- <div className={styles.pagerNumber}>{text}</div>
- <div role="button" className={styles.pagerRightArrow} onClick={onClickRightArrow}>
- <MoreRightSingle />
- </div>
+ {hasValue
+ ? (
+ <Fragment>
+ <div role="button" className={styles.pagerLeftArrow} onClick={onClickLeftArrow}>
+ <MoreLeftSingle />
+ </div>
+ <div className={styles.pagerNumber}>{text}</div>
+ <div role="button" className={styles.pagerRightArrow} onClick={onClickRightArrow}>
+ <MoreRightSingle />
+ </div>
+ </Fragment>
+ )
+ : <div className={styles.pagerNumber}>{text}</div>}
</div>
);
}
diff --git a/packages/design/src/index.ts b/packages/design/src/index.ts
index d912917d87..a36863e529 100644
--- a/packages/design/src/index.ts
+++ b/packages/design/src/index.ts
@@ -26,7 +26,7 @@ export { Container, type IContainerProps } from './components/container';
export { DatePicker, type IDatePickerProps } from './components/date-picker';
export { Dialog, type IDialogProps } from './components/dialog';
export { Dropdown, type IDropdownProps } from './components/dropdown';
-export { FormLayout, type IFormLayoutProps } from './components/form-layout';
+export { FormDualColumnLayout, type IFormDualColumnLayoutProps, FormLayout, type IFormLayoutProps } from './components/form-layout';
export { type IInputProps, type IInputWithSlotProps, Input, InputWithSlot } from './components/input';
export { type IInputNumberProps, InputNumber } from './components/input-number';
export { Menu, MenuItem, MenuItemGroup, SubMenu } from './components/menu';
diff --git a/packages/design/src/themes/default.module.less b/packages/design/src/themes/default.module.less
index ac0648637e..2b2457be76 100644
--- a/packages/design/src/themes/default.module.less
+++ b/packages/design/src/themes/default.module.less
@@ -3,7 +3,7 @@
/**
* new design system
*/
-// Fuctional / 功能
+// Functional / 功能
@info-color: @blue-400;
@success-color: @green-500;
@warning-color: @gold-400;
@@ -17,7 +17,7 @@
@link-color: @blue-500;
:export {
- // Fuctional / 功能
+ // Functional / 功能
--info-color: @info-color;
--success-color: @success-color;
--warning-color: @warning-color;
diff --git a/packages/design/src/themes/green.module.less b/packages/design/src/themes/green.module.less
index 07695f3e2b..cd851e6351 100644
--- a/packages/design/src/themes/green.module.less
+++ b/packages/design/src/themes/green.module.less
@@ -17,7 +17,7 @@
@link-color: @blue-500;
:export {
- // Fuctional / 功能
+ // Functional / 功能
--info-color: @info-color;
--success-color: @success-color;
--warning-color: @warning-color;
diff --git a/packages/docs-ui/src/controllers/app-ui-controller.ts b/packages/docs-ui/src/controllers/app-ui-controller.ts
index a96c766063..d0a1192d9f 100644
--- a/packages/docs-ui/src/controllers/app-ui-controller.ts
+++ b/packages/docs-ui/src/controllers/app-ui-controller.ts
@@ -17,9 +17,9 @@
import type { LocaleType } from '@univerjs/core';
import { LocaleService, RxDisposable } from '@univerjs/core';
import { Inject, Injector, Optional } from '@wendellhu/redi';
-
import { ILayoutService } from '@univerjs/ui';
import { ITextSelectionRenderManager } from '@univerjs/engine-render';
+
import type { IUniverDocsUIConfig } from '../basics';
import { DocContainerUIController } from './doc-container-ui-controller';
diff --git a/packages/engine-formula/src/engine/utils/r1c1-reference.ts b/packages/engine-formula/src/engine/utils/r1c1-reference.ts
index 02f89bbfc2..136d2d4465 100644
--- a/packages/engine-formula/src/engine/utils/r1c1-reference.ts
+++ b/packages/engine-formula/src/engine/utils/r1c1-reference.ts
@@ -14,9 +14,9 @@
* limitations under the License.
*/
-import { AbsoluteRefType, type IRange } from '@univerjs/core';
+import { AbsoluteRefType } from '@univerjs/core';
+import type { IRange, IUnitRangeName } from '@univerjs/core';
-import type { IGridRangeName } from './reference';
import { handleRefStringInfo } from './reference';
const $relativeRegex = /[\[\]]/g;
@@ -50,7 +50,7 @@ function singleReference(refBody: string, currentRow = 0, currentColumn = 0) {
};
}
-export function deserializeRangeForR1C1(refString: string, currentRow = 0, currentColumn = 0): IGridRangeName {
+export function deserializeRangeForR1C1(refString: string, currentRow = 0, currentColumn = 0): IUnitRangeName {
const { refBody, sheetName, unitId } = handleRefStringInfo(refString);
const colonIndex = refBody.indexOf(':');
diff --git a/packages/engine-formula/src/engine/utils/reference.ts b/packages/engine-formula/src/engine/utils/reference.ts
index 8027a98749..5265559172 100644
--- a/packages/engine-formula/src/engine/utils/reference.ts
+++ b/packages/engine-formula/src/engine/utils/reference.ts
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-import type { IRange } from '@univerjs/core';
+import type { IRange, IUnitRangeName } from '@univerjs/core';
import { AbsoluteRefType, RANGE_TYPE, Tools } from '@univerjs/core';
import { includeFormulaLexerToken } from '../../basics/match-token';
@@ -23,12 +23,6 @@ import { UNIT_NAME_REGEX } from '../../basics/regex';
const $ROW_REGEX = /[^0-9]/g;
const $COLUMN_REGEX = /[^A-Za-z]/g;
-export interface IGridRangeName {
- unitId: string;
- sheetName: string;
- range: IRange;
-}
-
export interface IAbsoluteRefTypeForRange {
startAbsoluteRefType: AbsoluteRefType;
endAbsoluteRefType?: AbsoluteRefType;
@@ -169,10 +163,11 @@ export function serializeRangeWithSpreadsheet(unit: string, sheetName: string, r
if (needsQuoting(unit) || needsQuoting(sheetName)) {
return `'[${unit}]${sheetName}'!${serializeRange(range)}`;
}
+
return `[${unit}]${sheetName}!${serializeRange(range)}`;
}
-export function serializeRangeToRefString(gridRangeName: IGridRangeName) {
+export function serializeRangeToRefString(gridRangeName: IUnitRangeName) {
const { unitId, sheetName, range } = gridRangeName;
if (unitId != null && unitId.length > 0 && sheetName != null && sheetName.length > 0) {
@@ -229,7 +224,7 @@ export function handleRefStringInfo(refString: string) {
};
}
-export function deserializeRangeWithSheet(refString: string): IGridRangeName {
+export function deserializeRangeWithSheet(refString: string): IUnitRangeName {
const { refBody, sheetName, unitId } = handleRefStringInfo(refString);
const colonIndex = refBody.indexOf(':');
diff --git a/packages/engine-render/src/basics/tools.ts b/packages/engine-render/src/basics/tools.ts
index f6188bf308..a79a46bc69 100644
--- a/packages/engine-render/src/basics/tools.ts
+++ b/packages/engine-render/src/basics/tools.ts
@@ -477,10 +477,18 @@ export function getCellPositionByIndex(
const startColumn = column - 1;
const startY = rowHeightAccumulation[startRow] || 0;
- const endY = rowHeightAccumulation[row] || rowHeightAccumulation[rowHeightAccumulation.length - 1];
+ let endY = rowHeightAccumulation[row];
+
+ if (endY == null) {
+ endY = rowHeightAccumulation[rowHeightAccumulation.length - 1];
+ }
const startX = columnWidthAccumulation[startColumn] || 0;
- const endX = columnWidthAccumulation[column] || columnWidthAccumulation[columnWidthAccumulation.length - 1];
+ let endX = columnWidthAccumulation[column];
+
+ if (endX == null) {
+ endX = columnWidthAccumulation[columnWidthAccumulation.length - 1];
+ }
return {
startY,
diff --git a/packages/engine-render/src/components/index.ts b/packages/engine-render/src/components/index.ts
index 17828469ac..917c8b7520 100644
--- a/packages/engine-render/src/components/index.ts
+++ b/packages/engine-render/src/components/index.ts
@@ -19,4 +19,5 @@ export * from './docs';
export * from './extension';
export * from './sheets';
export * from './skeleton';
+export { RENDER_RAW_FORMULA_KEY } from './sheets/sheet-skeleton';
export * from './slides';
diff --git a/packages/engine-render/src/components/sheets/sheet-skeleton.ts b/packages/engine-render/src/components/sheets/sheet-skeleton.ts
index cfef702bbc..a981208b22 100644
--- a/packages/engine-render/src/components/sheets/sheet-skeleton.ts
+++ b/packages/engine-render/src/components/sheets/sheet-skeleton.ts
@@ -31,7 +31,6 @@ import type {
ITextRotation,
ITextStyle,
IWorksheetData,
- LocaleService,
Nullable,
Styles,
TextDirection,
@@ -44,9 +43,11 @@ import {
DocumentDataModel,
getColorStyle,
HorizontalAlign,
+ IContextService,
isEmptyCell,
isNullCell,
isWhiteColor,
+ LocaleService,
ObjectMatrix,
searchArray,
Tools,
@@ -54,6 +55,8 @@ import {
WrapStrategy,
} from '@univerjs/core';
+import { Inject } from '@wendellhu/redi';
+import { distinctUntilChanged, startWith } from 'rxjs';
import { BORDER_TYPE, COLOR_BLACK_RGB, MAXIMUM_ROW_HEIGHT } from '../../basics/const';
import { getRotateOffsetAndFarthestHypotenuse } from '../../basics/draw';
import type { IDocumentSkeletonColumn } from '../../basics/i-document-skeleton-cached';
@@ -189,17 +192,15 @@ const DEFAULT_PADDING_DATA = {
r: 2,
};
+export const RENDER_RAW_FORMULA_KEY = 'RENDER_RAW_FORMULA';
+
export class SpreadsheetSkeleton extends Skeleton {
private _rowHeightAccumulation: number[] = [];
-
- private _rowTotalHeight: number = 0;
-
private _columnWidthAccumulation: number[] = [];
- private _columnTotalWidth: number = 0;
-
+ private _rowTotalHeight = 0;
+ private _columnTotalWidth = 0;
private _rowHeaderWidth = 0;
-
private _columnHeaderHeight = 0;
private _rowColumnSegment: IRowColumnSegment = {
@@ -210,11 +211,7 @@ export class SpreadsheetSkeleton extends Skeleton {
};
private _dataMergeCache: IRange[] = [];
-
- // private _dataMergeCacheAll: ObjectMatrix<IRange>;
-
private _overflowCache: ObjectMatrix<IRange> = new ObjectMatrix();
-
private _stylesCache: IStylesCache = {
background: {},
backgroundPositions: new ObjectMatrix<ISelectionCellWithCoord>(),
@@ -222,24 +219,28 @@ export class SpreadsheetSkeleton extends Skeleton {
border: new ObjectMatrix<BorderCache>(),
};
+ /** A matrix to store if a (row, column) position has render cache. */
private _renderedCellCache = new ObjectMatrix<boolean>();
private _showGridlines: BooleanNumber = BooleanNumber.TRUE;
private _marginTop: number = 0;
-
private _marginLeft: number = 0;
+ private _renderRawFormula = false;
+
constructor(
private _worksheet: Worksheet | undefined,
private _config: IWorksheetData,
private _cellData: ObjectMatrix<Nullable<ICellData>>,
private _styles: Styles,
- _localeService: LocaleService
+ @Inject(LocaleService) _localeService: LocaleService,
+ @IContextService private readonly _contextService: IContextService
) {
super(_localeService);
- this.updateLayout();
+ this._updateLayout();
+ this._initContextListener();
// this.updateDataMerge();
}
@@ -315,16 +316,10 @@ export class SpreadsheetSkeleton extends Skeleton {
config: IWorksheetData,
cellData: ObjectMatrix<Nullable<ICellData>>,
styles: Styles,
- LocaleService: LocaleService
+ localeService: LocaleService,
+ contextService: IContextService
) {
- return new SpreadsheetSkeleton(worksheet, config, cellData, styles, LocaleService);
- }
-
- /**
- * @deprecated should never expose a property that is provided by another module!
- */
- getWorksheetConfig() {
- return this._config;
+ return new SpreadsheetSkeleton(worksheet, config, cellData, styles, localeService, contextService);
}
/**
@@ -341,6 +336,19 @@ export class SpreadsheetSkeleton extends Skeleton {
return this._styles;
}
+ private _initContextListener() {
+ this.disposeWithMe(
+ this._contextService.subscribeContextValue$(RENDER_RAW_FORMULA_KEY).pipe(
+ startWith(false),
+ distinctUntilChanged()
+ ).subscribe((renderRaw) => {
+ this._renderRawFormula = renderRaw;
+ this._resetCache();
+ this.makeDirty(true);
+ })
+ );
+ }
+
setOverflowCache(value: ObjectMatrix<IRange>) {
this._overflowCache = value;
}
@@ -358,7 +366,7 @@ export class SpreadsheetSkeleton extends Skeleton {
return;
}
- this.updateLayout();
+ this._updateLayout();
if (!this._rowHeightAccumulation || !this._columnWidthAccumulation) {
return;
@@ -501,10 +509,11 @@ export class SpreadsheetSkeleton extends Skeleton {
return Math.min(height, MAXIMUM_ROW_HEIGHT);
}
- updateLayout() {
+ private _updateLayout() {
if (!this.dirty) {
return;
}
+
const {
rowData,
columnData,
@@ -551,6 +560,14 @@ export class SpreadsheetSkeleton extends Skeleton {
return this._getBounding(this._rowHeightAccumulation, this._columnWidthAccumulation, bounds?.viewBound);
}
+ /**
+ * @deprecated should never expose a property that is provided by another module!
+ * @returns
+ */
+ getWorksheetConfig() {
+ return this._config;
+ }
+
getRowColumnSegmentByViewBound(bound?: IBoundRectNoAngle) {
return this._getBounding(this._rowHeightAccumulation, this._columnWidthAccumulation, bound);
}
@@ -1029,7 +1046,7 @@ export class SpreadsheetSkeleton extends Skeleton {
private _getCellDocumentModel(
cell: Nullable<ICellData>,
isDeepClone: boolean = false,
- formulaFirst: boolean = false,
+ displayRawFormula: boolean = false,
ignoreTextRotation: boolean = false
): Nullable<IDocumentLayoutObject> {
const style = this._styles.getStyleByCell(cell);
@@ -1050,10 +1067,8 @@ export class SpreadsheetSkeleton extends Skeleton {
const wrapStrategy: WrapStrategy = cellOtherConfig.wrapStrategy || WrapStrategy.UNSPECIFIED;
const paddingData: IPaddingData = cellOtherConfig.paddingData || DEFAULT_PADDING_DATA;
- if (cell.f && formulaFirst) {
- /**
- * The formula does not detect horizontal alignment and rotation.
- */
+ if (cell.f && displayRawFormula) {
+ // The formula does not detect horizontal alignment and rotation.
documentModel = this._getDocumentDataByStyle(cell.f.toString(), {}, { verticalAlign });
horizontalAlign = HorizontalAlign.UNSPECIFIED;
} else if (cell.p) {
@@ -1140,7 +1155,7 @@ export class SpreadsheetSkeleton extends Skeleton {
// wrap and angle handler
const { documentSkeleton, vertexAngle = 0, centerAngle = 0, horizontalAlign, wrapStrategy } = docsConfig;
- const cell = this.getCellData().getValue(row, column);
+ const cell = this._cellData.getValue(row, column);
const { t: cellValueType = CellValueType.STRING } = cell || {};
@@ -1660,18 +1675,17 @@ export class SpreadsheetSkeleton extends Skeleton {
return;
}
- const modelObject = cell && this._getCellDocumentModel(cell);
-
+ const modelObject = cell && this._getCellDocumentModel(cell, undefined, this._renderRawFormula);
if (modelObject == null) {
return;
}
- const { documentModel, fontString, textRotation, wrapStrategy, verticalAlign, horizontalAlign } = modelObject;
-
+ const { documentModel } = modelObject;
if (documentModel == null) {
return;
}
+ const { fontString, textRotation, wrapStrategy, verticalAlign, horizontalAlign } = modelObject;
const documentViewModel = new DocumentViewModel(documentModel);
if (!cache.font![fontString]) {
diff --git a/packages/engine-render/src/scene.-transformer.ts b/packages/engine-render/src/scene.transformer.ts
similarity index 100%
rename from packages/engine-render/src/scene.-transformer.ts
rename to packages/engine-render/src/scene.transformer.ts
diff --git a/packages/engine-render/src/scene.ts b/packages/engine-render/src/scene.ts
index a087b9b99e..86c31782d8 100644
--- a/packages/engine-render/src/scene.ts
+++ b/packages/engine-render/src/scene.ts
@@ -28,8 +28,8 @@ import { Transform } from './basics/transform';
import { Vector2 } from './basics/vector2';
import type { UniverRenderingContext } from './context';
import { Layer } from './layer';
-import type { ITransformerConfig } from './scene.-transformer';
-import { Transformer } from './scene.-transformer';
+import type { ITransformerConfig } from './scene.transformer';
+import { Transformer } from './scene.transformer';
import { InputManager } from './scene.input-manager';
import type { SceneViewer } from './scene-viewer';
import type { ThinEngine } from './thin-engine';
diff --git a/packages/find-replace/README-zh.md b/packages/find-replace/README-zh.md
index 357db9b8fd..b62e894249 100644
--- a/packages/find-replace/README-zh.md
+++ b/packages/find-replace/README-zh.md
@@ -5,10 +5,16 @@
## 简介
-TODO: Not yet written.
+该包提供了支持查找和替换功能的基本能力。配合其他插件,例如 `@univerjs/sheets-find-replace`,可以同时在不同类型的文件中查找和替换文本。
## 使用指南
+```ts
+import { UniverFindReplacePlugin } from '@univerjs/find-replace';
+
+univer.registerPlugin(UniverFindReplacePlugin);
+```
+
### 安装
```shell
diff --git a/packages/find-replace/README.md b/packages/find-replace/README.md
index 2d6b636bfc..7e975f555b 100644
--- a/packages/find-replace/README.md
+++ b/packages/find-replace/README.md
@@ -5,10 +5,16 @@
## Introduction
-TODO: Not yet written.
+This package provides the basic ability to support find and replace. With other plugins, such as `@univerjs/sheets-find-replace`, you can find and replace text in different types of files at the same time.
## Usage
+```ts
+import { UniverFindReplacePlugin } from '@univerjs/find-replace';
+
+univer.registerPlugin(UniverFindReplacePlugin);
+```
+
### Installation
```shell
diff --git a/packages/find-replace/package.json b/packages/find-replace/package.json
index 90da3ab6d9..5d16d3da3a 100644
--- a/packages/find-replace/package.json
+++ b/packages/find-replace/package.json
@@ -63,6 +63,9 @@
"peerDependencies": {
"@univerjs/core": "workspace:*",
"@univerjs/design": "workspace:*",
+ "@univerjs/engine-formula": "workspace:*",
+ "@univerjs/engine-render": "workspace:*",
+ "@univerjs/icons": "^0.1.40",
"@univerjs/ui": "workspace:*",
"@wendellhu/redi": "0.13.0",
"react": ">=16.9.0",
@@ -75,6 +78,8 @@
"@types/react": "^18.2.64",
"@univerjs/core": "workspace:*",
"@univerjs/design": "workspace:*",
+ "@univerjs/engine-formula": "workspace:*",
+ "@univerjs/engine-render": "workspace:*",
"@univerjs/shared": "workspace:*",
"@univerjs/ui": "workspace:*",
"@wendellhu/redi": "^0.13.0",
diff --git a/packages/find-replace/src/commands/command/replace.command.ts b/packages/find-replace/src/commands/command/replace.command.ts
new file mode 100644
index 0000000000..bb918d293a
--- /dev/null
+++ b/packages/find-replace/src/commands/command/replace.command.ts
@@ -0,0 +1,79 @@
+/**
+ * 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 { ICommand } from '@univerjs/core';
+import { CommandType, LocaleService } from '@univerjs/core';
+import { IConfirmService, IMessageService } from '@univerjs/ui';
+import { MessageType } from '@univerjs/design';
+
+import { IFindReplaceService } from '../../services/find-replace.service';
+
+export const ReplaceCurrentMatchCommand: ICommand = {
+ id: 'ui.command.replace-current-match',
+ type: CommandType.COMMAND,
+ handler: (accessor) => {
+ const findReplaceService = accessor.get(IFindReplaceService);
+ return findReplaceService.replace();
+ },
+};
+
+const CONFIRM_REPLACE_ALL_ID = 'CONFIRM_REPLACE_ALL';
+
+export const ReplaceAllMatchesCommand: ICommand = {
+ id: 'ui.command.replace-all-matches',
+ type: CommandType.COMMAND,
+ handler: async (accessor) => {
+ const confirmService = accessor.get(IConfirmService);
+ const localeService = accessor.get(LocaleService);
+ const messageService = accessor.get(IMessageService);
+
+ if (!await confirmService.confirm({
+ id: CONFIRM_REPLACE_ALL_ID,
+ title: { title: localeService.t('find-replace.replace.confirm.title') },
+ cancelText: localeService.t('button.cancel'),
+ confirmText: localeService.t('button.confirm'),
+ })) {
+ return false;
+ }
+
+ const findReplaceService = accessor.get(IFindReplaceService);
+ const result = await findReplaceService.replaceAll();
+ const { success, failure } = result;
+
+ if (failure > 0) {
+ if (success === 0) {
+ messageService.show({
+ type: MessageType.Error,
+ content: localeService.t('find-replace.replace.all-failure'),
+ });
+ } else {
+ messageService.show({
+ type: MessageType.Warning,
+ content: localeService.t('find-replace.replace.partial-success', `${success}`, `${failure}`),
+ });
+ }
+
+ return false;
+ }
+
+ messageService.show({
+ type: MessageType.Success,
+ content: localeService.t('find-replace.replace.all-success', `${success}`),
+ });
+
+ return true;
+ },
+};
diff --git a/packages/find-replace/src/commands/operations/find-replace.operation.ts b/packages/find-replace/src/commands/operations/find-replace.operation.ts
index 7e6d602dca..28e43f9efa 100644
--- a/packages/find-replace/src/commands/operations/find-replace.operation.ts
+++ b/packages/find-replace/src/commands/operations/find-replace.operation.ts
@@ -24,7 +24,12 @@ export const OpenFindDialogOperation: IOperation = {
type: CommandType.OPERATION,
handler: (accessor) => {
const findReplaceService = accessor.get(IFindReplaceService);
- findReplaceService.start();
+ if (!findReplaceService.revealed) {
+ findReplaceService.start();
+ } else {
+ findReplaceService.focusFindInput();
+ }
+
return true;
},
};
@@ -34,25 +39,14 @@ export const OpenReplaceDialogOperation: IOperation = {
type: CommandType.OPERATION,
handler: (accessor) => {
const findReplaceService = accessor.get(IFindReplaceService);
- findReplaceService.start();
- return true;
- },
-};
+ if (!findReplaceService.revealed) {
+ findReplaceService.start(true);
+ } else if (!findReplaceService.replaceRevealed) {
+ findReplaceService.revealReplace();
+ } else {
+ findReplaceService.focusFindInput();
+ }
-export const ToggleReplaceDialogOperation: IOperation = {
- id: 'ui.operation.toggle-replace-dialog',
- type: CommandType.OPERATION,
- handler: (accessor) => {
- const findReplaceService = accessor.get(IFindReplaceService);
- // findReplaceService.
- return true;
- },
-};
-
-export const CloseFindReplaceDialogOperation: IOperation = {
- id: 'ui.operation.close-find-replace-dialog',
- type: CommandType.OPERATION,
- handler: (accessor) => {
return true;
},
};
diff --git a/packages/find-replace/src/controllers/find-replace.controller.ts b/packages/find-replace/src/controllers/find-replace.controller.ts
index 22e9f986ca..6a37baed92 100644
--- a/packages/find-replace/src/controllers/find-replace.controller.ts
+++ b/packages/find-replace/src/controllers/find-replace.controller.ts
@@ -17,45 +17,57 @@
import {
ICommandService,
IContextService,
+ ILogService,
+ IUniverInstanceService,
LifecycleStages,
LocaleService,
OnLifecycle,
RxDisposable,
} from '@univerjs/core';
import { SearchSingle16 } from '@univerjs/icons';
-import { ComponentManager, IDialogService, ILayoutService, IMenuService, IShortcutService } from '@univerjs/ui';
+import {
+ ComponentManager,
+ IDialogService,
+ ILayoutService,
+ IMenuService,
+ IShortcutService,
+} from '@univerjs/ui';
import { Inject, Injector } from '@wendellhu/redi';
import { takeUntil } from 'rxjs';
import {
- CloseFindReplaceDialogOperation,
GoToNextMatchOperation,
GoToPreviousMatchOperation,
OpenFindDialogOperation,
OpenReplaceDialogOperation,
- ToggleReplaceDialogOperation,
} from '../commands/operations/find-replace.operation';
-import { FIND_REPLACE_ACTIVATED } from '../services/context-keys';
import { IFindReplaceService } from '../services/find-replace.service';
-import { FindReplaceDialog } from '../views/dialog/Dialog';
-import { FindReplaceMenuItemFactory } from './find-replace.menu';
+import { FindReplaceDialog } from '../views/dialog/FindReplaceDialog';
+import { ReplaceAllMatchesCommand, ReplaceCurrentMatchCommand } from '../commands/command/replace.command';
import {
- CloseFRDialogShortcutItem,
GoToNextFindMatchShortcutItem,
GoToPreviousFindMatchShortcutItem,
+ MacOpenFindDialogShortcutItem,
OpenFindDialogShortcutItem,
OpenReplaceDialogShortcutItem,
} from './find-replace.shortcut';
+import { FindReplaceMenuItemFactory } from './find-replace.menu';
const FIND_REPLACE_DIALOG_ID = 'DESKTOP_FIND_REPLACE_DIALOG';
+const FIND_REPLACE_PANEL_WIDTH = 350;
+const FIND_REPLACE_PANEL_RIGHT_PADDING = 20;
+const FIND_REPLACE_PANEL_TOP_PADDING = 0;
+
@OnLifecycle(LifecycleStages.Rendered, FindReplaceController)
export class FindReplaceController extends RxDisposable {
constructor(
+ @IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService,
@IMenuService private readonly _menuService: IMenuService,
@IShortcutService private readonly _shortcutService: IShortcutService,
@ICommandService private readonly _commandService: ICommandService,
@IFindReplaceService private readonly _findReplaceService: IFindReplaceService,
+ @ILogService private readonly _logService: ILogService,
@IDialogService private readonly _dialogService: IDialogService,
@IContextService private readonly _contextService: IContextService,
@ILayoutService private readonly _layoutService: ILayoutService,
@@ -65,29 +77,36 @@ export class FindReplaceController extends RxDisposable {
) {
super();
- this._initOperations();
+ this._initCommands();
this._initUI();
this._initShortcuts();
}
- private _initOperations(): void {
+ private _initCommands(): void {
[
- CloseFindReplaceDialogOperation,
OpenFindDialogOperation,
OpenReplaceDialogOperation,
- ToggleReplaceDialogOperation,
GoToNextMatchOperation,
GoToPreviousMatchOperation,
+ ReplaceAllMatchesCommand,
+ ReplaceCurrentMatchCommand,
].forEach((c) => {
this.disposeWithMe(this._commandService.registerCommand(c));
});
}
- private _initUI(): void {
- [FindReplaceMenuItemFactory].forEach((f) => {
- this.disposeWithMe(this._menuService.addMenuItem(this._injector.invoke(f)));
- });
+ private _initShortcuts(): void {
+ [
+ OpenReplaceDialogShortcutItem,
+ OpenFindDialogShortcutItem,
+ MacOpenFindDialogShortcutItem,
+ GoToPreviousFindMatchShortcutItem,
+ GoToNextFindMatchShortcutItem,
+ ].forEach((s) => this.disposeWithMe(this._shortcutService.registerShortcut(s)));
+ }
+ private _initUI(): void {
+ this.disposeWithMe(this._menuService.addMenuItem(this._injector.invoke(FindReplaceMenuItemFactory)));
this.disposeWithMe(this._componentManager.register('FindReplaceDialog', FindReplaceDialog));
this.disposeWithMe(this._componentManager.register('SearchIcon', SearchSingle16));
@@ -95,41 +114,44 @@ export class FindReplaceController extends RxDisposable {
this._findReplaceService.stateUpdates$.pipe(takeUntil(this.dispose$)).subscribe((newState) => {
if (newState.revealed === true) {
this._openPanel();
- } else if (newState.revealed === false) {
- this._closePanel();
}
});
- }
- private _initShortcuts(): void {
- [
- OpenReplaceDialogShortcutItem,
- OpenFindDialogShortcutItem,
- CloseFRDialogShortcutItem,
- GoToPreviousFindMatchShortcutItem,
- GoToNextFindMatchShortcutItem,
- ].forEach((s) => {
- this.disposeWithMe(this._shortcutService.registerShortcut(s));
- });
+ // If focusing on a non-sheet Univer document, close the find replace dialog.
+ this.disposeWithMe(
+ this._univerInstanceService.focused$.pipe(takeUntil(this.dispose$)).subscribe((focused) => {
+ if (!focused || !this._univerInstanceService.getUniverSheetInstance(focused)) {
+ this.closePanel();
+ }
+ })
+ );
}
private _openPanel(): void {
this._dialogService.open({
id: FIND_REPLACE_DIALOG_ID,
draggable: true,
- width: 350,
- title: { title: this._localeService.t('univer.find-replace.dialog.title') },
+ width: FIND_REPLACE_PANEL_WIDTH,
+ title: { title: this._localeService.t('find-replace.dialog.title') },
children: { label: 'FindReplaceDialog' },
- onClose: () => this._closePanel(),
+ destroyOnClose: true,
+ defaultPosition: getFindReplaceDialogDefaultPosition(),
+ onClose: () => this.closePanel(),
});
-
- this._contextService.setContextValue(FIND_REPLACE_ACTIVATED, true);
}
- private _closePanel(): void {
+ closePanel(): void {
this._dialogService.close(FIND_REPLACE_DIALOG_ID);
- this._contextService.setContextValue(FIND_REPLACE_ACTIVATED, false);
- this._layoutService.focus();
- this._findReplaceService.end();
+ this._findReplaceService.terminate();
+
+ queueMicrotask(() => this._layoutService.focus());
}
}
+
+function getFindReplaceDialogDefaultPosition(): { x: number; y: number } {
+ const { innerWidth } = window;
+ const x = innerWidth - FIND_REPLACE_PANEL_WIDTH - FIND_REPLACE_PANEL_RIGHT_PADDING;
+ const y = FIND_REPLACE_PANEL_TOP_PADDING;
+
+ return { x, y };
+}
diff --git a/packages/find-replace/src/controllers/find-replace.menu.ts b/packages/find-replace/src/controllers/find-replace.menu.ts
index 5da7c2d4af..4f8fe2ac3e 100644
--- a/packages/find-replace/src/controllers/find-replace.menu.ts
+++ b/packages/find-replace/src/controllers/find-replace.menu.ts
@@ -14,21 +14,28 @@
* limitations under the License.
*/
-import { UniverInstanceType } from '@univerjs/core';
+import { EDITOR_ACTIVATED, FOCUSING_SHEET, IContextService, UniverInstanceType } from '@univerjs/core';
import type { IMenuButtonItem } from '@univerjs/ui';
import { getMenuHiddenObservable, MenuGroup, MenuItemType, MenuPosition } from '@univerjs/ui';
import type { IAccessor } from '@wendellhu/redi';
+import { combineLatest, map } from 'rxjs';
import { OpenFindDialogOperation } from '../commands/operations/find-replace.operation';
export function FindReplaceMenuItemFactory(accessor: IAccessor): IMenuButtonItem {
+ const contextService = accessor.get(IContextService);
+
return {
id: OpenFindDialogOperation.id,
icon: 'SearchIcon',
- tooltip: 'toolbar.find-replace',
+ tooltip: 'find-replace.toolbar',
group: MenuGroup.TOOLBAR_OTHERS,
type: MenuItemType.BUTTON,
positions: [MenuPosition.TOOLBAR_START],
hidden$: getMenuHiddenObservable(accessor, UniverInstanceType.SHEET),
+ disabled$: combineLatest([
+ contextService.subscribeContextValue$(EDITOR_ACTIVATED),
+ contextService.subscribeContextValue$(FOCUSING_SHEET),
+ ]).pipe(map(([editorActivated, focusingSheet]) => editorActivated || !focusingSheet)),
};
}
diff --git a/packages/find-replace/src/controllers/find-replace.shortcut.ts b/packages/find-replace/src/controllers/find-replace.shortcut.ts
index 1a03730e50..799ae0fd2a 100644
--- a/packages/find-replace/src/controllers/find-replace.shortcut.ts
+++ b/packages/find-replace/src/controllers/find-replace.shortcut.ts
@@ -16,64 +16,87 @@
import { type IShortcutItem, KeyCode, MetaKeys } from '@univerjs/ui';
+import { EDITOR_ACTIVATED, FOCUSING_SHEET, type IContextService } from '@univerjs/core';
import {
- CloseFindReplaceDialogOperation,
GoToNextMatchOperation,
GoToPreviousMatchOperation,
OpenFindDialogOperation,
OpenReplaceDialogOperation,
} from '../commands/operations/find-replace.operation';
-import { FIND_REPLACE_ACTIVATED } from '../services/context-keys';
+import { FIND_REPLACE_DIALOG_FOCUS, FIND_REPLACE_INPUT_FOCUS, FIND_REPLACE_REPLACE_REVEALED } from '../services/context-keys';
+
+function whenFindReplaceDialogFocused(contextService: IContextService): boolean {
+ return contextService.getContextValue(FIND_REPLACE_DIALOG_FOCUS);
+}
+
+function whenReplaceRevealed(contextService: IContextService): boolean {
+ return contextService.getContextValue(FIND_REPLACE_REPLACE_REVEALED);
+}
+
+function whenFindReplaceInputFocused(contextService: IContextService): boolean {
+ return contextService.getContextValue(FIND_REPLACE_INPUT_FOCUS);
+}
+
+const FIND_REPLACE_SHORTCUT_GROUP = '7_find-replace-shortcuts';
+
+// Current we only support find replace on sheet.
+function whenSheetFocused(contextService: IContextService) {
+ return contextService.getContextValue(FOCUSING_SHEET);
+}
+
+function whenEditorNotActivated(contextService: IContextService): boolean {
+ return !contextService.getContextValue(EDITOR_ACTIVATED);
+}
export const OpenFindDialogShortcutItem: IShortcutItem = {
id: OpenFindDialogOperation.id,
- description: 'shortcut.find-replace.open-find-dialog',
+ description: 'find-replace.shortcut.open-find-dialog',
binding: KeyCode.F | MetaKeys.CTRL_COMMAND,
- group: '4_find-replace',
+ group: FIND_REPLACE_SHORTCUT_GROUP,
preconditions(contextService) {
- return !contextService.getContextValue(FIND_REPLACE_ACTIVATED);
+ return !whenFindReplaceDialogFocused(contextService) && whenSheetFocused(contextService) && whenEditorNotActivated(contextService);
},
};
-export const OpenReplaceDialogShortcutItem: IShortcutItem = {
- id: OpenReplaceDialogOperation.id,
- description: 'shortcut.find-replace.open-replace-dialog',
- binding: KeyCode.H | MetaKeys.CTRL_COMMAND,
- group: '4_find-replace',
+export const MacOpenFindDialogShortcutItem: IShortcutItem = {
+ id: OpenFindDialogOperation.id,
+ description: 'find-replace.shortcut.open-find-dialog',
+ binding: KeyCode.F | MetaKeys.CTRL_COMMAND,
+ mac: KeyCode.F | MetaKeys.MAC_CTRL,
preconditions(contextService) {
- return !contextService.getContextValue(FIND_REPLACE_ACTIVATED);
+ return !whenFindReplaceDialogFocused(contextService) && whenSheetFocused(contextService) && whenEditorNotActivated(contextService);
},
};
-export const CloseFRDialogShortcutItem: IShortcutItem = {
- id: CloseFindReplaceDialogOperation.id,
- description: 'shortcut.find-replace.close-dialog',
- binding: KeyCode.ESC,
- group: '4_find-replace',
- priority: 1000,
+export const OpenReplaceDialogShortcutItem: IShortcutItem = {
+ id: OpenReplaceDialogOperation.id,
+ description: 'find-replace.shortcut.open-replace-dialog',
+ binding: KeyCode.H | MetaKeys.CTRL_COMMAND,
+ mac: KeyCode.H | MetaKeys.MAC_CTRL,
+ group: FIND_REPLACE_SHORTCUT_GROUP,
preconditions(contextService) {
- return !!contextService.getContextValue(FIND_REPLACE_ACTIVATED);
+ return whenSheetFocused(contextService) && whenEditorNotActivated(contextService) && (!whenFindReplaceDialogFocused(contextService) || !whenReplaceRevealed(contextService));
},
};
export const GoToNextFindMatchShortcutItem: IShortcutItem = {
id: GoToNextMatchOperation.id,
- description: 'shortcut.find-replace.go-to-next-find-match',
+ description: 'find-replace.shortcut.go-to-next-match',
binding: KeyCode.ENTER,
- group: '4_find-replace',
+ group: FIND_REPLACE_SHORTCUT_GROUP,
priority: 1000,
preconditions(contextService) {
- return !!contextService.getContextValue(FIND_REPLACE_ACTIVATED);
+ return whenFindReplaceInputFocused(contextService) && whenFindReplaceDialogFocused(contextService);
},
};
export const GoToPreviousFindMatchShortcutItem: IShortcutItem = {
id: GoToPreviousMatchOperation.id,
- description: 'shortcut.find-replace.go-to-previous-find-match',
+ description: 'find-replace.shortcut.go-to-previous-match',
binding: KeyCode.ENTER | MetaKeys.SHIFT,
- group: '4_find-replace',
+ group: FIND_REPLACE_SHORTCUT_GROUP,
priority: 1000,
preconditions(contextService) {
- return !!contextService.getContextValue(FIND_REPLACE_ACTIVATED);
+ return whenFindReplaceInputFocused(contextService) && whenFindReplaceDialogFocused(contextService);
},
};
diff --git a/packages/find-replace/src/index.ts b/packages/find-replace/src/index.ts
index 4bc7cdb542..7dcac2f284 100644
--- a/packages/find-replace/src/index.ts
+++ b/packages/find-replace/src/index.ts
@@ -15,5 +15,13 @@
*/
export { UniverFindReplacePlugin } from './plugin';
-export type { IFindComplete, IFindMatch, IFindQuery, IFindReplaceProvider } from './services/find-replace.service';
-export { FindModel, IFindReplaceService } from './services/find-replace.service';
+export { FindReplaceController } from './controllers/find-replace.controller';
+export type {
+ IFindComplete,
+ IFindMoveParams,
+ IFindMatch,
+ IFindQuery,
+ IFindReplaceProvider,
+ IReplaceAllResult,
+} from './services/find-replace.service';
+export { FindModel, IFindReplaceService, FindBy, FindScope, FindDirection } from './services/find-replace.service';
diff --git a/packages/find-replace/src/locale/en-US.ts b/packages/find-replace/src/locale/en-US.ts
index b43a676775..e8d4c73287 100644
--- a/packages/find-replace/src/locale/en-US.ts
+++ b/packages/find-replace/src/locale/en-US.ts
@@ -14,23 +14,53 @@
* limitations under the License.
*/
-import type zhCN from './zh-CN';
-
-const locale: typeof zhCN = {
- univer: {
- 'find-replace': {
- dialog: {
- title: 'Find',
- find: 'Find',
- replace: 'Replace',
- 'replace-all': 'Replace All',
- 'find-range': 'Find Range',
- 'find-placeholder': 'Find in this Sheet',
- 'advanced-finding': 'Advanced Searching & Replace',
- 'replace-placeholder': 'Input Replace String',
+const locale = {
+ 'find-replace': {
+ toolbar: 'Find & Replace',
+ shortcut: {
+ 'open-find-dialog': 'Open Find Dialog',
+ 'open-replace-dialog': 'Open Replace Dialog',
+ 'close-dialog': 'Close Find & Replace Dialog',
+ 'go-to-next-match': 'Go to Next Match',
+ 'go-to-previous-match': 'Go to Previous Match',
+ },
+ dialog: {
+ title: 'Find',
+ find: 'Find',
+ replace: 'Replace',
+ 'replace-all': 'Replace All',
+ 'case-sensitive': 'Case Sensitive',
+ 'find-placeholder': 'Find in this Sheet',
+ 'advanced-finding': 'Advanced Searching & Replace',
+ 'replace-placeholder': 'Input Replace String',
+ 'match-the-whole-cell': 'Match the Whole Cell',
+ 'find-direction': {
+ title: 'Find Direction',
+ row: 'Search by Row',
+ column: 'Search by Column',
+ },
+ 'find-scope': {
+ title: 'Find Range',
+ 'current-sheet': 'Current Sheet',
+ workbook: 'Workbook',
+ },
+ 'find-by': {
+ title: 'Find By',
+ value: 'Find by Value',
+ formula: 'Find Formula',
+ },
+ 'no-match': 'Finding completed but no match found.',
+ 'no-result': 'No Result',
+ },
+ replace: {
+ 'all-success': 'Replaced all {0} matches',
+ 'all-failure': 'Replace failed',
+ confirm: {
+ title: 'Are you sure to replace all matches?',
},
},
},
+ 'find-replace-shortcuts': 'Find & Replace',
};
export default locale;
diff --git a/packages/find-replace/src/locale/zh-CN.ts b/packages/find-replace/src/locale/zh-CN.ts
index 43b0ac0104..edc55ad3d7 100644
--- a/packages/find-replace/src/locale/zh-CN.ts
+++ b/packages/find-replace/src/locale/zh-CN.ts
@@ -14,21 +14,55 @@
* limitations under the License.
*/
-const locale = {
- univer: {
- 'find-replace': {
- dialog: {
- title: '查找',
- find: '查找',
- replace: '替换',
- 'replace-all': '替换全部',
- 'find-range': '查找范围',
- 'find-placeholder': '输入查找内容',
- 'advanced-finding': '替换 / 高级查找',
- 'replace-placeholder': '输入替换内容',
+import type enUS from './en-US';
+
+const locale: typeof enUS = {
+ 'find-replace': {
+ toolbar: '查找替换',
+ shortcut: {
+ 'open-find-dialog': '打开查找对话框',
+ 'open-replace-dialog': '打开替换对话框',
+ 'close-dialog': '关闭查找替换对话框',
+ 'go-to-next-match': '下一个匹配项',
+ 'go-to-previous-match': '下一个匹配项',
+ },
+ dialog: {
+ title: '查找',
+ find: '查找',
+ replace: '替换',
+ 'replace-all': '替换全部',
+ 'find-placeholder': '输入查找内容',
+ 'advanced-finding': '替换 / 高级查找',
+ 'replace-placeholder': '输入替换内容',
+ 'case-sensitive': '匹配大小写',
+ 'match-the-whole-cell': '匹配整个单元格',
+ 'find-scope': {
+ title: '查找范围',
+ 'current-sheet': '当前子表',
+ workbook: '整个工作簿',
+ },
+ 'find-direction': {
+ title: '查找顺序',
+ column: '按列查找',
+ row: '按行查找',
+ },
+ 'find-by': {
+ title: '查找方式',
+ formula: '查找公式',
+ value: '查找值',
+ },
+ 'no-match': '已完成搜索,但是未找到任何匹配项',
+ 'no-result': '无结果',
+ },
+ replace: {
+ 'all-success': '已全部替换 {0} 个匹配项',
+ 'all-failure': '替换失败',
+ confirm: {
+ title: '确定要替换所有的匹配项吗?',
},
},
},
+ 'find-replace-shortcuts': '查找替换',
};
export default locale;
diff --git a/packages/find-replace/src/services/context-keys.ts b/packages/find-replace/src/services/context-keys.ts
index e85fdc318a..dcff95b570 100644
--- a/packages/find-replace/src/services/context-keys.ts
+++ b/packages/find-replace/src/services/context-keys.ts
@@ -14,7 +14,14 @@
* limitations under the License.
*/
+export const FIND_REPLACE_INPUT_FOCUS = 'FIND_REPLACE_INPUT_FOCUS';
+
+/**
+ * If find replace panel is focused.
+ */
+export const FIND_REPLACE_DIALOG_FOCUS = 'FIND_REPLACE_DIALOG_FOCUS';
+
/**
- * If find replace feature is activated.
+ * If the find replace feature is activated and the replace is revealed.
*/
-export const FIND_REPLACE_ACTIVATED = 'FIND_REPLACE_ACTIVATED';
+export const FIND_REPLACE_REPLACE_REVEALED = 'FIND_REPLACE_REPLACE_REVEALED';
diff --git a/packages/find-replace/src/services/find-replace.service.ts b/packages/find-replace/src/services/find-replace.service.ts
index 07ffdcc59f..c22aa62172 100644
--- a/packages/find-replace/src/services/find-replace.service.ts
+++ b/packages/find-replace/src/services/find-replace.service.ts
@@ -15,11 +15,13 @@
*/
import type { Nullable } from '@univerjs/core';
-import { Disposable, ILogService, IUniverInstanceService, toDisposable } from '@univerjs/core';
+import { Disposable, DisposableCollection, IContextService, ILogService, IUniverInstanceService, toDisposable } from '@univerjs/core';
+import { RENDER_RAW_FORMULA_KEY } from '@univerjs/engine-render';
import type { IDisposable } from '@wendellhu/redi';
import { createIdentifier, Inject, Injector } from '@wendellhu/redi';
import type { Observable } from 'rxjs';
-import { BehaviorSubject, Subject } from 'rxjs';
+import { BehaviorSubject, combineLatest, debounceTime, Subject, throttleTime } from 'rxjs';
+import { FIND_REPLACE_REPLACE_REVEALED } from './context-keys';
export type FindProgressFn = () => void;
@@ -31,15 +33,52 @@ export interface IFindMatch<T = unknown> {
provider: string;
unitId: string;
range: T;
+
+ /** Indicates if the match could be replaced. */
+ replaceable?: boolean;
+}
+
+export interface IFindMoveParams {
+ /** Go to next (previous) matching in a loop. */
+ loop?: boolean;
+
+ /** If the the selection is on the match and then should stay on the match. */
+ stayIfOnMatch?: boolean;
+
+ /**
+ * If this param is true, we should only change matching position without performing focusing.
+ * This usually happens when "moving" is triggered when a document's content changes.
+ */
+ noFocus?: boolean;
+}
+
+export interface IReplaceAllResult {
+ success: number;
+ failure: number;
}
export abstract class FindModel extends Disposable {
abstract readonly unitId: string;
+ /**
+ * Find model should emit new matches from this observable if they changed no matter due to incremental
+ * or document's content changes.
+ */
+ abstract readonly matchesUpdate$: Observable<IFindMatch[]>;
+ abstract readonly activelyChangingMatch$: Observable<IFindMatch>;
+
abstract getMatches(): IFindMatch[];
- abstract moveToNextMatch(loop?: boolean): IFindMatch | null;
- abstract moveToPreviousMatch(loop?: boolean): IFindMatch | null;
+ abstract moveToNextMatch(params?: IFindMoveParams): IFindMatch | null;
+ abstract moveToPreviousMatch(params?: IFindMoveParams): IFindMatch | null;
+
+ /** Replace the currently focused matching if there is one. */
+ abstract replace(replaceString: string): Promise<boolean>;
+
+ /**
+ * Replace all matches. This method would return how many
+ */
+ abstract replaceAll(replaceString: string): Promise<IReplaceAllResult>;
}
/**
@@ -47,9 +86,11 @@ export abstract class FindModel extends Disposable {
*/
export interface IFindReplaceProvider {
find(query: IFindQuery): Promise<FindModel[]>;
- cancel(): void;
+ terminate(): void;
}
+type IReplaceableMatch = IFindMatch & { replaceable: boolean };
+
/**
* This service works as a core of the find & replace feature.
*/
@@ -57,6 +98,15 @@ export interface IFindReplaceService {
readonly stateUpdates$: Observable<Partial<IFindReplaceState>>;
readonly state$: Observable<IFindReplaceState>;
+ readonly currentMatch$: Observable<Nullable<IFindMatch>>;
+ /** An observable value of all matches those could be replaced. */
+ readonly replaceables$: Observable<IReplaceableMatch[]>;
+
+ readonly focusSignal$: Observable<void>;
+
+ readonly revealed: boolean;
+ readonly replaceRevealed: boolean;
+
/**
* Register a find replace provider to the service. The provider is the actual bearer to
* perform the find in different kinds of documents or different environments.
@@ -65,195 +115,272 @@ export interface IFindReplaceService {
*/
registerFindReplaceProvider(provider: IFindReplaceProvider): IDisposable;
+ /**
+ * Get find string from the internal state.
+ */
+ getFindString(): string;
+
/**
* Start a find & replace session.
*
- * @returns if the find & replace session is created and user could start find replace
+ * @returns execution result
+ */
+ start(revealReplace?: boolean): boolean;
+
+ /**
+ * Terminate a find session and clear all caches.
*/
- start(): boolean;
+ terminate(): void;
- end(): boolean;
+ /**
+ * Start searching with the current conditions.
+ */
+ find(): void;
+
+ focusFindInput(): void;
revealReplace(): void;
changeFindString(value: string): void;
+ changeInputtingFindString(value: string): void;
+ changeReplaceString(value: string): void;
+ changeCaseSensitive(sensitive: boolean): void;
+ changeMatchesTheWholeCell(wholeCell: boolean): void;
+ changeFindScope(scope: FindScope): void;
+ changeFindDirection(direction: FindDirection): void;
+ changeFindBy(findBy: FindBy): void;
+
moveToNextMatch(): void;
moveToPreviousMatch(): void;
- replace(): boolean;
- replaceAll(): boolean;
-
- // /**
- // * Call this method to start find.
- // *
- // * @param query The query object.
- // * @param onProgress The callback function to report the progress.
- // */
- // find(query: IFindQuery, onProgress?: FindProgressFn): void;
+
+ replace(): Promise<boolean>;
+ replaceAll(): Promise<IReplaceAllResult>;
}
-export const IFindReplaceService = createIdentifier<IFindReplaceService>('univer.find-replace.service');
+export const IFindReplaceService = createIdentifier<IFindReplaceService>('find-replace.service');
/**
* The find query object with finding options.
*/
-export interface IFindQuery {
- text: string;
-
- isRegex?: boolean;
- ignoreCase?: boolean;
-
- /** Other possible options set by business. */
- [key: string]: boolean | string | number | undefined;
+export interface IFindQuery extends Pick<
+ IFindReplaceState,
+ | 'replaceRevealed'
+ | 'findString'
+ | 'caseSensitive'
+ | 'findBy'
+ | 'findDirection'
+ | 'findScope'
+ | 'matchesTheWholeCell'
+> { }
+
+function shouldStateUpdateTriggerResearch(statusUpdate: Partial<IFindReplaceState>): boolean {
+ if (typeof statusUpdate.findString !== 'undefined') return true;
+ if (typeof statusUpdate.inputtingFindString !== 'undefined') return true;
+ if (typeof statusUpdate.findDirection !== 'undefined') return true;
+ if (typeof statusUpdate.matchesTheWholeCell !== 'undefined') return true;
+ if (typeof statusUpdate.caseSensitive !== 'undefined') return true;
+ if (typeof statusUpdate.findScope !== 'undefined') return true;
+ if (typeof statusUpdate.findBy !== 'undefined') return true;
+ return false;
}
/**
- * This class stores find replace options state. These state are stored
- * here instead of the React component so we can change state from
- * operations.
+ * This class stores find replace results and provides methods to perform replace or something.
+ *
+ * It **only** live through a find-replace session and would be disposed when the user
+ * close the find replace dialog (considered as session being terminated).
*/
-export class FindReplaceState {
- private readonly _stateUpdates$ = new Subject<Partial<IFindReplaceState>>();
- readonly stateUpdates$: Observable<Partial<IFindReplaceState>> = this._stateUpdates$.asObservable();
+export class FindReplaceModel extends Disposable {
+ readonly currentMatch$ = new BehaviorSubject<Nullable<IFindMatch>>(null);
+ readonly replaceables$ = new BehaviorSubject<IReplaceableMatch[]>([]);
- private readonly _state$ = new BehaviorSubject<IFindReplaceState>(createInitFindReplaceState());
- readonly state$ = this._state$.asObservable();
- get state(): IFindReplaceState {
- return this._state$.getValue();
- }
+ /** All find models returned by providers. */
+ private _findModels: FindModel[] = [];
- // TODO@wzhudev: put all state properties here
- private _findString: string = '';
- private _revealed = false;
- private _replaceRevealed = false;
- private _matchesPosition = 0;
- private _matchesCount = 0;
+ /** The find model that the current match is from. */
+ private _matchingModel: FindModel | null = null;
+
+ private _matches: IFindMatch[] = [];
+
+ private _currentSearchingDisposables: Nullable<DisposableCollection> = null;
+
+ get searched(): boolean { return this._findModels.length > 0; }
+
+ constructor(
+ private readonly _state: FindReplaceState,
+ private readonly _providers: Set<IFindReplaceProvider>,
+ @IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService,
+ @ILogService private readonly _logService: ILogService
+ ) {
+ super();
- get findString(): string {
- return this._findString;
+ // should restart finding when the following conditions changed
+ this.disposeWithMe(
+ this._state.stateUpdates$.pipe(throttleTime(200, undefined, { leading: true, trailing: true }))
+ .subscribe(async (stateUpdate) => {
+ const state = this._state.state;
+ if (shouldStateUpdateTriggerResearch(stateUpdate)) {
+ if (state.findString !== '' && !state.replaceRevealed) {
+ await this._startSearching();
+ this._state.changeState({ findCompleted: true });
+ } else if (stateUpdate.replaceRevealed !== true) {
+ this._stopSearching();
+ }
+ }
+ }));
}
- changeState(changes: Partial<IFindReplaceState>): void {
- let changed = false;
- const changedState: Partial<IFindReplaceState> = {};
+ override dispose(): void {
+ super.dispose();
- if (typeof changes.findString !== 'undefined' && changes.findString !== this._findString) {
- this._findString = changes.findString;
- changedState.findString = this._findString;
- changed = true;
- }
+ this._stopSearching();
- if (typeof changes.revealed !== 'undefined' && changes.revealed !== this._revealed) {
- this._revealed = changes.revealed;
- changedState.revealed = changes.revealed;
- changed = true;
- }
+ this.currentMatch$.complete();
+ this.replaceables$.complete();
- if (typeof changes.replaceRevealed !== 'undefined' && changes.replaceRevealed !== this._replaceRevealed) {
- this._replaceRevealed = changes.replaceRevealed;
- changedState.replaceRevealed = changes.replaceRevealed;
- changed = true;
- }
+ // reset all state, including
+ this._state.changeState({ ...createInitFindReplaceState(), revealed: false });
+ }
- if (typeof changes.matchesCount !== 'undefined' && changes.matchesCount !== this._matchesCount) {
- this._matchesCount = changes.matchesCount;
- changedState.matchesCount = changes.matchesCount;
- changed = true;
+ async start(): Promise<IFindComplete> {
+ if (!this._state.findString) {
+ return { results: [] };
}
- if (typeof changes.matchesPosition !== 'undefined' && changes.matchesPosition !== this._matchesPosition) {
- this._matchesPosition = changes.matchesPosition;
- changedState.matchesPosition = changes.matchesPosition;
- changed = true;
- // TODO@wzhudev: maybe we should recalc matches position according to the current selections position
+ const complete = await this._startSearching();
+ this._state.changeState({ findCompleted: true });
+ return complete;
+ }
+
+ /** Call this method to start a `searching`. */
+ private async _startSearching(): Promise<IFindComplete> {
+ if (!this._state.findString) {
+ return { results: [] };
}
- if (changed) {
- this._stateUpdates$.next(changedState);
- this._state$.next({
- findString: this._findString,
- revealed: this._revealed,
- replaceRevealed: this._replaceRevealed,
- matchesCount: this._matchesCount,
- matchesPosition: this._matchesPosition,
- });
+ const providers = Array.from(this._providers);
+ const findModels = (this._findModels = (
+ await Promise.all(providers.map((provider) => provider.find({
+ findString: this._state.findString,
+ findDirection: this._state.findDirection,
+ findScope: this._state.findScope,
+ findBy: this._state.findBy,
+ replaceRevealed: this._state.replaceRevealed,
+ caseSensitive: this._state.caseSensitive,
+ matchesTheWholeCell: this._state.matchesTheWholeCell,
+ })))
+ ).flat());
+
+ this._subscribeToModelsChanges(findModels);
+
+ const newMatches = this._matches = findModels.map((c) => c.getMatches()).flat();
+ this.replaceables$.next(newMatches.filter((m) => m.replaceable) as IReplaceableMatch[]);
+
+ if (!newMatches.length) {
+ this._state.changeState({ matchesCount: 0, matchesPosition: 0 });
+ return { results: [] };
}
+
+ const index = this._moveToInitialMatch(findModels, newMatches);
+ this._state.changeState({
+ matchesCount: newMatches.length,
+ matchesPosition: index + 1, // the matches position start from 1
+ });
+ return { results: newMatches };
}
-}
-/**
- * This class stores find replace results and provides methods to perform replace or something.
- */
-export class FindReplaceModel extends Disposable {
- private _matchPositionFindModel?: Nullable<FindModel> = null;
- private _findModels: FindModel[] = [];
- private _matches: IFindMatch[] = [];
- private _positionModel: FindModel | null = null;
+ /** Terminate the current searching session, when searching string is empty. */
+ private _stopSearching(): void {
+ this._providers.forEach((provider) => provider.terminate());
+ this._findModels = [];
+ this._matches = [];
+ this._matchingModel = null;
- constructor(
- private readonly _state: FindReplaceState,
- private readonly _providers: Set<IFindReplaceProvider>,
- @ILogService private readonly _logService: ILogService,
- @IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService
- ) {
- super();
+ this._currentSearchingDisposables?.dispose();
+ this._currentSearchingDisposables = null;
+
+ this.currentMatch$.next(null);
+ this.replaceables$.next([]);
+
+ this._state.changeState({
+ findCompleted: false,
+ matchesCount: 0,
+ matchesPosition: 0,
+ });
+ }
- // Should restart finding when the following conditions changed
- this._state.stateUpdates$.subscribe((newState) => {
- if (typeof newState.findString !== 'undefined') {
- if (newState.findString) {
- this.find();
+ // When a document's content changes, we should reset all matches and try to move to the next match.
+ private _subscribeToModelsChanges(models: FindModel[]): void {
+ const disposables = this._currentSearchingDisposables = new DisposableCollection();
+
+ const matchesUpdateSubscription = combineLatest(models.map((model) => model.matchesUpdate$))
+ .pipe(debounceTime(220))
+ .subscribe(([...allMatches]) => {
+ const newMatches = this._matches = allMatches.flat();
+ if (newMatches.length) {
+ const index = this._moveToInitialMatch(this._findModels, newMatches, true);
+ this._state.changeState({ matchesCount: newMatches.length, matchesPosition: index + 1 });
+ this.replaceables$.next(newMatches.filter((m) => m.replaceable) as IReplaceableMatch[]);
} else {
- this._cancelFinding();
+ this._state.changeState({ matchesCount: 0, matchesPosition: 0 });
+ this.replaceables$.next([]);
}
- }
- });
+ });
+
+ models.forEach((model) => disposables.add(toDisposable(model.activelyChangingMatch$.subscribe((match) => {
+ const index = this._matches.findIndex((m) => m === match);
+ this._state.changeState({ matchesPosition: index + 1 });
+ }))));
+
+ disposables.add(toDisposable(matchesUpdateSubscription));
}
- async find(): Promise<IFindComplete> {
- this._cancelFinding();
+ async replace(): Promise<boolean> {
+ if (!this._matchingModel) {
+ return false;
+ }
- const providers = Array.from(this._providers);
- const findModels = (this._findModels = (
- await Promise.all(providers.map((provider) => provider.find({ text: this._state.findString })))
- ).flat());
+ return this._matchingModel.replace(this._state.replaceString);
+ }
- const matches = findModels.map((c) => c.getMatches()).flat();
- this._matches = matches;
+ async replaceAll(): Promise<IReplaceAllResult> {
+ const result = await Promise.all(this._findModels.map((m) => m.replaceAll(this._state.replaceString)))
+ .then((results) => results.reduce((acc, cur) => {
+ acc.success += cur.success;
+ acc.failure += cur.failure;
+ return acc;
+ }, { success: 0, failure: 0 }));
- if (!matches.length) {
- return {
- results: [],
- };
+ if (result.failure === 0) {
+ this._stopSearching();
}
- const index = this._moveToInitialMatch(findModels, matches);
- this._state.changeState({
- matchesCount: matches.length,
- matchesPosition: index + 1, // the matches position start from 1
- });
+ return result;
+ }
- return {
- results: matches,
- };
+ getCurrentMatch(): Nullable<IFindMatch> {
+ return this._state.matchesPosition > 0 ? this._matches[this._state.matchesPosition - 1] : null;
}
moveToNextMatch(): void {
- if (!this._positionModel) {
+ if (!this._matchingModel) {
return;
}
const loopInCurrentUnit = this._findModels.length === 1;
- const nextMatch = this._positionModel.moveToNextMatch(loopInCurrentUnit);
+ const nextMatch = this._matchingModel.moveToNextMatch({ loop: loopInCurrentUnit });
if (nextMatch) {
const index = this._matches.findIndex((value) => value === nextMatch);
+ this.currentMatch$.next(nextMatch);
this._state.changeState({
matchesPosition: index + 1,
});
} else {
// search in the next find model
- const indexOfPositionModel = this._findModels.findIndex((m) => m === this._positionModel);
+ const indexOfPositionModel = this._findModels.findIndex((m) => m === this._matchingModel);
const nextPositionModel = this._findModels[(indexOfPositionModel + 1) % this._findModels.length]; // TODO: always loop or not
const nextMatch = nextPositionModel.moveToNextMatch();
const index = this._matches.findIndex((value) => value === nextMatch);
- this._positionModel = nextPositionModel;
+ this.currentMatch$.next(nextMatch);
+ this._matchingModel = nextPositionModel;
this._state.changeState({
matchesPosition: index + 1,
});
@@ -261,33 +388,33 @@ export class FindReplaceModel extends Disposable {
}
moveToPreviousMatch(): void {
- if (!this._positionModel) {
+ if (!this._matchingModel) {
return;
}
const loopInCurrentUnit = this._findModels.length === 1;
- const nextMatch = this._positionModel.moveToPreviousMatch(loopInCurrentUnit);
+ const nextMatch = this._matchingModel.moveToPreviousMatch({ loop: loopInCurrentUnit });
if (nextMatch) {
const index = this._matches.findIndex((value) => value === nextMatch);
+ this.currentMatch$.next(nextMatch);
this._state.changeState({
matchesPosition: index + 1,
});
} else {
- const indexOfPositionModel = this._findModels.findIndex((m) => m === this._positionModel);
+ const indexOfPositionModel = this._findModels.findIndex((m) => m === this._matchingModel);
const nextPositionModel =
this._findModels[(indexOfPositionModel - 1 + this._findModels.length) % this._findModels.length];
const nextMatch = nextPositionModel.moveToPreviousMatch();
const index = this._matches.findIndex((value) => value === nextMatch);
- this._positionModel = nextPositionModel;
+ this.currentMatch$.next(nextMatch);
+ this._matchingModel = nextPositionModel;
this._state.changeState({
matchesPosition: index + 1,
});
}
}
- // TODO@wzhudev: some cold could definitely be reused. Reuse them.
-
- private _moveToInitialMatch(findModels: FindModel[], results: IFindMatch[]): number {
+ private _moveToInitialMatch(findModels: FindModel[], results: IFindMatch[], noFocus = false): number {
const focusedUnitId = this._univerInstanceService.getFocusedUniverInstance()?.getUnitId();
if (!focusedUnitId) {
return -1;
@@ -295,26 +422,38 @@ export class FindReplaceModel extends Disposable {
const findModelOnFocusUnit = findModels.find((model) => model.unitId === focusedUnitId);
if (findModelOnFocusUnit) {
- this._positionModel = findModelOnFocusUnit;
- const result = findModelOnFocusUnit.moveToNextMatch();
- const index = results.findIndex((value) => value === result);
+ this._matchingModel = findModelOnFocusUnit;
+ const nextMatch = findModelOnFocusUnit.moveToNextMatch({ stayIfOnMatch: true, noFocus });
+ const index = results.findIndex((value) => value === nextMatch);
+ this.currentMatch$.next(nextMatch);
return index;
}
// otherwise we just simply match the first result
- this._positionModel = findModels[0];
- const nextMatch = this._positionModel.moveToNextMatch();
+ this._matchingModel = findModels[0];
+ const nextMatch = this._matchingModel.moveToNextMatch({ noFocus });
const matchPosition = this._matches.findIndex((m) => m === nextMatch);
+ this.currentMatch$.next(nextMatch);
return matchPosition;
}
+}
- private _cancelFinding(): void {
- this._providers.forEach((provider) => provider.cancel());
- this._state.changeState({
- matchesCount: 0,
- matchesPosition: 0,
- });
- }
+export enum FindDirection {
+ /** Default. */
+ ROW = 'row',
+ COLUMN = 'column',
+}
+
+export enum FindBy {
+ VALUE = 'value',
+ FORMULA = 'formula',
+}
+
+export enum FindScope {
+ /** Default. */
+ SUBUNIT = 'subunit',
+ /** Find the scope in the current unit. */
+ UNIT = 'unit',
}
export interface IFindReplaceState {
@@ -322,6 +461,7 @@ export interface IFindReplaceState {
/** The string user inputs in the input box. */
findString: string;
+ inputtingFindString: string;
replaceString?: string;
/** Indicates if is in replacing mode. */
@@ -329,19 +469,183 @@ export interface IFindReplaceState {
/** The currently focused match's index (1-based). */
matchesPosition: number;
+ /** The number of all matches. */
matchesCount: number;
+
+ /** Indicates if an user triggered finding process is progressed. */
+ findCompleted: boolean;
+
+ caseSensitive: boolean;
+ matchesTheWholeCell: boolean;
+ findDirection: FindDirection;
+ findScope: FindScope;
+ findBy: FindBy;
}
function createInitFindReplaceState(): IFindReplaceState {
return {
- revealed: true,
+ caseSensitive: false,
+ findBy: FindBy.VALUE,
+ findCompleted: false,
+ findDirection: FindDirection.ROW,
+ findScope: FindScope.SUBUNIT,
findString: '',
- replaceRevealed: false,
- matchesPosition: 0,
+ inputtingFindString: '',
matchesCount: 0,
+ matchesPosition: 0,
+ matchesTheWholeCell: false,
+ replaceRevealed: false,
+ replaceString: '',
+ revealed: true,
};
}
+/**
+ * This class stores find replace options state. These state are stored
+ * here instead of the React component so we can change state from
+ * operations.
+ */
+export class FindReplaceState {
+ private readonly _stateUpdates$ = new Subject<Partial<IFindReplaceState>>();
+ readonly stateUpdates$: Observable<Partial<IFindReplaceState>> = this._stateUpdates$.asObservable();
+
+ private readonly _state$ = new BehaviorSubject<IFindReplaceState>(createInitFindReplaceState());
+ readonly state$ = this._state$.asObservable();
+ get state(): IFindReplaceState {
+ return this._state$.getValue();
+ }
+
+ private _findString = '';
+ private _inputtingFindString = '';
+ private _replaceString = '';
+ private _revealed = false;
+ private _replaceRevealed = false;
+ private _matchesPosition = 0;
+ private _matchesCount = 0;
+ private _caseSensitive = true;
+ private _matchesTheWholeCell = false;
+ private _findDirection = FindDirection.ROW;
+ private _findScope = FindScope.SUBUNIT;
+ private _findBy = FindBy.VALUE;
+ private _findCompleted = false;
+
+ get inputtingFindString(): string { return this._inputtingFindString; }
+ get findString(): string { return this._findString; }
+ get revealed(): boolean { return this._revealed; }
+ get replaceRevealed(): boolean { return this._replaceRevealed; }
+ get matchesPosition(): number { return this._matchesPosition; }
+ get matchesCount(): number { return this._matchesCount; }
+ get replaceString(): string { return this._replaceString; }
+ get caseSensitive(): boolean { return this._caseSensitive; }
+ get matchesTheWholeCell(): boolean { return this._matchesTheWholeCell; }
+ get findDirection(): FindDirection { return this._findDirection; }
+ get findScope(): FindScope { return this._findScope; }
+ get findBy(): FindBy { return this._findBy; }
+ get findCompleted(): boolean { return this._findCompleted; }
+
+ changeState(changes: Partial<IFindReplaceState>): void {
+ let changed = false;
+ const changedState: Partial<IFindReplaceState> = {};
+
+ if (typeof changes.findString !== 'undefined' && changes.findString !== this._findString) {
+ this._findString = changes.findString;
+ changedState.findString = this._findString;
+ changed = true;
+ }
+
+ if (typeof changes.revealed !== 'undefined' && changes.revealed !== this._revealed) {
+ this._revealed = changes.revealed;
+ changedState.revealed = changes.revealed;
+ changed = true;
+ }
+
+ if (typeof changes.replaceRevealed !== 'undefined' && changes.replaceRevealed !== this._replaceRevealed) {
+ this._replaceRevealed = changes.replaceRevealed;
+ changedState.replaceRevealed = changes.replaceRevealed;
+ changed = true;
+ }
+
+ if (typeof changes.replaceString !== 'undefined' && changes.replaceString !== this._replaceString) {
+ this._replaceString = changes.replaceString;
+ changedState.replaceString = changes.replaceString;
+ changed = true;
+ }
+
+ if (typeof changes.matchesCount !== 'undefined' && changes.matchesCount !== this._matchesCount) {
+ this._matchesCount = changes.matchesCount;
+ changedState.matchesCount = changes.matchesCount;
+ changed = true;
+ }
+
+ if (typeof changes.matchesPosition !== 'undefined' && changes.matchesPosition !== this._matchesPosition) {
+ this._matchesPosition = changes.matchesPosition;
+ changedState.matchesPosition = changes.matchesPosition;
+ changed = true;
+ }
+
+ if (typeof changes.findBy !== 'undefined' && changes.findBy !== this._findBy) {
+ this._findBy = changes.findBy;
+ changedState.findBy = changes.findBy;
+ changed = true;
+ }
+
+ if (typeof changes.findScope !== 'undefined' && changes.findScope !== this._findScope) {
+ this._findScope = changes.findScope;
+ changedState.findScope = changes.findScope;
+ changed = true;
+ }
+
+ if (typeof changes.findDirection !== 'undefined' && changes.findDirection !== this._findDirection) {
+ this._findDirection = changes.findDirection;
+ changedState.findDirection = changes.findDirection;
+ changed = true;
+ }
+
+ if (typeof changes.caseSensitive !== 'undefined' && changes.caseSensitive !== this._caseSensitive) {
+ this._caseSensitive = changes.caseSensitive;
+ changedState.caseSensitive = changes.caseSensitive;
+ changed = true;
+ }
+
+ if (typeof changes.matchesTheWholeCell !== 'undefined' && changes.matchesTheWholeCell !== this._matchesTheWholeCell) {
+ this._matchesTheWholeCell = changes.matchesTheWholeCell;
+ changedState.matchesTheWholeCell = changes.matchesTheWholeCell;
+ changed = true;
+ }
+
+ if (typeof changes.inputtingFindString !== 'undefined' && changes.inputtingFindString !== this._inputtingFindString) {
+ this._inputtingFindString = changes.inputtingFindString;
+ changedState.inputtingFindString = changes.inputtingFindString;
+ changed = true;
+ }
+
+ if (typeof changes.findCompleted !== 'undefined' && changes.findCompleted !== this._findCompleted) {
+ this._findCompleted = changes.findCompleted;
+ changedState.findCompleted = changes.findCompleted;
+ changed = true;
+ }
+
+ if (changed) {
+ this._state$.next({
+ caseSensitive: this._caseSensitive,
+ findBy: this._findBy,
+ findCompleted: this._findCompleted,
+ findDirection: this._findDirection,
+ findScope: this._findScope,
+ findString: this._findString,
+ inputtingFindString: this._inputtingFindString,
+ matchesCount: this._matchesCount,
+ matchesPosition: this._matchesPosition,
+ matchesTheWholeCell: this._matchesTheWholeCell,
+ replaceRevealed: this._replaceRevealed,
+ revealed: this._revealed,
+ });
+
+ this._stateUpdates$.next(changedState);
+ }
+ }
+}
+
// Since Univer' Find&Replace features works in a plugin manner,
// each `IFind&Replace` provider should have their own implementations
// of 'state' and 'model'.
@@ -351,79 +655,177 @@ export class FindReplaceService extends Disposable implements IFindReplaceServic
private readonly _state = new FindReplaceState();
private _model: Nullable<FindReplaceModel>;
- get stateUpdates$() {
- return this._state.stateUpdates$;
+ private readonly _currentMatch$ = new BehaviorSubject<Nullable<IFindMatch>>(null);
+ readonly currentMatch$ = this._currentMatch$.asObservable();
+
+ private readonly _replaceables$ = new BehaviorSubject<IReplaceableMatch[]>([]);
+ readonly replaceables$ = this._replaceables$.asObservable();
+
+ private readonly _focusSignal$ = new Subject<void>();
+ readonly focusSignal$ = this._focusSignal$.asObservable();
+
+ get stateUpdates$() { return this._state.stateUpdates$; }
+ get state$() { return this._state.state$; }
+ get revealed(): boolean { return this._state.revealed; }
+ get replaceRevealed(): boolean { return this._state.replaceRevealed; }
+
+ constructor(@Inject(Injector) private readonly _injector: Injector, @IContextService private readonly _contextService: IContextService) {
+ super();
}
- get state$() {
- return this._state.state$;
+ override dispose(): void {
+ super.dispose();
+
+ this._currentMatch$.next(null);
+ this._currentMatch$.complete();
+
+ this._replaceables$.next([]);
+ this._replaceables$.complete();
+
+ this._focusSignal$.complete();
}
- constructor(
- @Inject(Injector) private readonly _injector: Injector,
- @IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService,
- @ILogService private readonly _logService: ILogService
- ) {
- super();
+ getCurrentMatch(): Nullable<IFindMatch> {
+ return this._model?.getCurrentMatch();
}
- changeFindString(value: string): void {
- this._state.changeState({
- findString: value,
- });
+ getFindString(): string {
+ return this._state.findString;
+ }
+
+ changeFindString(findString: string): void {
+ this._state.changeState({ findString });
+ }
+
+ focusFindInput(): void {
+ this._focusSignal$.next();
+ }
+
+ changeInputtingFindString(value: string): void {
+ if (value) {
+ this._state.changeState({ inputtingFindString: value });
+ } else {
+ this._state.changeState({ inputtingFindString: '', findString: '' });
+ }
+ }
+
+ changeReplaceString(replaceString: string): void {
+ this._state.changeState({ replaceString });
+ }
+
+ changeMatchesTheWholeCell(matchesTheWholeCell: boolean): void {
+ this._state.changeState({ matchesTheWholeCell });
+ }
+
+ changeCaseSensitive(caseSensitive: boolean): void {
+ this._state.changeState({ caseSensitive });
+ }
+
+ changeFindBy(findBy: FindBy): void {
+ this._state.changeState({ findBy });
+ this._toggleDisplayRawFormula(findBy === FindBy.FORMULA);
+ }
+
+ changeFindScope(scope: FindScope): void {
+ this._state.changeState({ findScope: scope });
+ }
+
+ changeFindDirection(direction: FindDirection): void {
+ this._state.changeState({ findDirection: direction });
}
moveToNextMatch(): void {
- if (this._model) {
- this._model?.moveToNextMatch();
+ if (!this._model) {
+ return;
+ }
+
+ if (this._state.replaceRevealed && !this._model.searched) {
+ this._state.changeState({ findString: this._state.inputtingFindString });
+ this._model.start();
+ } else {
+ this._model.moveToNextMatch();
}
+
+ this._focusSignal$.next();
}
moveToPreviousMatch(): void {
- if (this._model) {
- this._model?.moveToPreviousMatch();
+ if (!this._model) {
+ return;
}
- }
- replace(): boolean {
- return true;
+ if (this._state.replaceRevealed && !this._model.searched) {
+ this._state.changeState({ findString: this._state.inputtingFindString });
+ this._model.start();
+ } else {
+ this._model.moveToPreviousMatch();
+ }
+
+ this._focusSignal$.next();
}
- replaceAll(): boolean {
- return true;
+ async replace(): Promise<boolean> {
+ if (!this._model) {
+ return false;
+ }
+
+ return this._model.replace();
}
- revealReplace(): void {
- this._state.changeState({ replaceRevealed: true });
+ async replaceAll(): Promise<IReplaceAllResult> {
+ if (!this._model) {
+ throw new Error('[FindReplaceService] replaceAll: model is not initialized!');
+ }
+
+ return this._model.replaceAll();
}
- disposeModel(): void {
- this._model?.dispose();
- this._model = null;
+ revealReplace(): void {
+ this._state.changeState({ replaceRevealed: true, inputtingFindString: this._state.findString });
+ this._toggleRevealReplace(true);
}
- start(): boolean {
+ start(revealReplace = false): boolean {
if (this._providers.size === 0) {
return false;
}
this._model = this._injector.createInstance(FindReplaceModel, this._state, this._providers);
+ this._model.currentMatch$.subscribe((match) => this._currentMatch$.next(match));
+ this._model.replaceables$.subscribe((replaceables) => this._replaceables$.next(replaceables));
const newState = createInitFindReplaceState();
- newState.revealed = true;
+ if (revealReplace) {
+ newState.replaceRevealed = true;
+ }
this._state.changeState(newState);
-
+ this._toggleRevealReplace(revealReplace);
return true;
}
- end(): boolean {
- this._state.changeState({ revealed: false, replaceRevealed: false });
- return true;
+ find(): void {
+ this._model?.start();
+ }
+
+ terminate(): void {
+ this._model?.dispose();
+ this._model = null;
+
+ this._toggleDisplayRawFormula(false);
+ this._toggleRevealReplace(false);
}
registerFindReplaceProvider(provider: IFindReplaceProvider): IDisposable {
this._providers.add(provider);
return toDisposable(() => this._providers.delete(provider));
}
+
+ private _toggleRevealReplace(revealReplace: boolean): void {
+ this._contextService.setContextValue(FIND_REPLACE_REPLACE_REVEALED, revealReplace);
+ }
+
+ private _toggleDisplayRawFormula(force: boolean): void {
+ this._contextService.setContextValue(RENDER_RAW_FORMULA_KEY, force);
+ }
}
diff --git a/packages/find-replace/src/views/dialog/Dialog.module.less b/packages/find-replace/src/views/dialog/Dialog.module.less
deleted file mode 100644
index 7623534473..0000000000
--- a/packages/find-replace/src/views/dialog/Dialog.module.less
+++ /dev/null
@@ -1,9 +0,0 @@
-.find-replace {
- // &-dialog-container {
- // }
-
- &-expand-container {
- margin-top: 16px;
- text-align: center;
- }
-}
diff --git a/packages/find-replace/src/views/dialog/Dialog.tsx b/packages/find-replace/src/views/dialog/Dialog.tsx
deleted file mode 100644
index 8e4e14464a..0000000000
--- a/packages/find-replace/src/views/dialog/Dialog.tsx
+++ /dev/null
@@ -1,149 +0,0 @@
-/**
- * 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 { LocaleService } from '@univerjs/core';
-import { Button, FormLayout, Input, InputWithSlot, Pager, Select } from '@univerjs/design';
-import { ILayoutService, useObservable } from '@univerjs/ui';
-import type { IDisposable } from '@wendellhu/redi';
-import { useDependency } from '@wendellhu/redi/react-bindings';
-import React, { Fragment, useCallback, useEffect, useRef, useState } from 'react';
-
-import { IFindReplaceService } from '../../services/find-replace.service';
-import styles from './Dialog.module.less';
-
-const FIND_THROTTLE_TIME = 500;
-
-export function FindReplaceDialog() {
- const findReplaceService = useDependency(IFindReplaceService);
- const localeService = useDependency(LocaleService);
- const layoutService = useDependency(ILayoutService);
-
- const [findString, setFindString] = useState<string>('');
- const [replaceString, setReplaceString] = useState<string>('');
-
- const dialogContainerRef = useRef<HTMLDivElement>(null);
-
- const state = useObservable(findReplaceService.state$, undefined, true);
- const { matchesCount, matchesPosition } = state;
- const revealReplace = useCallback(() => findReplaceService.revealReplace(), [findReplaceService]);
-
- const updateFindString = useCallback(
- (findString: string) => findReplaceService.changeFindString(findString),
- // FIXME@wzhudev: this throttle function has no leading and taling config hence has some problems
- // throttle((findString: string) => findReplaceService.changeFindString(findString), FIND_THROTTLE_TIME),
- [findReplaceService]
- );
-
- const onFindInputChange = useCallback(
- (findString: string) => {
- setFindString(findString);
- updateFindString(findString);
- },
- [findReplaceService]
- );
-
- const onReplaceInputChange = useCallback(
- (replaceString: string) => {
- setReplaceString(replaceString);
- },
- [findReplaceService]
- );
-
- useEffect(() => {
- let disposable: IDisposable | undefined;
- if (dialogContainerRef.current) {
- disposable = layoutService.registerContainerElement(dialogContainerRef.current);
- }
-
- return () => disposable?.dispose();
- }, [dialogContainerRef.current]);
-
- function renderFindDialog() {
- return (
- <Fragment>
- <InputWithSlot
- autoFocus={true}
- placeholder={localeService.t('univer.find-replace.dialog.find-placeholder')}
- slot={(
- <Pager
- loop={true}
- value={matchesPosition}
- total={matchesCount}
- onChange={(newIndex) => {
- if (matchesPosition === matchesCount && newIndex === 1) {
- findReplaceService.moveToNextMatch();
- } else if (matchesPosition === 1 && newIndex === matchesCount) {
- findReplaceService.moveToPreviousMatch();
- } else if (newIndex < matchesPosition) {
- findReplaceService.moveToPreviousMatch();
- } else {
- findReplaceService.moveToNextMatch();
- }
- }}
- />
- )}
- value={findString}
- onChange={(value) => onFindInputChange(value)}
- />
-
- <div className={styles.findReplaceExpandContainer}>
- <Button type="text" size="small" onClick={revealReplace}>
- {localeService.t('univer.find-replace.dialog.advanced-finding')}
- </Button>
- </div>
- </Fragment>
- );
- }
-
- function renderReplaceDialog() {
- /*
- * TODO@wzhudev: this form should be configure by business (maybe with a schema?) Here we just
- * simply hard coded them here for a quick implementation.
- */
-
- return (
- <Fragment>
- <FormLayout label={localeService.t('univer.find-replace.dialog.find')}>
- <Input
- placeholder={localeService.t('univer.find-replace.dialog.find-placeholder')}
- autoFocus={true}
- value={findString}
- onChange={(value) => onReplaceInputChange(value)}
- />
- </FormLayout>
- <FormLayout label={localeService.t('univer.find-replace.dialog.replace')}>
- <Input
- placeholder={localeService.t('univer.find-replace.dialog.replace-placeholder')}
- value={replaceString}
- onChange={(value) => onReplaceInputChange(value)}
- />
- </FormLayout>
- <FormLayout label={localeService.t('univer.find-replace.dialog.find-range')}>
- <Select value="123" onChange={() => {}} />
- </FormLayout>
- <Button type="primary">{localeService.t('univer.find-replace.dialog.find')}</Button>
- <Button>{localeService.t('univer.find-replace.dialog.replace')}</Button>
- <Button>{localeService.t('univer.find-replace.dialog.replace-all')}</Button>
- </Fragment>
- );
- }
-
- return (
- <div className={styles.findReplaceDialogContainer} ref={dialogContainerRef}>
- {!state.replaceRevealed ? renderFindDialog() : renderReplaceDialog()}
- </div>
- );
-}
diff --git a/packages/find-replace/src/views/dialog/FindReplaceDialog.module.less b/packages/find-replace/src/views/dialog/FindReplaceDialog.module.less
new file mode 100644
index 0000000000..9ad086d5ba
--- /dev/null
+++ b/packages/find-replace/src/views/dialog/FindReplaceDialog.module.less
@@ -0,0 +1,28 @@
+.find-replace {
+ &-dialog-container {
+ display: block;
+ }
+
+ &-expand-container {
+ margin-top: 16px;
+ text-align: center;
+
+ .button-text {
+ color: rgb(var(--primary-color));
+ }
+ }
+
+ &-buttons-group {
+ display: flex;
+ justify-content: space-between;
+ margin-top: 24px;
+
+ &-right {
+ > button {
+ &:not(:first-child) {
+ margin-left: 8px;
+ }
+ }
+ }
+ }
+}
diff --git a/packages/find-replace/src/views/dialog/Dialog.stories.tsx b/packages/find-replace/src/views/dialog/FindReplaceDialog.stories.tsx
similarity index 98%
rename from packages/find-replace/src/views/dialog/Dialog.stories.tsx
rename to packages/find-replace/src/views/dialog/FindReplaceDialog.stories.tsx
index 9bee95a9c4..f78b2880f6 100644
--- a/packages/find-replace/src/views/dialog/Dialog.stories.tsx
+++ b/packages/find-replace/src/views/dialog/FindReplaceDialog.stories.tsx
@@ -24,7 +24,7 @@ import { LocaleService, LocaleType } from '@univerjs/core';
import { FindReplaceService, IFindReplaceService } from '../../services/find-replace.service';
import { FindReplaceController } from '../../controllers/find-replace.controller';
import { enUS, zhCN } from '../../locale';
-import { FindReplaceDialog } from './Dialog';
+import { FindReplaceDialog } from './FindReplaceDialog';
const meta: Meta = {
title: 'Find Replace Dialog',
diff --git a/packages/find-replace/src/views/dialog/FindReplaceDialog.tsx b/packages/find-replace/src/views/dialog/FindReplaceDialog.tsx
new file mode 100644
index 0000000000..fe6ca00870
--- /dev/null
+++ b/packages/find-replace/src/views/dialog/FindReplaceDialog.tsx
@@ -0,0 +1,345 @@
+/**
+ * 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 { Button, Checkbox, FormDualColumnLayout, FormLayout, Input, MessageType, Select } from '@univerjs/design';
+import { ILayoutService, IMessageService, useObservable } from '@univerjs/ui';
+import type { Nullable } from '@univerjs/core';
+import { ICommandService, IContextService, LocaleService } from '@univerjs/core';
+import type { IDisposable } from '@wendellhu/redi';
+import { useDependency } from '@wendellhu/redi/react-bindings';
+import type { ForwardedRef } from 'react';
+import React, { forwardRef, Fragment, useCallback, useEffect, useImperativeHandle, useMemo, useRef } from 'react';
+import { fromEvent } from 'rxjs';
+
+import { FindBy, FindDirection, FindScope, IFindReplaceService } from '../../services/find-replace.service';
+import { FIND_REPLACE_DIALOG_FOCUS, FIND_REPLACE_INPUT_FOCUS } from '../../services/context-keys';
+import { ReplaceAllMatchesCommand, ReplaceCurrentMatchCommand } from '../../commands/command/replace.command';
+import { OpenReplaceDialogOperation } from '../../commands/operations/find-replace.operation';
+import { SearchInput } from './SearchInput';
+
+import styles from './FindReplaceDialog.module.less';
+
+interface ISubFormRef {
+ focus(): void;
+ selectHasFocus(): boolean;
+}
+
+function useFindInputFocus(findReplaceService: IFindReplaceService, ref: ForwardedRef<unknown>) {
+ const focus = useCallback(() => {
+ (document.querySelector('.univer-find-input input') as Nullable<HTMLInputElement>)?.focus();
+ }, []);
+
+ const selectHasFocus = useCallback(() => {
+ const allInputs = document.querySelectorAll('.univer-find-replace-dialog-container .univer-select-selection-search-input');
+ return Array.from(allInputs).some((input) => input === document.activeElement);
+ }, []);
+
+ useImperativeHandle(ref, () => ({ focus, selectHasFocus }));
+
+ useEffect(() => {
+ const subscription = findReplaceService.focusSignal$.subscribe(() => focus());
+ return () => subscription.unsubscribe();
+ }, [findReplaceService, focus]);
+
+ return { focus, selectHasFocus };
+}
+
+export const FindDialog = forwardRef(function FindDialogImpl(_props, ref) {
+ const localeService = useDependency(LocaleService);
+ const findReplaceService = useDependency(IFindReplaceService);
+ const commandService = useDependency(ICommandService);
+
+ const state = useObservable(findReplaceService.state$, undefined, true);
+ const { findCompleted, findString, matchesCount, matchesPosition } = state;
+
+ const revealReplace = useCallback(() => {
+ commandService.executeCommand(OpenReplaceDialogOperation.id);
+ }, [commandService]);
+
+ const onFindStringChange = useCallback((findString: string) => findReplaceService.changeFindString(findString), [findReplaceService]);
+
+ useFindInputFocus(findReplaceService, ref);
+
+ return (
+ <Fragment>
+ <SearchInput
+ findCompleted={findCompleted}
+ className="univer-find-input"
+ matchesCount={matchesCount}
+ matchesPosition={matchesPosition}
+ findReplaceService={findReplaceService}
+ localeService={localeService}
+ findString={findString}
+ onChange={onFindStringChange}
+ />
+ <div className={styles.findReplaceExpandContainer}>
+ <Button type="text" size="small" onClick={revealReplace}>
+ {localeService.t('find-replace.dialog.advanced-finding')}
+ </Button>
+ </div>
+ </Fragment>
+ );
+});
+
+export const ReplaceDialog = forwardRef(function ReplaceDIalogImpl(_props, ref) {
+ const findReplaceService = useDependency(IFindReplaceService);
+ const localeService = useDependency(LocaleService);
+ const commandService = useDependency(ICommandService);
+ const messageService = useDependency(IMessageService);
+
+ const currentMatch = useObservable(findReplaceService.currentMatch$, undefined, true);
+ const replaceables = useObservable(findReplaceService.replaceables$, undefined, true);
+ const state = useObservable(findReplaceService.state$, undefined, true);
+ const {
+ matchesCount,
+ matchesPosition,
+ findString,
+ inputtingFindString,
+ replaceString,
+ caseSensitive,
+ matchesTheWholeCell,
+ findDirection,
+ findScope,
+ findBy,
+ findCompleted,
+ } = state;
+
+ const findDisabled = inputtingFindString.length === 0;
+ const replaceDisabled = matchesCount === 0 || !currentMatch?.replaceable;
+ const replaceAllDisabled = replaceables.length === 0;
+
+ const onFindStringChange = useCallback(
+ (newValue: string) => findReplaceService.changeInputtingFindString(newValue),
+ [findReplaceService]
+ );
+ const onReplaceStringChange = useCallback(
+ (replaceString: string) => findReplaceService.changeReplaceString(replaceString),
+ [findReplaceService]
+ );
+
+ const { focus } = useFindInputFocus(findReplaceService, ref);
+
+ const onClickFindButton = useCallback(() => {
+ if (findString === inputtingFindString) {
+ findReplaceService.moveToNextMatch();
+ } else {
+ findReplaceService.changeFindString(inputtingFindString);
+ findReplaceService.find();
+ }
+ }, [findString, inputtingFindString, findReplaceService]);
+ const onClickReplaceButton = useCallback(() => commandService.executeCommand(ReplaceCurrentMatchCommand.id), [commandService]);
+ const onClickReplaceAllButton = useCallback(async () => {
+ await commandService.executeCommand(ReplaceAllMatchesCommand.id);
+ focus();
+ }, [commandService]);
+
+ const onChangeFindDirection = useCallback((findDirection: string) => {
+ findReplaceService.changeFindDirection(findDirection as FindDirection);
+ }, [findReplaceService]);
+ const onChangeFindScope = useCallback((findScope: string) => {
+ findReplaceService.changeFindScope(findScope as FindScope);
+ }, [findReplaceService]);
+ const onChangeFindBy = useCallback((findBy: string) => {
+ findReplaceService.changeFindBy(findBy as FindBy);
+ }, [findReplaceService]);
+
+ const findScopeOptions = useFindScopeOptions(localeService);
+ const findDirectionOptions = useFindDirectionOptions(localeService);
+ const findByOptions = useFindByOptions(localeService);
+
+ useEffect(() => {
+ const shouldDisplayNoMatchInfo = findCompleted && matchesCount === 0;
+
+ let messageDisposable: Nullable<IDisposable> = null;
+ if (shouldDisplayNoMatchInfo) {
+ messageDisposable = messageService.show({
+ content: localeService.t('find-replace.dialog.no-match'),
+ type: MessageType.Warning,
+ delay: 5000,
+ });
+ }
+
+ return () => messageDisposable?.dispose();
+ }, [findCompleted, matchesCount, messageService, localeService]);
+
+ return (
+ <Fragment>
+ <FormLayout label={localeService.t('find-replace.dialog.find')}>
+ <SearchInput
+ findCompleted={findCompleted}
+ className="univer-find-input"
+ matchesCount={matchesCount}
+ matchesPosition={matchesPosition}
+ findReplaceService={findReplaceService}
+ localeService={localeService}
+ findString={inputtingFindString}
+ onChange={onFindStringChange}
+ />
+ </FormLayout>
+ <FormLayout label={localeService.t('find-replace.dialog.replace')}>
+ <Input
+ placeholder={localeService.t('find-replace.dialog.replace-placeholder')}
+ value={replaceString}
+ onChange={(value) => onReplaceStringChange(value)}
+ />
+ </FormLayout>
+ <FormLayout label={localeService.t('find-replace.dialog.find-direction.title')}>
+ <Select value={findDirection} options={findDirectionOptions} onChange={onChangeFindDirection} />
+ </FormLayout>
+ <FormDualColumnLayout>
+ <Fragment>
+ <FormLayout label={localeService.t('find-replace.dialog.find-scope.title')}>
+ <Select value={findScope} options={findScopeOptions} onChange={onChangeFindScope}></Select>
+ </FormLayout>
+ <FormLayout label={localeService.t('find-replace.dialog.find-by.title')}>
+ <Select value={findBy} options={findByOptions} onChange={onChangeFindBy}></Select>
+ </FormLayout>
+ </Fragment>
+ </FormDualColumnLayout>
+ <FormDualColumnLayout>
+ <Fragment>
+ <FormLayout>
+ <Checkbox
+ checked={caseSensitive}
+ value={caseSensitive}
+ onChange={(checked) => {
+ findReplaceService.changeCaseSensitive(checked as boolean);
+ }}
+ >
+ {localeService.t('find-replace.dialog.case-sensitive')}
+ </Checkbox>
+ </FormLayout>
+ <FormLayout>
+ <Checkbox
+ checked={matchesTheWholeCell}
+ value={matchesTheWholeCell}
+ onChange={(checked) => {
+ findReplaceService.changeMatchesTheWholeCell(checked as boolean);
+ }}
+ >
+ {localeService.t('find-replace.dialog.match-the-whole-cell')}
+ </Checkbox>
+ </FormLayout>
+ </Fragment>
+ </FormDualColumnLayout>
+ <div className={styles.findReplaceButtonsGroup}>
+ <Button type="primary" onClick={onClickFindButton} disabled={findDisabled}>{localeService.t('find-replace.dialog.find')}</Button>
+ <span className={styles.findReplaceButtonsGroupRight}>
+ <Button disabled={replaceDisabled} onClick={onClickReplaceButton}>{localeService.t('find-replace.dialog.replace')}</Button>
+ <Button disabled={replaceAllDisabled} onClick={onClickReplaceAllButton}>{localeService.t('find-replace.dialog.replace-all')}</Button>
+ </span>
+ </div>
+ </Fragment>
+ );
+});
+
+export function FindReplaceDialog() {
+ const findReplaceService = useDependency(IFindReplaceService);
+ const layoutService = useDependency(ILayoutService);
+ const contextService = useDependency(IContextService);
+
+ const state = useObservable(findReplaceService.state$, undefined, true);
+
+ const dialogContainerRef = useRef<HTMLDivElement>(null);
+ useEffect(() => {
+ let disposable: IDisposable | undefined;
+ if (dialogContainerRef.current) {
+ disposable = layoutService.registerContainerElement(dialogContainerRef.current);
+ }
+
+ return () => disposable?.dispose();
+ }, [layoutService]);
+
+ const focusRef = useRef<ISubFormRef>(null);
+ const setDialogContainerFocus = useCallback(
+ (focused: boolean) => contextService.setContextValue(FIND_REPLACE_DIALOG_FOCUS, focused),
+ [contextService]);
+ const setDialogInputFocus = useCallback(
+ (focused: boolean) => contextService.setContextValue(FIND_REPLACE_INPUT_FOCUS, focused)
+ , [contextService]);
+
+ useEffect(() => {
+ const focusSubscription = fromEvent(document, 'focusin').subscribe((event) => {
+ if (event.target && dialogContainerRef.current?.contains(event.target as Node)) {
+ setDialogContainerFocus(true);
+ } else {
+ setDialogContainerFocus(false);
+ }
+
+ if (!focusRef.current || !focusRef.current.selectHasFocus()) {
+ setDialogInputFocus(true);
+ } else {
+ setDialogInputFocus(false);
+ }
+ });
+
+ // Focus the input element the first time we open the find replace dialog.
+ focusRef.current?.focus();
+
+ setDialogContainerFocus(true);
+ setDialogInputFocus(true);
+
+ return () => {
+ focusSubscription.unsubscribe();
+ setDialogContainerFocus(false);
+ };
+ }, [setDialogContainerFocus, setDialogInputFocus]);
+
+ return (
+ <div className={styles.findReplaceDialogContainer} ref={dialogContainerRef}>
+ {!state.replaceRevealed ? <FindDialog ref={focusRef} /> : <ReplaceDialog ref={focusRef} />}
+ </div>
+ );
+}
+
+function useFindScopeOptions(localeService: LocaleService): Array<{ label: string; value: string }> {
+ const locale = localeService.getCurrentLocale();
+ const options = useMemo(() => {
+ return [
+ { label: localeService.t('find-replace.dialog.find-scope.current-sheet'), value: FindScope.SUBUNIT },
+ { label: localeService.t('find-replace.dialog.find-scope.workbook'), value: FindScope.UNIT },
+ ];
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [locale]);
+
+ return options;
+}
+
+function useFindDirectionOptions(localeService: LocaleService): Array<{ label: string; value: string }> {
+ const locale = localeService.getCurrentLocale();
+ const options = useMemo(() => {
+ return [
+ { label: localeService.t('find-replace.dialog.find-direction.row'), value: FindDirection.ROW },
+ { label: localeService.t('find-replace.dialog.find-direction.column'), value: FindDirection.COLUMN },
+ ];
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [locale]);
+
+ return options;
+}
+
+function useFindByOptions(localeService: LocaleService): Array<{ label: string; value: string }> {
+ const locale = localeService.getCurrentLocale();
+ const options = useMemo(() => {
+ return [
+ { label: localeService.t('find-replace.dialog.find-by.value'), value: FindBy.VALUE },
+ { label: localeService.t('find-replace.dialog.find-by.formula'), value: FindBy.FORMULA },
+ ];
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [locale]);
+
+ return options;
+}
diff --git a/packages/find-replace/src/views/dialog/SearchInput.tsx b/packages/find-replace/src/views/dialog/SearchInput.tsx
new file mode 100644
index 0000000000..14384ea75e
--- /dev/null
+++ b/packages/find-replace/src/views/dialog/SearchInput.tsx
@@ -0,0 +1,69 @@
+/**
+ * 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 { LocaleService } from '@univerjs/core';
+import type { IInputWithSlotProps } from '@univerjs/design';
+import { InputWithSlot, Pager } from '@univerjs/design';
+import React from 'react';
+import type { IFindReplaceService } from '../../services/find-replace.service';
+
+export interface ISearchInputProps extends Pick<IInputWithSlotProps, 'onFocus' | 'onBlur' | 'className' | 'onChange'> {
+ findCompleted: boolean;
+ localeService: LocaleService;
+ findReplaceService: IFindReplaceService;
+ matchesPosition: number;
+ matchesCount: number;
+ findString: string;
+}
+
+export function SearchInput(props: ISearchInputProps) {
+ const { findCompleted: findComplete, localeService, matchesCount, matchesPosition, findString, findReplaceService, onChange, ...rest } = props;
+ const noResult = findComplete && matchesCount === 0;
+ const text = noResult
+ ? localeService.t('find-replace.dialog.no-result')
+ : matchesCount === 0
+ ? ' '
+ : undefined;
+
+ return (
+ <InputWithSlot
+ autoFocus={true}
+ placeholder={localeService.t('find-replace.dialog.find-placeholder')}
+ slot={(
+ <Pager
+ loop={true}
+ text={text}
+ value={matchesPosition}
+ total={matchesCount}
+ onChange={(newIndex) => {
+ if (matchesPosition === matchesCount && newIndex === 1) {
+ findReplaceService.moveToNextMatch();
+ } else if (matchesPosition === 1 && newIndex === matchesCount) {
+ findReplaceService.moveToPreviousMatch();
+ } else if (newIndex < matchesPosition) {
+ findReplaceService.moveToPreviousMatch();
+ } else {
+ findReplaceService.moveToNextMatch();
+ }
+ }}
+ />
+ )}
+ value={findString}
+ onChange={(value) => onChange?.(value)}
+ {...rest}
+ />
+ );
+}
diff --git a/packages/sheets-find-replace/README-zh.md b/packages/sheets-find-replace/README-zh.md
index e3501941df..ff77c3226e 100644
--- a/packages/sheets-find-replace/README-zh.md
+++ b/packages/sheets-find-replace/README-zh.md
@@ -1,20 +1,30 @@
-# @univerjs/sheets-find
+# @univerjs/sheets-find-replace
-[![npm version](https://img.shields.io/npm/v/@univerjs/sheets-find)](https://npmjs.org/package/@univerjs/sheets-find)
-[![license](https://img.shields.io/npm/l/@univerjs/sheets-find)](https://img.shields.io/npm/l/@univerjs/sheets-find)
+[![npm version](https://img.shields.io/npm/v/@univerjs/sheets-find-replace)](https://npmjs.org/package/@univerjs/sheets-find-replace)
+[![license](https://img.shields.io/npm/l/@univerjs/sheets-find-replace)](https://img.shields.io/npm/l/@univerjs/sheets-find-replace)
## 简介
-TODO: Not written yet.
+该包提供了在电子表格中查找和替换文本的功能。
## 使用指南
+你应该将此插件与 `@univerjs/find-replace` 包一起使用。
+
+```ts
+import { UniverFindReplacePlugin } from '@univerjs/find-replace';
+import { UniverSheetsFindReplacePlugin } from '@univerjs/sheets-find-replace';
+
+univer.registerPlugin(UniverFindReplacePlugin);
+univer.registerPlugin(UniverSheetsFindReplacePlugin);
+```
+
### 安装
```shell
# 使用 npm
-npm install @univerjs/sheets-find
+npm install @univerjs/sheets-find-replace
# 使用 pnpm
-pnpm add @univerjs/sheets-find
+pnpm add @univerjs/sheets-find-replace
```
diff --git a/packages/sheets-find-replace/README.md b/packages/sheets-find-replace/README.md
index 1e40fbfbc5..e477b19b83 100644
--- a/packages/sheets-find-replace/README.md
+++ b/packages/sheets-find-replace/README.md
@@ -1,20 +1,30 @@
-# @univerjs/sheets-find
+# @univerjs/sheets-find-replace
-[![npm version](https://img.shields.io/npm/v/@univerjs/sheets-find)](https://npmjs.org/package/@univerjs/sheets-find)
-[![license](https://img.shields.io/npm/l/@univerjs/sheets-find)](https://img.shields.io/npm/l/@univerjs/sheets-find)
+[![npm version](https://img.shields.io/npm/v/@univerjs/sheets-find-replace)](https://npmjs.org/package/@univerjs/sheets-find-replace)
+[![license](https://img.shields.io/npm/l/@univerjs/sheets-find-replace)](https://img.shields.io/npm/l/@univerjs/sheets-find-replace)
## Introduction
-TODO: Not written yet.
+This package provides the feature to find and replace text in spreadsheets.
## Usage
+You should use this plugin with the `@univerjs/find-replace` package.
+
+```ts
+import { UniverFindReplacePlugin } from '@univerjs/find-replace';
+import { UniverSheetsFindReplacePlugin } from '@univerjs/sheets-find-replace';
+
+univer.registerPlugin(UniverFindReplacePlugin);
+univer.registerPlugin(UniverSheetsFindReplacePlugin);
+```
+
### Installation
```shell
# Using npm
-npm install @univerjs/sheets-find
+npm install @univerjs/sheets-find-replace
# Using pnpm
-pnpm add @univerjs/sheets-find
+pnpm add @univerjs/sheets-find-replace
```
diff --git a/packages/sheets-find-replace/package.json b/packages/sheets-find-replace/package.json
index f1ca45a88d..cb241e55b2 100644
--- a/packages/sheets-find-replace/package.json
+++ b/packages/sheets-find-replace/package.json
@@ -1,7 +1,7 @@
{
"name": "@univerjs/sheets-find-replace",
"version": "0.1.2",
- "private": true,
+ "private": false,
"description": "UniverSheet find replace plugin",
"author": "DreamNum <[email protected]>",
"license": "Apache-2.0",
@@ -62,20 +62,28 @@
},
"peerDependencies": {
"@univerjs/core": "workspace:*",
+ "@univerjs/engine-formula": "workspace:*",
"@univerjs/engine-render": "workspace:*",
"@univerjs/find-replace": "workspace:*",
"@univerjs/sheets": "workspace:*",
"@univerjs/sheets-ui": "workspace:*",
- "@wendellhu/redi": "0.13.0"
+ "@univerjs/ui": "workspace:*",
+ "@wendellhu/redi": "0.13.0",
+ "react": ">=16.9.0",
+ "rxjs": ">=7.0.0"
},
"devDependencies": {
"@univerjs/core": "workspace:*",
+ "@univerjs/engine-formula": "workspace:*",
"@univerjs/engine-render": "workspace:*",
"@univerjs/find-replace": "workspace:*",
"@univerjs/shared": "workspace:*",
"@univerjs/sheets": "workspace:*",
"@univerjs/sheets-ui": "workspace:*",
"@wendellhu/redi": "^0.13.0",
+ "less": "^4.2.0",
+ "react": "^18.2.0",
+ "rxjs": ">=7.0.0",
"typescript": "^5.4.2",
"vite": "^5.1.5",
"vitest": "^1.3.1"
diff --git a/packages/sheets-find-replace/src/action/action-find.ts b/packages/sheets-find-replace/src/action/action-find.ts
deleted file mode 100644
index 35c679b307..0000000000
--- a/packages/sheets-find-replace/src/action/action-find.ts
+++ /dev/null
@@ -1,17 +0,0 @@
-/**
- * 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 class ActionFind {}
diff --git a/packages/sheets-find-replace/src/action/i-action.ts b/packages/sheets-find-replace/src/action/i-action.ts
deleted file mode 100644
index 1b3489f788..0000000000
--- a/packages/sheets-find-replace/src/action/i-action.ts
+++ /dev/null
@@ -1,17 +0,0 @@
-/**
- * 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 class IAction {}
diff --git a/packages/sheets-find-replace/src/action/index.ts b/packages/sheets-find-replace/src/action/index.ts
deleted file mode 100644
index 7b0c32122e..0000000000
--- a/packages/sheets-find-replace/src/action/index.ts
+++ /dev/null
@@ -1,19 +0,0 @@
-/**
- * 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 * from './action-find';
-export * from './i-action';
-export * from './i-action-set';
diff --git a/packages/sheets-find-replace/src/base/cache.ts b/packages/sheets-find-replace/src/base/cache.ts
deleted file mode 100644
index 101c9971e7..0000000000
--- a/packages/sheets-find-replace/src/base/cache.ts
+++ /dev/null
@@ -1,17 +0,0 @@
-/**
- * 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 class Cache {}
diff --git a/packages/sheets-find-replace/src/base/index.ts b/packages/sheets-find-replace/src/base/index.ts
deleted file mode 100644
index 12401e3e01..0000000000
--- a/packages/sheets-find-replace/src/base/index.ts
+++ /dev/null
@@ -1,18 +0,0 @@
-/**
- * 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 * from './cache';
-export * from './state';
diff --git a/packages/sheets-find-replace/src/base/state.ts b/packages/sheets-find-replace/src/base/state.ts
deleted file mode 100644
index a82f0d8eb4..0000000000
--- a/packages/sheets-find-replace/src/base/state.ts
+++ /dev/null
@@ -1,17 +0,0 @@
-/**
- * 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 class State {}
diff --git a/packages/sheets-find-replace/src/commands/commands/sheet-replace.command.ts b/packages/sheets-find-replace/src/commands/commands/sheet-replace.command.ts
new file mode 100644
index 0000000000..38852618e7
--- /dev/null
+++ b/packages/sheets-find-replace/src/commands/commands/sheet-replace.command.ts
@@ -0,0 +1,74 @@
+/**
+ * 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 { CommandType, ICommandService, IUndoRedoService } from '@univerjs/core';
+import type { ICellData, ICommand, IObjectArrayPrimitiveType } from '@univerjs/core';
+import type { IReplaceAllResult } from '@univerjs/find-replace';
+import { type ISetRangeValuesCommandParams, SetRangeValuesCommand } from '@univerjs/sheets';
+import type { IAccessor } from '@wendellhu/redi';
+
+export interface ISheetReplaceCommandParams {
+ unitId: string;
+ replacements: ISheetReplacement[];
+}
+
+export interface ISheetReplacement {
+ count: number;
+ subUnitId: string;
+ value: IObjectArrayPrimitiveType<ICellData>;
+}
+
+/**
+ * This command is used for the SheetFindReplaceController to deal with replacing, including undo redo.
+ *
+ */
+export const SheetReplaceCommand: ICommand<ISheetReplaceCommandParams, IReplaceAllResult> = {
+ id: 'sheet.command.replace',
+ type: CommandType.COMMAND,
+ handler: async (accessor: IAccessor, params: ISheetReplaceCommandParams) => {
+ const undoRedoService = accessor.get(IUndoRedoService);
+ const commandService = accessor.get(ICommandService);
+
+ const { unitId, replacements } = params;
+
+ // NOTE: Note that if we are going to support "Replace All" in different units, this need to be changed.
+ const disposeBatchingHandler = undoRedoService.__tempBatchingUndoRedo(unitId);
+ const results = await Promise.all(replacements.map((replacement) => commandService.executeCommand(SetRangeValuesCommand.id, {
+ unitId,
+ subUnitId: replacement.subUnitId,
+ value: replacement.value,
+ } as ISetRangeValuesCommandParams)));
+ disposeBatchingHandler.dispose();
+
+ return getReplaceAllResult(results, replacements);
+ },
+};
+
+function getReplaceAllResult(results: boolean[], replacements: ISheetReplacement[]): IReplaceAllResult {
+ let success = 0;
+ let failure = 0;
+
+ results.forEach((r, index) => {
+ const count = replacements[index].count;
+ if (r) {
+ success += count;
+ } else {
+ failure += count;
+ }
+ });
+
+ return { success, failure };
+}
diff --git a/packages/sheets-find-replace/src/controllers/__tests__/utils.spec.ts b/packages/sheets-find-replace/src/controllers/__tests__/utils.spec.ts
index edfebcf212..74352a2063 100644
--- a/packages/sheets-find-replace/src/controllers/__tests__/utils.spec.ts
+++ b/packages/sheets-find-replace/src/controllers/__tests__/utils.spec.ts
@@ -14,8 +14,13 @@
* limitations under the License.
*/
-import { describe, expect, it } from 'vitest';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+import type { IWorkbookData, Worksheet } from '@univerjs/core';
+import { ILogService, IUniverInstanceService, LocaleType, LogLevel, Univer } from '@univerjs/core';
+import type { Dependency } from '@wendellhu/redi';
+import type { IFindQuery } from '@univerjs/find-replace';
+import { FindBy, FindDirection, FindScope } from '@univerjs/find-replace';
import {
isBeforePositionWithColumnPriority,
isBeforePositionWithRowPriority,
@@ -23,6 +28,7 @@ import {
isBehindPositionWithRowPriority,
isSamePosition,
} from '../utils';
+import { hitCell } from '../sheet-find-replace.controller';
describe('Test sheet find replace utils', () => {
it('Should "isSamePosition" work as expected', () => {
@@ -196,3 +202,125 @@ describe('Test sheet find replace utils', () => {
).toBeFalsy();
});
});
+
+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,
+ 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,
+ 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.createUniverSheet(TEST_WORKBOOK_DATA);
+ const univerInstanceService = get(IUniverInstanceService);
+ univerInstanceService.focusUniverInstance(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/find-replace.controller.ts b/packages/sheets-find-replace/src/controllers/find-replace.controller.ts
deleted file mode 100644
index 8ada975388..0000000000
--- a/packages/sheets-find-replace/src/controllers/find-replace.controller.ts
+++ /dev/null
@@ -1,391 +0,0 @@
-/**
- * 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 { ICellData, IRange, Nullable, Workbook, Worksheet } from '@univerjs/core';
-import { Disposable, ICommandService, IUniverInstanceService, LifecycleStages, OnLifecycle } from '@univerjs/core';
-import { IRenderManagerService } from '@univerjs/engine-render';
-import type { IFindComplete, IFindMatch, IFindQuery, IFindReplaceProvider } from '@univerjs/find-replace';
-import { FindModel, IFindReplaceService } from '@univerjs/find-replace';
-import { SelectionManagerService, SheetInterceptorService } from '@univerjs/sheets';
-import { getCoordByCell, getSheetObject, SheetSkeletonManagerService } from '@univerjs/sheets-ui';
-import { type IDisposable, Inject, Injector } from '@wendellhu/redi';
-
-import type { ISheetFindReplaceHighlightShapeProps } from '../views/shapes/find-replace-highlight.shape';
-import { SheetFindReplaceHighlightShape } from '../views/shapes/find-replace-highlight.shape';
-import { isBeforePositionWithRowPriority, isBehindPositionWithRowPriority, isSamePosition } from './utils';
-
-@OnLifecycle(LifecycleStages.Steady, SheetsFindReplaceController)
-export class SheetsFindReplaceController extends Disposable implements IDisposable {
- private _provider!: SheetsFindReplaceProvider;
-
- constructor(
- @Inject(Injector) private readonly _injector: Injector,
- @IFindReplaceService private readonly _findReplaceService: IFindReplaceService
- ) {
- super();
-
- this._init();
- }
-
- override dispose(): void {
- super.dispose();
-
- this._provider.dispose();
- }
-
- private _init(): void {
- const provider = this._injector.createInstance(SheetsFindReplaceProvider);
- this._provider = provider;
- this.disposeWithMe(this._findReplaceService.registerFindReplaceProvider(provider));
- }
-}
-
-const SHEETS_FIND_REPLACE_PROVIDER_NAME = 'sheets-find-replace-provider';
-const FIND_REPLACE_Z_INDEX = 10000;
-
-export interface ISheetCellMatch extends IFindMatch {
- provider: typeof SHEETS_FIND_REPLACE_PROVIDER_NAME;
- range: {
- unitId: string;
- subUnitId: string;
- range: IRange;
- };
-}
-
-/**
- * This class executes finding in a workbook and subscribe to the content change event so when its results changes
- * FindReplaceService would know that and update searching results. Also this class in responsible for
- * highlighting matched cells.
- */
-export class SheetFindModel extends FindModel {
- private _matchesCount = 0;
- private _matchesPosition = 0; // position starts from 1
- private _matches: ISheetCellMatch[] = [];
-
- private _highlightShapes: Nullable<Set<SheetFindReplaceHighlightShape>>;
-
- get unitId(): string {
- return this._workbook.getUnitId();
- }
-
- get matchesCount(): number {
- return this._matchesCount;
- }
-
- get matchesPosition(): number {
- return this._matchesPosition;
- }
-
- get currentMatch(): Nullable<ISheetCellMatch> {
- return this._matchesPosition > 0 ? this._matches[this._matchesPosition - 1] : null;
- }
-
- constructor(
- private readonly _workbook: Workbook,
- @ICommandService private readonly _commandService: ICommandService,
- @IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService,
- @IRenderManagerService private readonly _renderManagerService: IRenderManagerService,
- @Inject(SheetSkeletonManagerService) private readonly _sheetSkeletonManagerService: SheetSkeletonManagerService,
- @Inject(SelectionManagerService) private readonly _selectionManagerService: SelectionManagerService,
- @Inject(SheetInterceptorService) private readonly _sheetInterceptorService: SheetInterceptorService
- ) {
- super();
- }
-
- override dispose(): void {
- this._highlightShapes?.forEach((shape) => shape.dispose());
- }
-
- getMatches(): IFindMatch[] {
- return this._matches;
- }
-
- findInActiveWorksheet(query: IFindQuery): IFindComplete {
- const currentWorksheet = this._workbook.getActiveSheet();
- const unitId = this._workbook.getUnitId();
-
- const complete = this._findTheActiveWorksheet(currentWorksheet, query, unitId);
- this._matches = complete.results;
- this._matchesCount = complete.results.length;
-
- return complete;
- }
-
- private _getStartPosition(): IRange | null {
- if (!this._isSelfFocused()) {
- return null;
- }
-
- if (this.currentMatch) {
- return this.currentMatch.range.range;
- }
-
- const selections = this._selectionManagerService.getSelections();
- return selections?.length ? selections[0].range : null;
- }
-
- override moveToNextMatch(loop = false): ISheetCellMatch | null {
- const startPosition = this._getStartPosition();
- const matchToMove: [ISheetCellMatch, number] | null = startPosition
- ? this._findNextMatch(startPosition, loop)
- : [this._matches[0], 0];
-
- if (matchToMove) {
- this._matchesPosition = matchToMove[1] + 1;
- return matchToMove[0];
- }
-
- this._matchesPosition = 0;
- return null;
- }
-
- override moveToPreviousMatch(loop = false): ISheetCellMatch | null {
- const startPosition = this._getStartPosition();
- const matchToMove: [ISheetCellMatch, number] | null = startPosition
- ? this._findPreviousMatch(startPosition, loop)
- : [this._matches[0], 0];
-
- if (matchToMove) {
- this._matchesPosition = matchToMove[1] + 1;
- return matchToMove[0];
- }
-
- this._matchesPosition = 0;
- return null;
- }
-
- private _findPreviousMatch(range: IRange, loop = false): [ISheetCellMatch, number] | null {
- let index = this._matches.findLastIndex((match) => {
- const matchRange = match.range.range;
- const isBefore = isBeforePositionWithRowPriority(range, matchRange);
- if (!isBefore) {
- return false;
- }
-
- if (!this.currentMatch) {
- return true;
- }
-
- return !isSamePosition(range, matchRange);
- });
-
- if (index === -1 && !this.currentMatch) {
- index = 0;
- }
-
- if (index === -1 && loop) {
- index = this._matches.length - 1;
- }
-
- return index > -1 ? [this._matches[index], index] : null;
- }
-
- private _findNextMatch(range: IRange, loop = false): [ISheetCellMatch, number] | null {
- let index = this._matches.findIndex((match) => {
- const matchRange = match.range.range;
- const isBehind = isBehindPositionWithRowPriority(range, matchRange);
- if (!isBehind) {
- return false;
- }
-
- if (!this.currentMatch) {
- return true;
- }
-
- return !isSamePosition(range, matchRange);
- });
-
- if (index === -1 && !this.currentMatch) {
- index = this._matches.length - 1;
- }
-
- if (index === -1 && loop) {
- index = 0;
- }
-
- return index > -1 ? [this._matches[index], index] : null;
- }
-
- private _findTheActiveWorksheet(
- worksheet: Worksheet,
- query: IFindQuery,
- unitId: string
- ): IFindComplete<ISheetCellMatch> {
- if (!query.text) {
- return {
- results: [],
- };
- }
-
- const subUnitId = worksheet.getSheetId();
- const rowCount = worksheet.getRowCount();
- const colCount = worksheet.getColumnCount();
-
- const results: ISheetCellMatch[] = [];
- worksheet.getMatrixWithMergedCells(0, 0, rowCount, colCount).forValue((row, col, value) => {
- // We should get value from the view model.
- // TODO: this may change because sometime we need to search the raw value.
- const displayValue = worksheet.getCell(row, col);
- const hit = hitCell(displayValue, query);
- if (hit) {
- const result: ISheetCellMatch = {
- provider: SHEETS_FIND_REPLACE_PROVIDER_NAME,
- unitId,
- range: {
- unitId,
- subUnitId,
- range: {
- startRow: row,
- startColumn: col,
- endColumn: col + (value.rowSpan ?? 0),
- endRow: row + (value.colSpan ?? 0),
- },
- },
- };
-
- results.push(result);
- }
- });
-
- const complete = {
- results,
- };
-
- this._updateFindHighlight(complete);
- return complete;
- }
-
- private _updateFindHighlight(findComplete: IFindComplete): void {
- this._highlightShapes?.forEach((shape) => shape.dispose());
-
- const skeleton = this._sheetSkeletonManagerService.getCurrent()?.skeleton;
- if (!skeleton) {
- return;
- }
-
- const sheetObjects = this._getSheetObject();
- if (!sheetObjects) {
- return;
- }
-
- const unitId = this._workbook.getUnitId();
- const currentRender = this._renderManagerService.getRenderById(unitId);
- if (currentRender == null) {
- return;
- }
-
- const { scene } = currentRender;
- const results = findComplete.results as ISheetCellMatch[];
- const highlightShapes = results.map((find, index) => {
- const { startColumn, startRow, endColumn, endRow } = find.range.range;
- const startPosition = getCoordByCell(startRow, startColumn, scene, skeleton);
- const endPosition = getCoordByCell(endRow, endColumn, scene, skeleton);
- const { startX, startY } = startPosition;
- const { endX, endY } = endPosition;
- const width = endX - startX;
- const height = endY - startY;
-
- // TODO@wzhudev: we may need an edge detection to decide to put label on the top or on the bottom of the rect.
- const props: ISheetFindReplaceHighlightShapeProps = {
- left: startX,
- top: startY,
- width,
- height,
- evented: false,
- };
-
- return new SheetFindReplaceHighlightShape(`find-highlight-${index}`, props);
- });
-
- // TODO@wzhudev: there is a change that re-render is not triggered
- scene.addObjects(highlightShapes, FIND_REPLACE_Z_INDEX);
- this._highlightShapes = new Set(highlightShapes);
- }
-
- private _getSheetObject() {
- return getSheetObject(this._univerInstanceService, this._renderManagerService);
- }
-
- private _isSelfFocused(): boolean {
- return this._univerInstanceService.getFocusedUniverInstance()?.getUnitId() === this._workbook.getUnitId();
- }
-}
-
-/**
- * This module is responsible for searching and replacing in the sheets.
- * It also adds the search results to the search view by highlighting them.
- */
-class SheetsFindReplaceProvider extends Disposable implements IFindReplaceProvider {
- /**
- * Hold all find results in this kind of univer business instances (Workbooks).
- */
- private readonly _findModels: SheetFindModel[] = [];
- private readonly _findModelsByUnitId = new Map<string, SheetFindModel>();
-
- constructor(
- @IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService,
- @Inject(Injector) private readonly _injector: Injector
- ) {
- super();
- }
-
- async find(query: IFindQuery): Promise<SheetFindModel[]> {
- this._cancelFinding();
-
- const currentWorkbook = this._univerInstanceService.getCurrentUniverSheetInstance();
- if (currentWorkbook) {
- const sheetFind = this._injector.createInstance(SheetFindModel, currentWorkbook);
- this._findModels.push(sheetFind);
- this._findModelsByUnitId.set(currentWorkbook.getUnitId(), sheetFind);
-
- sheetFind.findInActiveWorksheet(query);
- return [sheetFind];
- }
-
- return [];
- }
-
- cancel(): void {
- this._cancelFinding();
- }
-
- private _cancelFinding(): void {
- this._findModels.forEach((model) => model.dispose());
- this._findModelsByUnitId.clear();
- }
-}
-
-/**
- * This function determines if a cell's content matches what is looked for.
- * @param value
- * @param query
- * @returns
- */
-function hitCell(value: Nullable<ICellData>, query: IFindQuery): boolean {
- if (value == null) {
- return false;
- }
-
- const { v } = value;
-
- if (typeof v === 'string') {
- return v.toLowerCase().includes(query.text.toLowerCase());
- }
-
- // TODO@wzhudev: there are a lot of implementation details.
-
- return false;
-}
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.ts
new file mode 100644
index 0000000000..e9c239bd08
--- /dev/null
+++ b/packages/sheets-find-replace/src/controllers/sheet-find-replace.controller.ts
@@ -0,0 +1,1047 @@
+/**
+ * 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 { ColorKit, CommandType, Disposable, EDITOR_ACTIVATED, fromCallback, groupBy, ICommandService, IContextService, IUniverInstanceService, LifecycleStages, ObjectMatrix, OnLifecycle, replaceInDocumentBody, rotate, ThemeService, Tools } from '@univerjs/core';
+import type { ICellData, IObjectMatrixPrimitiveType, IRange, Nullable, Workbook, Worksheet } from '@univerjs/core';
+import { IRenderManagerService, RENDER_RAW_FORMULA_KEY } from '@univerjs/engine-render';
+import type { IFindComplete, IFindMatch, IFindMoveParams, IFindQuery, IFindReplaceProvider, IReplaceAllResult } from '@univerjs/find-replace';
+import { FindBy, FindDirection, FindModel, FindReplaceController, FindScope, IFindReplaceService } from '@univerjs/find-replace';
+import type { ISelectionWithStyle, ISetRangeValuesCommandParams, ISetSelectionsOperationParams, ISetWorksheetActivateCommandParams, ISheetCommandSharedParams } from '@univerjs/sheets';
+import { SelectionManagerService, SetRangeValuesCommand, SetSelectionsOperation, SetWorksheetActivateCommand, SetWorksheetActiveOperation } from '@univerjs/sheets';
+import type { IScrollToCellCommandParams } from '@univerjs/sheets-ui';
+import { getCoordByCell, getSheetObject, ScrollToCellCommand, SheetSkeletonManagerService } from '@univerjs/sheets-ui';
+import { type IDisposable, Inject, Injector } from '@wendellhu/redi';
+import { debounceTime, filter, merge, skip, Subject, throttleTime } from 'rxjs';
+
+import type { ISheetFindReplaceHighlightShapeProps } from '../views/shapes/find-replace-highlight.shape';
+import { SheetFindReplaceHighlightShape } from '../views/shapes/find-replace-highlight.shape';
+import type { ISheetReplaceCommandParams, ISheetReplacement } from '../commands/commands/sheet-replace.command';
+import { SheetReplaceCommand } from '../commands/commands/sheet-replace.command';
+import { isBeforePositionWithColumnPriority, isBeforePositionWithRowPriority, isBehindPositionWithColumnPriority, isBehindPositionWithRowPriority, isSamePosition, isSelectionSingleCell } from './utils';
+
+@OnLifecycle(LifecycleStages.Steady, SheetsFindReplaceController)
+export class SheetsFindReplaceController extends Disposable implements IDisposable {
+ private _provider!: SheetsFindReplaceProvider;
+
+ constructor(
+ @Inject(Injector) private readonly _injector: Injector,
+ @Inject(FindReplaceController) private readonly _findReplaceController: FindReplaceController,
+ @IContextService private readonly _contextService: IContextService,
+ @IFindReplaceService private readonly _findReplaceService: IFindReplaceService,
+ @ICommandService private readonly _commandService: ICommandService
+ ) {
+ super();
+
+ this._init();
+ this._initCommands();
+ }
+
+ override dispose(): void {
+ super.dispose();
+
+ this._provider.dispose();
+ }
+
+ private _init(): void {
+ const provider = this._injector.createInstance(SheetsFindReplaceProvider);
+ this._provider = provider;
+
+ this.disposeWithMe(this._findReplaceService.registerFindReplaceProvider(provider));
+
+ // The find replace panel should be closed when sheet cell editor is activated, or the formula editor is focused.
+ this.disposeWithMe(
+ this._contextService.subscribeContextValue$(EDITOR_ACTIVATED).pipe(filter((v) => !!v)).subscribe(() => this._findReplaceController.closePanel())
+ );
+ }
+
+ private _initCommands(): void {
+ [SheetReplaceCommand].forEach((command) => this.disposeWithMe(this._commandService.registerCommand(command)));
+ }
+}
+
+const SHEETS_FIND_REPLACE_PROVIDER_NAME = 'sheets-find-replace-provider';
+const FIND_REPLACE_Z_INDEX = 10000;
+
+export interface ISheetCellMatch extends IFindMatch {
+ isFormula: boolean;
+ provider: typeof SHEETS_FIND_REPLACE_PROVIDER_NAME;
+ range: {
+ subUnitId: string;
+ range: IRange;
+ };
+}
+
+/**
+ * This class executes finding in a workbook and subscribe to the content change event so when its results changes
+ * FindReplaceService would know that and update searching results. Also this class in responsible for
+ * highlighting matched cells.
+ */
+export class SheetFindModel extends FindModel {
+ // We can directly inject the `FindReplaceService` here, and call its methods instead of using the observables.
+ private readonly _matchesUpdate$ = new Subject<ISheetCellMatch[]>();
+ readonly matchesUpdate$ = this._matchesUpdate$.asObservable();
+
+ private readonly _activelyChangingMatch$ = new Subject<ISheetCellMatch>();
+ readonly activelyChangingMatch$ = this._activelyChangingMatch$.asObservable();
+
+ /** Hold matches by the worksheet they are in. Make it easier to track the next (or previous) match when searching in the whole workbook. */
+ private _matchesByWorksheet = new Map<string, ISheetCellMatch[]>();
+ /** Hold all matches in the currently searching scope. */
+ private _matches: ISheetCellMatch[] = [];
+ /** Position of the current focused ISheetCellMatch, starting from 1. */
+ private _matchesPosition = 0;
+
+ private _activeHighlightIndex = -1;
+ private _highlightShapes: SheetFindReplaceHighlightShape[] = [];
+ private _currentHighlightShape: Nullable<SheetFindReplaceHighlightShape> = null;
+
+ /** This properties holds the query params during this searching session. */
+ private _query: Nullable<IFindQuery> = null;
+
+ private get _matchesCount(): number { return this._matches.length; }
+ get unitId(): string { return this._workbook.getUnitId(); }
+ get matchesCount(): number { return this._matchesCount; }
+ get matchesPosition(): number { return this._matchesPosition; }
+ get currentMatch(): Nullable<ISheetCellMatch> { return this._matchesPosition > 0 ? this._matches[this._matchesPosition - 1] : null; }
+
+ constructor(
+ private readonly _workbook: Workbook,
+ @IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService,
+ @IRenderManagerService private readonly _renderManagerService: IRenderManagerService,
+ @ICommandService private readonly _commandService: ICommandService,
+ @IContextService private readonly _contextService: IContextService,
+ @Inject(ThemeService) private readonly _themeService: ThemeService,
+ @Inject(SheetSkeletonManagerService) private readonly _sheetSkeletonManagerService: SheetSkeletonManagerService,
+ @Inject(SelectionManagerService) private readonly _selectionManagerService: SelectionManagerService
+ ) {
+ super();
+ }
+
+ override dispose(): void {
+ super.dispose();
+
+ this._disposeHighlights();
+ this._toggleDisplayRawFormula(false);
+ }
+
+ getMatches(): IFindMatch[] {
+ return this._matches;
+ }
+
+ start(query: IFindQuery): void {
+ this._query = query;
+
+ if (query.findBy === FindBy.FORMULA) {
+ this._toggleDisplayRawFormula(true);
+ } else {
+ this._toggleDisplayRawFormula(false);
+ }
+
+ switch (query.findScope) {
+ case FindScope.UNIT:
+ this.findInWorkbook(query);
+ break;
+ case FindScope.SUBUNIT:
+ default:
+ this.findInActiveWorksheet(query);
+ break;
+ }
+ }
+
+ private _toggleDisplayRawFormula(force: boolean): void {
+ this._contextService.setContextValue(RENDER_RAW_FORMULA_KEY, force);
+ }
+
+ /**
+ * Find all matches in the current workbook no matter which worksheet is activated.
+ * @param query the query object
+ * @returns the query complete event
+ */
+ findInWorkbook(query: IFindQuery): IFindComplete {
+ const unitId = this._workbook.getUnitId();
+
+ let complete: IFindComplete;
+ let firstSearch = true;
+
+ const findInWorkbook = () => {
+ const allCompletes = this._workbook.getSheets()
+ .filter((worksheet) => !worksheet.isSheetHidden()) // We do not search in hidden Worksheets.
+ .map((worksheet) => {
+ const complete = this._findInWorksheet(worksheet, query, unitId);
+ const sheetId = worksheet.getSheetId();
+
+ const { results } = complete;
+ if (results.length) {
+ this._matchesByWorksheet.set(sheetId, complete.results);
+ } else {
+ this._matchesByWorksheet.delete(sheetId);
+ }
+
+ return complete;
+ });
+
+ this._matches = allCompletes.map((c) => c.results).flat();
+ this._updateFindHighlight();
+
+ if (firstSearch) {
+ complete = { results: this._matches };
+ firstSearch = false;
+ } else {
+ this._matchesUpdate$.next(this._matches);
+ }
+ };
+
+ this.disposeWithMe(this._sheetSkeletonManagerService.currentSkeleton$.subscribe(() => {
+ this._updateFindHighlight();
+ this._updateCurrentHighlightShape(this._activeHighlightIndex);
+ }));
+
+ this.disposeWithMe(
+ fromCallback(this._commandService.onCommandExecuted)
+ .pipe(
+ filter(([command, options]) => command.id === SetWorksheetActiveOperation.id && !options?.fromFindReplace)
+ )
+ .subscribe(() => {
+ const activeSheet = this._workbook.getActiveSheet();
+ const activeSheetId = activeSheet.getSheetId();
+ if (!this._matchesByWorksheet.has(activeSheetId)) {
+ return;
+ }
+
+ this._findNextMatchOnActiveSheetChange(activeSheet);
+ })
+ );
+
+ // When the sheet model changes, we should re-search.
+ this.disposeWithMe(
+ fromCallback(this._commandService.onCommandExecuted)
+ .pipe(
+ filter(([command]) => command.type === CommandType.MUTATION
+ && (command.params as ISheetCommandSharedParams).unitId === this._workbook.getUnitId()
+ ),
+ throttleTime(600, undefined, { leading: false, trailing: true })
+ )
+ .subscribe(() => findInWorkbook())
+ );
+
+ findInWorkbook();
+ return complete!;
+ }
+
+ /**
+ * This method is used in `findInWorkbook`. When the active sheet changes, this method helps to find the next match
+ * in the new worksheet.
+ */
+ private _findNextMatchOnActiveSheetChange(activeSheet: Worksheet): void {
+ let match: ISheetCellMatch;
+ let index: number;
+ let globalIndex = 0;
+
+ const matchesByWorksheet = this._matchesByWorksheet.get(activeSheet.getSheetId())!;
+ const selections = this._selectionManagerService.getSelections();
+ if (!selections?.length) {
+ match = matchesByWorksheet[0];
+ index = 0;
+ globalIndex = this._matches.findIndex((m) => m === match);
+ } else {
+ [match, globalIndex] = this._findNextMatchByRange(matchesByWorksheet, selections[0].range);
+ index = matchesByWorksheet.findIndex((m) => m === match);
+ }
+
+ this._matchesPosition = globalIndex + 1;
+ this._activelyChangingMatch$.next(match);
+
+ this._activeHighlightIndex = index;
+ this._updateFindHighlight();
+ this._updateCurrentHighlightShape(index);
+ }
+
+ /**
+ * Find all matches (only) in the currently activated worksheet.
+ * @param query the query object
+ * @returns the query complete event
+ */
+ findInActiveWorksheet(query: IFindQuery): IFindComplete {
+ const unitId = this._workbook.getUnitId();
+
+ const checkShouldFindInSelections = (): boolean => {
+ const currentWorksheet = this._workbook.getActiveSheet();
+ const currentSelections = this._selectionManagerService.getSelections();
+ const shouldFindInSelections = currentSelections?.some((selection) => !isSelectionSingleCell(selection, currentWorksheet)) ?? false;
+ return shouldFindInSelections;
+ };
+
+ let complete: IFindComplete;
+ let firstSearch = true;
+ let findBySelections = false;
+
+ const performFindInWorksheet = (): IFindComplete => {
+ const currentWorksheet = this._workbook.getActiveSheet();
+ const lastMatch = this.currentMatch; // temporarily store the last match to restore the position after the model changes
+
+ findBySelections = checkShouldFindInSelections();
+ const currentSelections = this._selectionManagerService.getSelections();
+ const newComplete = findBySelections
+ ? this._findInSelections(currentWorksheet, currentSelections as ISelectionWithStyle[], query, unitId)
+ : this._findInWorksheet(currentWorksheet, query, unitId);
+
+ this._matches = newComplete.results;
+ this._matchesPosition = this._tryRestoreLastMatchesPosition(lastMatch, this._matches);
+
+ if (firstSearch) {
+ complete = newComplete;
+ firstSearch = false;
+ } else {
+ this._matchesUpdate$.next(this._matches);
+ }
+
+ this._updateFindHighlight();
+ return newComplete;
+ };
+
+ // When the skeleton changes, we should re-render the highlights.
+ this.disposeWithMe(this._sheetSkeletonManagerService.currentSkeleton$.subscribe(() => this._updateFindHighlight()));
+
+ this.disposeWithMe(
+ merge(
+ fromCallback(this._commandService.onCommandExecuted).pipe(
+ filter(([command]) => {
+ // If there mutations happens on this unit, we should re-search.
+ if (command.type === CommandType.MUTATION && (command.params as ISheetCommandSharedParams).unitId === this._workbook.getUnitId()) {
+ return true;
+ };
+
+ // If selections changes, we should re-search.
+ if (command.id === SetSelectionsOperation.id && (command.params as ISetSelectionsOperationParams).unitId === unitId) {
+ const shouldFindBySelections = checkShouldFindInSelections();
+ if (shouldFindBySelections === false && findBySelections === false) {
+ return false;
+ }
+
+ findBySelections = shouldFindBySelections;
+ return true;
+ }
+
+ return false;
+ })
+ ),
+ // activeSheet$ is a BehaviorSubject, so we need to skip the first
+ this._workbook.activeSheet$.pipe(skip(1))
+ ).pipe(debounceTime(200)).subscribe(() => performFindInWorksheet())
+ );
+
+ performFindInWorksheet();
+
+ return complete!;
+ }
+
+ private _findInRange(
+ worksheet: Worksheet,
+ query: IFindQuery,
+ range: IRange,
+ unitId: string,
+ dedupeFn?: (row: number, col: number) => boolean
+ ): IFindComplete<ISheetCellMatch> {
+ const results: ISheetCellMatch[] = [];
+ const subUnitId = worksheet.getSheetId();
+
+ const iter = (query.findDirection === FindDirection.COLUMN ? worksheet.iterateByColumn : worksheet.iterateByRow).bind(worksheet)(range);
+ while (true) {
+ const { done, value } = iter.next();
+ if (done) break;
+
+ const { row, col, colSpan, rowSpan, value: cellData } = value;
+ if (dedupeFn?.(row, col)) continue;
+
+ const { hit, replaceable, isFormula } = hitCell(worksheet, row, col, query, cellData);
+ if (hit) {
+ const result: ISheetCellMatch = {
+ provider: SHEETS_FIND_REPLACE_PROVIDER_NAME,
+ unitId,
+ replaceable,
+ isFormula,
+ range: {
+ subUnitId,
+ range: {
+ startRow: row,
+ startColumn: col,
+ endColumn: col + (colSpan ?? 1) - 1,
+ endRow: row + (rowSpan ?? 1) - 1,
+ },
+ },
+ };
+
+ results.push(result);
+ }
+ }
+
+ return { results };
+ }
+
+ private _findInSelections(
+ worksheet: Worksheet,
+ selections: ISelectionWithStyle[],
+ query: IFindQuery,
+ unitId: string
+ ): IFindComplete<ISheetCellMatch> {
+ const { findDirection } = query;
+
+ const sortFn = findDirection === FindDirection.ROW ? isBehindPositionWithRowPriority : isBehindPositionWithColumnPriority;
+ const dedupeSet = new Set<string>();
+ const finds = selections
+ .map((selection) => this._findInRange(worksheet, query, selection.range, unitId,
+ (row, col) => {
+ const key = `${row}-${col}`;
+ if (dedupeSet.has(key)) return true;
+ dedupeSet.add(key);
+ return false;
+ }).results)
+ .flat()
+ .sort((a, b) => sortFn(a.range.range, b.range.range) ? -1 : 1);
+
+ return { results: finds };
+ // TODO@wzhudev: we need to dedupe
+ }
+
+ /** Find matches in a given worksheet. */
+ private _findInWorksheet(worksheet: Worksheet, query: IFindQuery, unitId: string): IFindComplete<ISheetCellMatch> {
+ const rowCount = worksheet.getRowCount();
+ const colCount = worksheet.getColumnCount();
+ const range: IRange = { startRow: 0, startColumn: 0, endRow: rowCount - 1, endColumn: colCount - 1 };
+
+ return this._findInRange(worksheet, query, range, unitId);
+ }
+
+ private _disposeHighlights(): void {
+ this._highlightShapes.forEach((shape) => {
+ shape.dispose();
+ shape.getScene().makeDirty();
+ });
+
+ this._highlightShapes = [];
+
+ this._currentHighlightShape?.dispose();
+ this._currentHighlightShape = null;
+ }
+
+ private _updateFindHighlight(): void {
+ this._disposeHighlights();
+
+ const skeleton = this._sheetSkeletonManagerService.getCurrent()?.skeleton;
+ if (!skeleton) {
+ return;
+ }
+
+ const sheetObjects = this._getSheetObject();
+ if (!sheetObjects) {
+ return;
+ }
+
+ const currentUnitId = this._univerInstanceService.getFocusedUniverInstance()?.getUnitId();
+ if (currentUnitId !== this._workbook.getUnitId()) {
+ return;
+ }
+
+ const unitId = this._workbook.getUnitId();
+ const currentRender = this._renderManagerService.getRenderById(unitId);
+ if (currentRender == null) {
+ return;
+ }
+
+ const { scene } = currentRender;
+ const matches = this._matches;
+
+ const searchBackgroundColor = this._themeService.getCurrentTheme().gold400;
+ const color = new ColorKit(searchBackgroundColor).toRgb();
+ const worksheet = this._workbook.getActiveSheet();
+ const activeSheetId = worksheet.getSheetId();
+ const highlightShapes = matches.filter((match) => match.range.subUnitId === activeSheetId).map((find, index) => {
+ const { startColumn, startRow, endColumn, endRow } = find.range.range;
+ const startPosition = getCoordByCell(startRow, startColumn, scene, skeleton);
+ const endPosition = getCoordByCell(endRow, endColumn, scene, skeleton);
+ const { startX, startY } = startPosition;
+ const { endX, endY } = endPosition;
+
+ const rowHidden = !worksheet.getRowVisible(startRow);
+ const columnHidden = !worksheet.getColVisible(startColumn);
+
+ const inHiddenRange = rowHidden || columnHidden;
+ const width = columnHidden ? 2 : endX - startX;
+ const height = rowHidden ? 2 : endY - startY;
+
+ const props: ISheetFindReplaceHighlightShapeProps = {
+ left: startX,
+ top: startY,
+ color,
+ width,
+ height,
+ evented: false,
+ inHiddenRange,
+ };
+
+ return new SheetFindReplaceHighlightShape(`find-highlight-${index}`, props);
+ });
+
+ scene.addObjects(highlightShapes, FIND_REPLACE_Z_INDEX);
+ this._highlightShapes = highlightShapes;
+
+ scene.makeDirty();
+ }
+
+ private _updateCurrentHighlightShape(matchIndex?: number): void {
+ // de-highlight the current highlighted shape
+ this._currentHighlightShape?.setShapeProps({ activated: false });
+ this._currentHighlightShape = null;
+
+ if (matchIndex !== undefined) {
+ const shape = this._highlightShapes[matchIndex];
+ if (!shape) {
+ return;
+ }
+
+ this._currentHighlightShape = shape;
+ shape.setShapeProps({ activated: true });
+ }
+ }
+
+ private _getSheetObject() {
+ return getSheetObject(this._univerInstanceService, this._renderManagerService);
+ }
+
+ private _focusMatch(match: ISheetCellMatch): void {
+ const subUnitId = match.range.subUnitId;
+ if (subUnitId !== this._workbook.getActiveSheet().getSheetId()) {
+ this._commandService.syncExecuteCommand(SetWorksheetActivateCommand.id,
+ { unitId: this._workbook.getUnitId(), subUnitId } as ISetWorksheetActivateCommandParams,
+ { fromFindReplace: true }
+ );
+ }
+
+ this._commandService.syncExecuteCommand(
+ ScrollToCellCommand.id,
+ { range: match.range.range } as IScrollToCellCommandParams,
+ { fromFindReplace: true }
+ );
+ }
+
+ private _tryRestoreLastMatchesPosition(lastMatch: Nullable<ISheetCellMatch>, newMatches: ISheetCellMatch[]): number {
+ if (!lastMatch) return 0;
+
+ const { subUnitId: lastSubUnitId } = lastMatch.range;
+ const { startColumn: lastStartColumn, startRow: lastStartRow } = lastMatch.range.range;
+ const index = newMatches.findIndex((match) => {
+ if (lastSubUnitId !== match.range.subUnitId) {
+ return false;
+ }
+
+ const { startColumn, startRow } = match.range.range;
+ return startColumn === lastStartColumn && startRow === lastStartRow;
+ });
+
+ return index > -1 ? index + 1 : 0;
+ }
+
+ override moveToNextMatch(params?: IFindMoveParams): ISheetCellMatch | null {
+ if (!this._matches.length) {
+ return null;
+ }
+
+ const loop = params?.loop ?? false;
+ const stayIfOnMatch = params?.stayIfOnMatch ?? false;
+ const noFocus = params?.noFocus ?? false;
+
+ const matchToMove = this._findNextMatch(loop, stayIfOnMatch);
+ if (matchToMove) {
+ const [match, index] = matchToMove;
+ this._matchesPosition = index + 1;
+
+ if (this._query!.findScope === FindScope.UNIT) {
+ this._activeHighlightIndex = this._matchesByWorksheet.get(match.range.subUnitId)!.findIndex((m) => m === match);
+ } else {
+ this._activeHighlightIndex = index;
+ }
+
+ if (!noFocus) this._focusMatch(match);
+ if (this._workbook.getActiveSheet().getSheetId() === match.range.subUnitId) {
+ this._updateCurrentHighlightShape(this._activeHighlightIndex);
+ }
+
+ return match;
+ }
+
+ this._matchesPosition = 0;
+ this._updateCurrentHighlightShape();
+ return null;
+ }
+
+ override moveToPreviousMatch(params?: IFindMoveParams): ISheetCellMatch | null {
+ if (!this._matches.length) {
+ return null;
+ }
+
+ const loop = params?.loop ?? false;
+ const stayIfOnMatch = params?.stayIfOnMatch ?? false;
+ const noFocus = params?.noFocus ?? false;
+
+ const matchToMove = this._findPreviousMatch(loop, stayIfOnMatch);
+ if (matchToMove) {
+ const [match, index] = matchToMove;
+ this._matchesPosition = index + 1;
+
+ if (this._query!.findScope === FindScope.UNIT) {
+ this._activeHighlightIndex = this._matchesByWorksheet.get(match.range.subUnitId)!.findIndex((m) => m === match);
+ } else {
+ this._activeHighlightIndex = index;
+ }
+
+ if (!noFocus) this._focusMatch(match);
+ if (this._workbook.getActiveSheet().getSheetId() === match.range.subUnitId) {
+ this._updateCurrentHighlightShape(this._activeHighlightIndex);
+ }
+
+ return match;
+ }
+
+ this._matchesPosition = 0;
+ this._updateCurrentHighlightShape();
+ return null;
+ }
+
+ private _findPreviousMatch(loop = false, stayIfOnMatch = false): [ISheetCellMatch, number] | null {
+ // Technically speaking, there are eight different situations!
+ // Case 1: if there is a current match and the process is very easy
+ if (this.currentMatch) {
+ const currentMatchIndex = this._matches.findIndex((match) => match === this.currentMatch);
+ if (stayIfOnMatch) {
+ return [this.currentMatch, currentMatchIndex];
+ }
+
+ const nextMatchIndex = currentMatchIndex - 1;
+ if (!loop && nextMatchIndex < 0) {
+ return null;
+ }
+
+ const length = this._matches.length;
+ const modded = (nextMatchIndex + length) % length;
+ return [this._matches[modded], modded];
+ }
+
+ // Case 2: if there is no current match, we should find the next match that is closest to the user's current selection.
+ // Still need to handle `stayInOnMatch` here.
+ const selections = this._selectionManagerService.getSelections();
+ if (!selections?.length) {
+ return [this._matches[0], 0];
+ }
+
+ if (this._query!.findScope !== FindScope.UNIT) {
+ return this._findPreviousMatchByRange(this._matches, selections[0].range);
+ }
+
+ const currentSheetId = this._workbook.getActiveSheet().getSheetId();
+ const worksheetThatHasMatch = this._findPreviousWorksheetThatHasAMatch(currentSheetId, loop);
+ if (!worksheetThatHasMatch) {
+ return null;
+ }
+
+ return this._findPreviousMatchByRange(this._matchesByWorksheet.get(worksheetThatHasMatch)!, selections[0].range);
+ }
+
+ private _findNextMatch(loop = false, stayIfOnMatch = false): [ISheetCellMatch, number] | null {
+ // Technically speaking, there are eight different situations!
+ // Case 1: if there is a current match and the process is very easy
+ if (this.currentMatch) {
+ const currentMatchIndex = this._matches.findIndex((match) => match === this.currentMatch);
+ if (stayIfOnMatch) {
+ return [this.currentMatch, currentMatchIndex];
+ }
+
+ const nextMatchIndex = currentMatchIndex + 1;
+ const length = this._matches.length;
+ if (!loop && nextMatchIndex >= length) {
+ return null;
+ }
+
+ const modded = nextMatchIndex % length; // we don't need to add length here
+ return [this._matches[modded], modded];
+ }
+
+ // Case 2: if there is no current match, we should find the next match that is closest to the user's current selection.
+ // Still need to handle `stayInOnMatch` here.
+ const selections = this._selectionManagerService.getSelections();
+ if (!selections?.length) {
+ return [this._matches[0], 0];
+ }
+
+ if (this._query!.findScope !== FindScope.UNIT) {
+ return this._findNextMatchByRange(this._matches, selections[0].range, stayIfOnMatch);
+ }
+
+ const currentSheetId = this._workbook.getActiveSheet().getSheetId();
+ const worksheetThatHasMatch = this._findNextWorksheetThatHasAMatch(currentSheetId, loop);
+ if (!worksheetThatHasMatch) {
+ return null;
+ }
+
+ return this._findNextMatchByRange(this._matchesByWorksheet.get(worksheetThatHasMatch)!, selections[0].range);
+ }
+
+ private _findPreviousWorksheetThatHasAMatch(currentWorksheet: string, loop = false): string | null {
+ const rawWorksheetsInOrder = this._workbook.getSheetOrders();
+ const currentSheetIndex = rawWorksheetsInOrder.findIndex((sheet) => sheet === currentWorksheet);
+ const worksheetsToSearch = loop
+ ? rotate(rawWorksheetsInOrder, currentSheetIndex + 1)
+ : rawWorksheetsInOrder.slice(0, currentSheetIndex + 1);
+ const first = worksheetsToSearch.findLast((worksheet) => this._matchesByWorksheet.has(worksheet));
+ return first ?? null;
+ }
+
+ private _findNextWorksheetThatHasAMatch(currentWorksheet: string, loop = false): string | null {
+ const rawWorksheetsInOrder = this._workbook.getSheetOrders();
+ const currentSheetIndex = rawWorksheetsInOrder.findIndex((sheet) => sheet === currentWorksheet);
+ const worksheetsToSearch = loop
+ ? rotate(rawWorksheetsInOrder, currentSheetIndex)
+ : rawWorksheetsInOrder.slice(currentSheetIndex);
+ const first = worksheetsToSearch.find((worksheet) => this._matchesByWorksheet.has(worksheet));
+ return first ?? null;
+ }
+
+ private _findNextMatchByRange(matches: ISheetCellMatch[], range: IRange, stayIfOnMatch = false): [ISheetCellMatch, number] {
+ const findByRow = this._query!.findDirection === FindDirection.ROW;
+ let index = matches.findIndex((match) => {
+ const matchRange = match.range.range;
+ const isBehind = findByRow ? isBehindPositionWithRowPriority(range, matchRange) : isBehindPositionWithColumnPriority(range, matchRange);
+ if (!isBehind) {
+ return false;
+ }
+
+ const isSame = isSamePosition(range, matchRange);
+ return stayIfOnMatch ? isSame : !isSame;
+ });
+
+ if (index === -1) {
+ index = matches.length - 1;
+ }
+
+ const match = matches[index];
+ return [match, this._matches.findIndex((m) => m === match)];
+ }
+
+ private _findPreviousMatchByRange(matches: ISheetCellMatch[], range: IRange, stayIfOnMatch = false): [ISheetCellMatch, number] {
+ const findByRow = this._query!.findDirection === FindDirection.ROW;
+ let index = this._matches.findLastIndex((match) => {
+ const matchRange = match.range.range;
+ const isBefore = findByRow ? isBeforePositionWithRowPriority(range, matchRange) : isBeforePositionWithColumnPriority(range, matchRange);
+ if (!isBefore) {
+ return false;
+ }
+
+ const isSame = isSamePosition(range, matchRange);
+ return stayIfOnMatch ? isSame : !isSame;
+ });
+
+ if (index === -1) {
+ index = 0;
+ }
+
+ const match = matches[index];
+ return [match, this._matches.findIndex((m) => m === match)];
+ }
+
+ async replace(replaceString: string): Promise<boolean> {
+ if (this._matchesCount === 0 || !this.currentMatch || !this._query || !this.currentMatch.replaceable) {
+ return false;
+ }
+
+ const range = this.currentMatch.range;
+ const targetWorksheet = this._workbook.getSheetBySheetId(this.currentMatch.range.subUnitId)!;
+ const newContent = this._getReplacedCellData(
+ this.currentMatch,
+ targetWorksheet,
+ this._query.findBy === FindBy.FORMULA,
+ this._query.findString,
+ replaceString,
+ this._query.caseSensitive ? 'g' : 'ig'
+ );
+
+ // for single cell replace we just use SetRangeValuesCommand directly for simplicity
+ const params: ISetRangeValuesCommandParams = {
+ unitId: this.currentMatch.unitId,
+ subUnitId: range.subUnitId,
+ value: {
+ [range.range.startRow]: {
+ [range.range.startColumn]: newContent,
+ },
+ } as IObjectMatrixPrimitiveType<ICellData>,
+ };
+
+ return this._commandService.executeCommand(SetRangeValuesCommand.id, params);
+ }
+
+ async replaceAll(replaceString: string): Promise<IReplaceAllResult> {
+ if (this._matchesCount === 0 || !this._query) {
+ return { success: 0, failure: 0 };
+ }
+
+ const unitId = this._workbook.getUnitId();
+
+ const { findString, caseSensitive, findBy } = this._query!;
+ const shouldReplaceFormula = findBy === FindBy.FORMULA;
+ const replaceFlag = caseSensitive ? 'g' : 'ig';
+
+ const replacements: ISheetReplacement[] = [];
+ const matchesByWorksheet = groupBy(this._matches.filter((m) => m.replaceable), (match) => match.range.subUnitId);
+ matchesByWorksheet.forEach((matches, subUnitId) => {
+ const matrix = new ObjectMatrix<ICellData>();
+ const worksheet = this._workbook.getSheetBySheetId(subUnitId)!;
+
+ matches.forEach((match) => {
+ const { startColumn, startRow } = match.range.range;
+ const newCellData = this._getReplacedCellData(match, worksheet, shouldReplaceFormula, findString, replaceString!, replaceFlag);
+ if (newCellData) {
+ matrix.setValue(startRow, startColumn, newCellData);
+ }
+ });
+
+ replacements.push({
+ count: matches.length,
+ subUnitId,
+ value: matrix.getMatrix(),
+ });
+ });
+
+ if (!replacements) {
+ return { success: 0, failure: 0 };
+ }
+
+ return this._commandService.executeCommand(SheetReplaceCommand.id, {
+ unitId,
+ replacements,
+ } as ISheetReplaceCommandParams);
+ }
+
+ private _getReplacedCellData(
+ match: ISheetCellMatch,
+ worksheet: Worksheet,
+ shouldReplaceFormula: boolean,
+ findString: string,
+ replaceString: string,
+ replaceFlag: string
+ ): Nullable<ICellData> {
+ const range = match.range.range;
+ const { startRow, startColumn } = range;
+
+ const currentContent = worksheet.getCellRaw(startRow, startColumn)!;
+ // TODO: should not get it again, just hook to match item
+
+ // replace formula
+ if (match.isFormula) {
+ if (!shouldReplaceFormula) {
+ return null;
+ }
+
+ const newContent = currentContent!.f!.replace(new RegExp(escapeRegExp(findString), replaceFlag), replaceString);
+ return { f: newContent, v: null };
+ }
+
+ // replace rich format text
+ const isRichText = !!currentContent.p?.body;
+ if (isRichText) {
+ const clonedRichText = Tools.deepClone(currentContent.p!);
+ replaceInDocumentBody(clonedRichText.body!, findString, replaceString);
+ return { p: clonedRichText };
+ }
+
+ // replace plain text string
+ const newContent = currentContent.v!.toString().replace(new RegExp(escapeRegExp(findString), replaceFlag), replaceString!);
+ return { v: newContent };
+ }
+}
+
+function escapeRegExp(text: string) {
+ return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
+}
+
+/**
+ * This module is responsible for searching and replacing in the sheets.
+ * It also adds the search results to the search view by highlighting them.
+ */
+class SheetsFindReplaceProvider extends Disposable implements IFindReplaceProvider {
+ /**
+ * Hold all find results in this kind of univer business instances (Workbooks).
+ */
+ private readonly _findModelsByUnitId = new Map<string, SheetFindModel>();
+
+ constructor(
+ @IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService,
+ @Inject(Injector) private readonly _injector: Injector
+ ) {
+ super();
+ }
+
+ async find(query: IFindQuery): Promise<SheetFindModel[]> {
+ this._terminate();
+
+ // NOTE: If there are multi Workbook instances then we should create `SheetFindModel` for each of them.
+ // But we don't need to implement that in the foreseeable future.
+ const currentWorkbook = this._univerInstanceService.getCurrentUniverSheetInstance();
+ if (currentWorkbook) {
+ const sheetFind = this._injector.createInstance(SheetFindModel, currentWorkbook);
+ this._findModelsByUnitId.set(currentWorkbook.getUnitId(), sheetFind);
+ const parsedQuery = this._preprocessQuery(query);
+ sheetFind.start(parsedQuery);
+ return [sheetFind];
+ }
+
+ return [];
+ }
+
+ terminate(): void {
+ this._terminate();
+ }
+
+ private _terminate(): void {
+ this._findModelsByUnitId.forEach((model) => model.dispose());
+ this._findModelsByUnitId.clear();
+ }
+
+ /**
+ * Parsed the query object before do actual searching in favor of performance.
+ * @param query the raw query object
+ * @returns the parsed query object
+ */
+ private _preprocessQuery(query: Readonly<IFindQuery>): IFindQuery {
+ let findString = query.caseSensitive
+ ? query.findString
+ : query.findString.toLowerCase();
+
+ findString = findString.trim();
+
+ return {
+ ...query,
+ findString,
+ };
+ }
+}
+
+// Use this object to pass results in avoid of GC.
+interface IValuePassingObject {
+ hit: boolean;
+ replaceable: boolean;
+ isFormula: boolean;
+ rawData: Nullable<ICellData>;
+}
+const VALUE_PASSING_OBJECT: IValuePassingObject = { hit: false, replaceable: false, isFormula: false, rawData: null };
+
+/**
+ * This function determines if a cell's content matches what is searched for.
+ * @param worksheet worksheet the Worksheet to search
+ * @param row the row index
+ * @param col the column index
+ * @param query the parsed query object
+ * @returns if the cell is hit, replaceable and is a formula
+ */
+export function hitCell(worksheet: Worksheet, row: number, col: number, query: IFindQuery, cellData: ICellData): IValuePassingObject {
+ const { findBy } = query;
+ const findByFormula = findBy === FindBy.FORMULA;
+
+ const rawData = worksheet.getCellRaw(row, col);
+ VALUE_PASSING_OBJECT.rawData = rawData;
+
+ // Deal with formula searching first.
+ const hasFormula = !!rawData?.f;
+ if (hasFormula) {
+ VALUE_PASSING_OBJECT.isFormula = true;
+
+ // For formula, it is only replaceable when it matches the raw formula.
+ if (findByFormula) {
+ const formulaMatch = matchCellData({ v: rawData.f! }, query);
+ if (formulaMatch) {
+ VALUE_PASSING_OBJECT.hit = true;
+ VALUE_PASSING_OBJECT.replaceable = true;
+ return VALUE_PASSING_OBJECT;
+ }
+
+ VALUE_PASSING_OBJECT.hit = false;
+ VALUE_PASSING_OBJECT.replaceable = false;
+ return VALUE_PASSING_OBJECT;
+ }
+
+ // Otherwise, no matter it matches the result value, it should be unreplaceable.
+ VALUE_PASSING_OBJECT.replaceable = false;
+ if (matchCellData(cellData, query)) {
+ VALUE_PASSING_OBJECT.hit = true;
+ } else {
+ VALUE_PASSING_OBJECT.hit = false;
+ }
+
+ return VALUE_PASSING_OBJECT;
+ }
+
+ // If the cell does not match, we should not check the raw data.
+ VALUE_PASSING_OBJECT.isFormula = false;
+ if (!matchCellData(cellData, query)) {
+ VALUE_PASSING_OBJECT.hit = false;
+ VALUE_PASSING_OBJECT.replaceable = false;
+ } else if (!rawData) {
+ VALUE_PASSING_OBJECT.hit = true;
+ VALUE_PASSING_OBJECT.replaceable = false;
+ } else {
+ VALUE_PASSING_OBJECT.hit = true;
+ VALUE_PASSING_OBJECT.replaceable = true;
+ }
+
+ return VALUE_PASSING_OBJECT;
+}
+
+function matchCellData(cellData: ICellData, query: IFindQuery): boolean {
+ let 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;
+ }
+ return query.caseSensitive
+ ? value.indexOf(query.findString) > -1
+ : value.toLowerCase().indexOf(query.findString) > -1;
+}
+
+function extractPureValue(cell: ICellData): Nullable<string> {
+ const rawValue = cell?.p?.body?.dataStream ?? cell?.v;
+
+ if (typeof rawValue === 'number') {
+ return `${rawValue}`;
+ }
+
+ if (typeof rawValue === 'boolean') {
+ return rawValue ? '1' : '0';
+ }
+
+ 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
+}
diff --git a/packages/sheets-find-replace/src/controllers/utils.ts b/packages/sheets-find-replace/src/controllers/utils.ts
index f15ed35469..b2657741dc 100644
--- a/packages/sheets-find-replace/src/controllers/utils.ts
+++ b/packages/sheets-find-replace/src/controllers/utils.ts
@@ -14,7 +14,8 @@
* limitations under the License.
*/
-import type { IRange } from '@univerjs/core';
+import { type IRange, Rectangle, type Worksheet } from '@univerjs/core';
+import type { ISelectionWithStyle } from '@univerjs/sheets';
export function isSamePosition(range1: IRange, range2: IRange): boolean {
return range1.startRow === range2.startRow && range1.startColumn === range2.startColumn;
@@ -65,3 +66,15 @@ export function isBeforePositionWithColumnPriority(range1: IRange, range2: IRang
(range1.startColumn === range2.startColumn && range1.startRow >= range2.startRow)
);
}
+
+export function isSelectionSingleCell(selection: ISelectionWithStyle, worksheet: Worksheet): boolean {
+ const { range } = selection;
+ const { startRow, startColumn } = range;
+ const hasMergedCell = worksheet.getMergedCell(startRow, startColumn);
+
+ if (hasMergedCell) {
+ return Rectangle.equals(range, hasMergedCell);
+ } else {
+ return range.endRow === range.startRow && range.endColumn === range.startColumn;
+ }
+}
diff --git a/packages/sheets-find-replace/src/index.ts b/packages/sheets-find-replace/src/index.ts
index 3faf1bd5b9..d0c0724c90 100644
--- a/packages/sheets-find-replace/src/index.ts
+++ b/packages/sheets-find-replace/src/index.ts
@@ -15,4 +15,4 @@
*/
export { enUS, zhCN } from './locale';
-export { UniverSheetsFindPlugin } from './plugin';
+export { UniverSheetsFindReplacePlugin } from './plugin';
diff --git a/packages/sheets-find-replace/src/locale/en-US.ts b/packages/sheets-find-replace/src/locale/en-US.ts
index 39f717c17b..cdaaecfe9c 100644
--- a/packages/sheets-find-replace/src/locale/en-US.ts
+++ b/packages/sheets-find-replace/src/locale/en-US.ts
@@ -15,72 +15,10 @@
*/
export default {
- find: {
- findLabel: 'Find and replace',
- find: 'Find',
- advanced: 'Advanced Find',
- replace: 'Replace',
- replaceWith: 'Replace With',
- goto: 'Go to',
- location: 'Location',
- formula: 'Formula',
- date: 'Date',
- number: 'Number',
- string: 'String',
- error: 'Error',
- condition: 'Condition',
- rowSpan: 'Row span',
- columnSpan: 'Column span',
- locationExample: 'Location',
- lessTwoRowTip: 'Please select at least two rows',
- lessTwoColumnTip: 'Please select at least two columns',
-
- findTextbox: 'Find Content',
- replaceTextbox: 'Replace Content',
- search: 'Search',
- matchCase: 'Match case',
- matchAll: 'Match entire cell contents',
- matchInFormula: 'Also search within formulas',
-
- regexTextbox: 'Regular Expression',
- wholeTextbox: 'Whole word',
- distinguishTextbox: 'Case sensitive',
-
- allReplaceBtn: 'Replace All',
- replaceBtn: 'Replace',
- allFindBtn: 'Find All',
- findBtn: 'Find next',
-
- noFindTip: 'The content was not found',
- modeTip: 'This operation is not available in this mode',
-
- searchTargetSheet: 'Sheet',
- specific: 'Specific range',
- searchAll: 'All sheets',
- searchTargetCell: 'Cell',
- searchTargetValue: 'Value',
-
- searchInputTip: 'Please enter the search content',
-
- noReplceTip: 'There is nothing to replace',
- noMatchTip: 'No match found',
-
- // successTip: "${xlength} items found",
-
- locationConstant: 'Const',
- locationFormula: 'Formula',
- locationDate: 'Date',
- locationDigital: 'Number',
- locationString: 'String',
- locationBool: 'Logical',
- locationError: 'Error',
- locationNull: 'Null',
- locationCondition: 'Conditional format',
- locationRowSpan: 'Row span',
- locationColumnSpan: 'Column span',
-
- locationTiplessTwoRow: 'Please select at least two rows',
- locationTiplessTwoColumn: 'Please select at least two columns',
- locationTipNotFindCell: 'Cell not found',
+ 'sheet-find-replace': {
+ replace: {
+ 'partial-failure': 'Failed to replace some cells',
+ failure: 'Failed to replace all cells',
+ },
},
};
diff --git a/packages/sheets-find-replace/src/locale/zh-CN.ts b/packages/sheets-find-replace/src/locale/zh-CN.ts
index bd6841d2ca..18af51dd87 100644
--- a/packages/sheets-find-replace/src/locale/zh-CN.ts
+++ b/packages/sheets-find-replace/src/locale/zh-CN.ts
@@ -15,72 +15,10 @@
*/
export default {
- find: {
- findLabel: '查找替换',
- find: '查找',
- advanced: '高级查找',
- replace: '替换',
- replaceWith: '替换为',
- goto: '转到',
- location: '定位条件',
- formula: '公式',
- date: '日期',
- number: '数字',
- string: '字符',
- error: '错误',
- condition: '条件格式',
- rowSpan: '间隔行',
- columnSpan: '间隔列',
- locationExample: '定位',
- lessTwoRowTip: '请选择最少两行',
- lessTwoColumnTip: '请选择最少两行',
-
- findTextbox: '查找内容',
- replaceTextbox: '替换内容',
-
- regexTextbox: '正则表达式匹配',
- wholeTextbox: '整词匹配',
- distinguishTextbox: '区分大小写匹配',
- matchCase: '匹配大小写',
- matchAll: '匹配整个单元格内容',
- matchInFormula: '也在公式中搜索',
-
- allReplaceBtn: '全部替换',
- replaceBtn: '替换',
- allFindBtn: '查找全部',
- findBtn: '查找下一个',
-
- noFindTip: '没有查找到该内容',
- modeTip: '该模式下不可进行此操作',
-
- searchTargetSheet: '工作表',
- specific: '具体范围',
- searchAll: '所有工作表',
- searchTargetCell: '单元格',
- searchTargetValue: '值',
-
- searchInputTip: '请输入查找内容',
-
- noReplceTip: '没有可替换的内容',
- noMatchTip: '找不到匹配项',
- search: '搜索',
-
- // successTip: '已经帮您搜索并进行了${xlength}处替换',
-
- locationConstant: '常量',
- locationFormula: '公式',
- locationDate: '日期',
- locationDigital: '数字',
- locationString: '字符',
- locationBool: '逻辑值',
- locationError: '错误',
- locationNull: '空值',
- locationCondition: '条件格式',
- locationRowSpan: '间隔行',
- locationColumnSpan: '间隔列',
-
- locationTiplessTwoRow: '请选择最少两行',
- locationTiplessTwoColumn: '请选择最少两列',
- locationTipNotFindCell: '未找到单元格',
+ 'sheet-find-replace': {
+ replace: {
+ 'partial-failure': '部分单元格替换失败',
+ failure: '替换失败',
+ },
},
};
diff --git a/packages/sheets-find-replace/src/plugin.ts b/packages/sheets-find-replace/src/plugin.ts
index e154f26834..3b3c4cd83a 100644
--- a/packages/sheets-find-replace/src/plugin.ts
+++ b/packages/sheets-find-replace/src/plugin.ts
@@ -18,13 +18,13 @@ import { Plugin, PluginType } from '@univerjs/core';
import type { Dependency } from '@wendellhu/redi';
import { Inject, Injector } from '@wendellhu/redi';
-import { SheetsFindReplaceController } from './controllers/find-replace.controller';
+import { SheetsFindReplaceController } from './controllers/sheet-find-replace.controller';
export interface IFindPluginConfig {}
const NAME = 'UNIVER_SHEETS_FIND_REPLACE_PLUGIN';
-export class UniverSheetsFindPlugin extends Plugin {
+export class UniverSheetsFindReplacePlugin extends Plugin {
static override type = PluginType.Sheet;
constructor(
diff --git a/packages/sheets-find-replace/src/views/shapes/find-replace-highlight.shape.ts b/packages/sheets-find-replace/src/views/shapes/find-replace-highlight.shape.ts
index 662b05bcfa..8f0f3edbd3 100644
--- a/packages/sheets-find-replace/src/views/shapes/find-replace-highlight.shape.ts
+++ b/packages/sheets-find-replace/src/views/shapes/find-replace-highlight.shape.ts
@@ -14,15 +14,20 @@
* limitations under the License.
*/
+import type { IRgbColor, Nullable } from '@univerjs/core';
import type { IShapeProps, UniverRenderingContext } from '@univerjs/engine-render';
import { Rect, Shape } from '@univerjs/engine-render';
export interface ISheetFindReplaceHighlightShapeProps extends IShapeProps {
+ inHiddenRange: boolean;
+ color: IRgbColor;
activated?: boolean;
}
export class SheetFindReplaceHighlightShape extends Shape<ISheetFindReplaceHighlightShapeProps> {
protected _activated = false;
+ protected _inHiddenRange = false;
+ protected _color: Nullable<IRgbColor>;
constructor(key?: string, props?: ISheetFindReplaceHighlightShapeProps) {
super(key, props);
@@ -35,6 +40,14 @@ export class SheetFindReplaceHighlightShape extends Shape<ISheetFindReplaceHighl
setShapeProps(props: Partial<ISheetFindReplaceHighlightShapeProps>): void {
this._activated = !!props.activated;
+ if (typeof props.inHiddenRange !== 'undefined') {
+ this._inHiddenRange = props.inHiddenRange;
+ }
+
+ if (typeof props.color !== 'undefined') {
+ this._color = props.color;
+ }
+
this.transformByState({
width: props.width!,
height: props.height!,
@@ -42,10 +55,16 @@ export class SheetFindReplaceHighlightShape extends Shape<ISheetFindReplaceHighl
}
protected override _draw(ctx: CanvasRenderingContext2D): void {
+ const activated = this._activated;
+ const color = `rgba(${this._color!.r}, ${this._color!.g}, ${this._color!.b}, 0.35)`;
+ const borderColor = `rgb(${this._color!.r}, ${this._color!.g}, ${this._color!.b})`;
+
Rect.drawWith(ctx as UniverRenderingContext, {
width: this.width,
height: this.height,
- fill: 'rgba(89, 208, 30, 0.2)',
+ fill: color,
+ stroke: activated ? borderColor : undefined,
+ strokeWidth: activated ? 2 : 0,
evented: false,
});
}
diff --git a/packages/sheets-find-replace/vite.config.ts b/packages/sheets-find-replace/vite.config.ts
index 67b2fff8f2..e38cd8530b 100644
--- a/packages/sheets-find-replace/vite.config.ts
+++ b/packages/sheets-find-replace/vite.config.ts
@@ -4,4 +4,9 @@ import pkg from './package.json';
export default ({ mode }) => createViteConfig({}, {
mode,
pkg,
+ features: {
+ react: true,
+ css: true,
+ dom: true,
+ },
});
diff --git a/packages/sheets-ui/src/commands/commands/auto-fill.command.ts b/packages/sheets-ui/src/commands/commands/auto-fill.command.ts
index 644f356ec9..8782584de7 100644
--- a/packages/sheets-ui/src/commands/commands/auto-fill.command.ts
+++ b/packages/sheets-ui/src/commands/commands/auto-fill.command.ts
@@ -84,12 +84,6 @@ export const AutoClearContentCommand: ICommand = {
unitID: unitId,
undoMutations: [{ id: SetRangeValuesMutation.id, params: undoClearMutationParams }],
redoMutations: [{ id: SetRangeValuesMutation.id, params: clearMutationParams }],
- undo() {
- return commandService.syncExecuteCommand(SetRangeValuesMutation.id, undoClearMutationParams);
- },
- redo() {
- return commandService.syncExecuteCommand(SetRangeValuesMutation.id, clearMutationParams);
- },
});
return true;
diff --git a/packages/sheets-ui/src/commands/commands/set-scroll.command.ts b/packages/sheets-ui/src/commands/commands/set-scroll.command.ts
index 638facd891..12be8066a6 100644
--- a/packages/sheets-ui/src/commands/commands/set-scroll.command.ts
+++ b/packages/sheets-ui/src/commands/commands/set-scroll.command.ts
@@ -14,18 +14,12 @@
* limitations under the License.
*/
-import type { ICommand } from '@univerjs/core';
+import type { ICommand, IRange } from '@univerjs/core';
import { CommandType, ICommandService, IUniverInstanceService } from '@univerjs/core';
import { ScrollManagerService } from '../../services/scroll-manager.service';
import { SetScrollOperation } from '../operations/scroll.operation';
-
-export interface IScrollCommandParams {
- offsetX?: number;
- offsetY?: number;
- sheetViewStartRow?: number;
- sheetViewStartColumn?: number;
-}
+import { ScrollController } from '../../controllers/scroll.controller';
export interface ISetScrollRelativeCommandParams {
offsetX?: number;
@@ -65,29 +59,35 @@ export const SetScrollRelativeCommand: ICommand<ISetScrollRelativeCommandParams>
},
};
+export interface IScrollCommandParams {
+ offsetX?: number;
+ offsetY?: number;
+ sheetViewStartRow?: number;
+ sheetViewStartColumn?: number;
+}
+
/**
* This command is used to manage the scroll position of the current view by specifying the cell index of the top left cell
*/
export const ScrollCommand: ICommand<IScrollCommandParams> = {
id: 'sheet.command.scroll-view',
type: CommandType.COMMAND,
- handler: async (accessor, params) => {
+ handler: (accessor, params) => {
if (!params) {
return false;
}
+
const univerInstanceService = accessor.get(IUniverInstanceService);
+ const scrollManagerService = accessor.get(ScrollManagerService);
const currentWorkbook = univerInstanceService.getCurrentUniverSheetInstance();
const currentWorksheet = currentWorkbook.getActiveSheet();
- const scrollManagerService = accessor.get(ScrollManagerService);
const currentScroll = scrollManagerService.getCurrentScroll();
if (!currentWorksheet) {
return false;
}
- const commandService = accessor.get(ICommandService);
-
const { sheetViewStartRow, sheetViewStartColumn, offsetX, offsetY } = params;
const {
sheetViewStartColumn: currentColumn,
@@ -98,7 +98,8 @@ export const ScrollCommand: ICommand<IScrollCommandParams> = {
const { xSplit, ySplit } = currentWorksheet.getConfig().freeze;
- return commandService.executeCommand(SetScrollOperation.id, {
+ const commandService = accessor.get(ICommandService);
+ return commandService.syncExecuteCommand(SetScrollOperation.id, {
unitId: currentWorkbook.getUnitId(),
sheetId: currentWorksheet.getSheetId(),
sheetViewStartRow: sheetViewStartRow ?? (currentRow ?? 0) + ySplit,
@@ -109,10 +110,26 @@ export const ScrollCommand: ICommand<IScrollCommandParams> = {
},
};
+export interface IScrollToCellCommandParams {
+ range: IRange;
+}
+
+/**
+ * The command is used to scroll to the specific cell if the target cell is not in the viewport.
+ */
+export const ScrollToCellCommand: ICommand<IScrollToCellCommandParams> = {
+ id: 'sheet.command.scroll-to-cell',
+ type: CommandType.COMMAND,
+ handler: (accessor, params) => {
+ const scrollController = accessor.get(ScrollController);
+ return scrollController.scrollToRange(params!.range);
+ },
+};
+
/**
* This command is reset the scroll position of the current view to 0, 0
*/
-export const RestScrollCommand: ICommand<{}> = {
+export const ResetScrollCommand: ICommand = {
id: 'sheet.command.scroll-view-reset',
type: CommandType.COMMAND,
handler: async (accessor) => {
diff --git a/packages/sheets-ui/src/controllers/active-worksheet/active-worksheet.controller.ts b/packages/sheets-ui/src/controllers/active-worksheet/active-worksheet.controller.ts
index 3366bef2f6..0356ac0d3b 100644
--- a/packages/sheets-ui/src/controllers/active-worksheet/active-worksheet.controller.ts
+++ b/packages/sheets-ui/src/controllers/active-worksheet/active-worksheet.controller.ts
@@ -45,7 +45,7 @@ export class ActiveWorksheetController extends Disposable {
super();
this.disposeWithMe(
- this._commandService.beforeCommandExecuted((command, options) => {
+ this._commandService.beforeCommandExecuted((command) => {
if (command.id === RemoveSheetMutation.id) {
return this._beforeAdjustActiveSheetOnRemoveSheet(
command as IMutationInfo<IRemoveSheetMutationParams>
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.ts
index 2e415dcbf7..fda9abfabf 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
@@ -15,7 +15,7 @@
*/
import type { IDocumentData, Univer, Workbook } from '@univerjs/core';
-import { LocaleService } from '@univerjs/core';
+import { IContextService, LocaleService } from '@univerjs/core';
import { LexerTreeBuilder } from '@univerjs/engine-formula';
import { SpreadsheetSkeleton } from '@univerjs/engine-render';
import type { Injector } from '@wendellhu/redi';
@@ -74,6 +74,7 @@ describe('Test EndEditController', () => {
let workbook: Workbook;
let get: Injector['get'];
let localeService: LocaleService;
+ let contextService: IContextService;
let lexerTreeBuilder: LexerTreeBuilder;
let spreadsheetSkeleton: SpreadsheetSkeleton;
@@ -85,6 +86,7 @@ describe('Test EndEditController', () => {
get = testBed.get;
localeService = get(LocaleService);
+ contextService = get(IContextService);
lexerTreeBuilder = new LexerTreeBuilder();
const worksheet = workbook.getActiveSheet();
@@ -94,7 +96,8 @@ describe('Test EndEditController', () => {
config,
worksheet.getCellMatrix(),
workbook.getStyles(),
- localeService
+ localeService,
+ contextService
);
});
diff --git a/packages/sheets-ui/src/controllers/navigation/navigation.controller.ts b/packages/sheets-ui/src/controllers/navigation/navigation.controller.ts
deleted file mode 100644
index 0e5cbbbcba..0000000000
--- a/packages/sheets-ui/src/controllers/navigation/navigation.controller.ts
+++ /dev/null
@@ -1,41 +0,0 @@
-/**
- * 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 { Disposable, ICommandService, LifecycleStages, OnLifecycle } from '@univerjs/core';
-import { Inject } from '@wendellhu/redi';
-
-import { MoveSelectionCommand, MoveSelectionEnterAndTabCommand } from '../../commands/commands/set-selection.command';
-import { ScrollController } from '../scroll.controller';
-
-const SHEET_NAVIGATION_COMMANDS = [MoveSelectionCommand.id, MoveSelectionEnterAndTabCommand.id];
-
-@OnLifecycle(LifecycleStages.Rendered, SheetNavigationController)
-export class SheetNavigationController extends Disposable {
- constructor(
- @ICommandService private readonly _commandService: ICommandService,
- @Inject(ScrollController) private readonly _scrollController: ScrollController
- ) {
- super();
-
- this.disposeWithMe(
- this._commandService.onCommandExecuted((command) => {
- if (SHEET_NAVIGATION_COMMANDS.includes(command.id)) {
- this._scrollController.scrollToVisible();
- }
- })
- );
- }
-}
diff --git a/packages/sheets-ui/src/controllers/scroll.controller.ts b/packages/sheets-ui/src/controllers/scroll.controller.ts
index 96e645dec0..5342af2767 100644
--- a/packages/sheets-ui/src/controllers/scroll.controller.ts
+++ b/packages/sheets-ui/src/controllers/scroll.controller.ts
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-import type { IWorksheetData } from '@univerjs/core';
+import type { IFreeze, IRange, IWorksheetData, Nullable } from '@univerjs/core';
import {
Disposable,
ICommandService,
@@ -32,8 +32,14 @@ import { VIEWPORT_KEY } from '../common/keys';
import { ScrollManagerService } from '../services/scroll-manager.service';
import type { ISheetSkeletonManagerParam } from '../services/sheet-skeleton-manager.service';
import { SheetSkeletonManagerService } from '../services/sheet-skeleton-manager.service';
+import { MoveSelectionCommand, MoveSelectionEnterAndTabCommand } from '../commands/commands/set-selection.command';
import { getSheetObject } from './utils/component-tools';
+const SHEET_NAVIGATION_COMMANDS = [MoveSelectionCommand.id, MoveSelectionEnterAndTabCommand.id];
+
+/**
+ * This controller handles scroll logic in sheet interaction.
+ */
@OnLifecycle(LifecycleStages.Rendered, ScrollController)
export class ScrollController extends Disposable {
constructor(
@@ -46,136 +52,41 @@ export class ScrollController extends Disposable {
) {
super();
- this._initialize();
- }
-
- scrollToVisible(targetIsActualRowAndColumn = true) {
- let startSheetViewRow;
- let startSheetViewColumn;
- const selection = this._selectionManagerService.getLast();
- if (selection == null) {
- return;
- }
-
- const { startRow, startColumn, actualRow, actualColumn } = selection.primary;
- const selectionStartRow = targetIsActualRowAndColumn ? actualRow : startRow;
- const selectionStartColumn = targetIsActualRowAndColumn ? actualColumn : startColumn;
- const { rowHeightAccumulation, columnWidthAccumulation } =
- this._sheetSkeletonManagerService.getCurrent()?.skeleton ?? {};
-
- if (rowHeightAccumulation == null || columnWidthAccumulation == null) {
- return;
- }
-
- const scene = this._getSheetObject()?.scene;
- if (scene == null) {
- return;
- }
-
- const viewport = scene.getViewport(VIEWPORT_KEY.VIEW_MAIN);
- if (viewport == null) {
- return;
- }
-
- const sheetObject = this._getSheetObject();
- if (sheetObject == null) {
- return;
- }
-
- const worksheet = this._currentUniverService.getCurrentUniverSheetInstance().getActiveSheet();
- const {
- startColumn: freezeStartColumn,
- startRow: freezeStartRow,
- ySplit: freezeYSplit,
- xSplit: freezeXSplit,
- } = worksheet.getFreeze();
-
- const bounds = viewport.getBounding();
- const skeleton = this._sheetSkeletonManagerService.getCurrent()?.skeleton;
- if (skeleton == null) {
- return;
- }
-
- const {
- startRow: viewportStartRow,
- startColumn: viewportStartColumn,
- endRow: viewportEndRow,
- endColumn: viewportEndColumn,
- } = skeleton.getRowColumnSegment(bounds);
-
- // vertical overflow only happens when the selection's row is in not the freeze area
- if (selectionStartRow >= freezeStartRow && selectionStartColumn >= freezeStartColumn - freezeXSplit) {
- // top overflow
- if (selectionStartRow <= viewportStartRow) {
- startSheetViewRow = selectionStartRow;
- }
-
- // bottom overflow
- if (selectionStartRow >= viewportEndRow) {
- const minRowAccumulation = rowHeightAccumulation[selectionStartRow] - viewport.height!;
- for (let r = viewportStartRow; r <= selectionStartRow; r++) {
- if (rowHeightAccumulation[r] >= minRowAccumulation) {
- startSheetViewRow = r + 1;
- break;
- }
- }
- }
- }
- // horizontal overflow only happens when the selection's column is in not the freeze area
- if (selectionStartColumn >= freezeStartColumn && selectionStartRow >= freezeStartRow - freezeYSplit) {
- // left overflow
- if (selectionStartColumn <= viewportStartColumn) {
- startSheetViewColumn = selectionStartColumn;
- }
-
- // right overflow
- if (selectionStartColumn >= viewportEndColumn) {
- const minColumnAccumulation = columnWidthAccumulation[selectionStartColumn] - viewport.width!;
- for (let c = viewportStartColumn; c <= selectionStartColumn; c++) {
- if (columnWidthAccumulation[c] >= minColumnAccumulation) {
- startSheetViewColumn = c + 1;
- break;
- }
- }
- }
- }
-
- if (startSheetViewRow === undefined && startSheetViewColumn === undefined) {
- return;
- }
- const { offsetX, offsetY } = this._scrollManagerService.getCurrentScroll() || {};
-
- this._commandService.executeCommand(ScrollCommand.id, {
- sheetViewStartRow: startSheetViewRow,
- sheetViewStartColumn: startSheetViewColumn,
- offsetX: startSheetViewColumn === undefined ? offsetX : 0,
- offsetY: startSheetViewRow === undefined ? offsetY : 0,
- });
+ this._init();
}
- override dispose(): void {
- super.dispose();
+ scrollToRange(range: IRange): boolean {
+ const { startRow, startColumn } = range;
+ return this._scrollToCell(startRow, startColumn);
}
- private _initialize() {
- this._scrollEventBinding();
+ private _init() {
+ this._initCommandListener();
+ this._initScrollEventListener();
this._scrollSubscribeBinding();
- this._skeletonListener();
+ this._initSkeletonListener();
}
- private _getFreeze() {
- const config: IWorksheetData | undefined = this._sheetSkeletonManagerService
- .getCurrent()
- ?.skeleton.getWorksheetConfig();
+ private _initCommandListener(): void {
+ this.disposeWithMe(
+ this._commandService.onCommandExecuted((command) => {
+ if (SHEET_NAVIGATION_COMMANDS.includes(command.id)) {
+ this._scrollToSelection();
+ }
+ })
+ );
+ }
- if (config == null) {
+ private _getFreeze(): Nullable<IFreeze> {
+ const snapshot: IWorksheetData | undefined = this._sheetSkeletonManagerService.getCurrent()?.skeleton.getWorksheetConfig();
+ if (snapshot == null) {
return;
}
- return config.freeze;
+ return snapshot.freeze;
}
- private _scrollEventBinding() {
+ private _initScrollEventListener() {
const scene = this._getSheetObject()?.scene;
if (scene == null) {
return;
@@ -291,38 +202,36 @@ export class ScrollController extends Disposable {
);
}
- private _skeletonListener() {
- this.disposeWithMe(
- toDisposable(
- this._sheetSkeletonManagerService.currentSkeleton$.subscribe((param) => {
- if (param == null) {
- return;
- }
- const { unitId, sheetId } = param;
+ private _initSkeletonListener() {
+ this.disposeWithMe(toDisposable(
+ this._sheetSkeletonManagerService.currentSkeleton$.subscribe((param) => {
+ if (param == null) {
+ return;
+ }
- const currentRender = this._renderManagerService.getRenderById(unitId);
+ const { unitId, sheetId } = param;
+ const currentRender = this._renderManagerService.getRenderById(unitId);
- if (currentRender == null) {
- return;
- }
+ if (currentRender == null) {
+ return;
+ }
- this._updateSceneSize(param);
+ this._updateSceneSize(param);
- this._scrollManagerService.setCurrentScroll({
- unitId,
- sheetId,
- });
- })
- )
- );
+ this._scrollManagerService.setCurrentScroll({
+ unitId,
+ sheetId,
+ });
+ })
+ ));
}
private _updateSceneSize(param: ISheetSkeletonManagerParam) {
if (param == null) {
return;
}
- const { skeleton, unitId } = param;
+ const { skeleton, unitId } = param;
const scene = this._renderManagerService.getRenderById(unitId)?.scene;
if (skeleton == null || scene == null) {
@@ -341,4 +250,113 @@ export class ScrollController extends Disposable {
private _getSheetObject() {
return getSheetObject(this._currentUniverService, this._renderManagerService);
}
+
+ private _scrollToSelection(targetIsActualRowAndColumn = true) {
+ const selection = this._selectionManagerService.getLast();
+ if (selection == null) {
+ return;
+ }
+
+ const { startRow, startColumn, actualRow, actualColumn } = selection.primary;
+ const selectionStartRow = targetIsActualRowAndColumn ? actualRow : startRow;
+ const selectionStartColumn = targetIsActualRowAndColumn ? actualColumn : startColumn;
+
+ this._scrollToCell(selectionStartRow, selectionStartColumn);
+ }
+
+ private _scrollToCell(row: number, column: number): boolean {
+ const { rowHeightAccumulation, columnWidthAccumulation } = this._sheetSkeletonManagerService.getCurrent()?.skeleton ?? {};
+
+ if (rowHeightAccumulation == null || columnWidthAccumulation == null) {
+ return false;
+ }
+
+ const scene = this._getSheetObject()?.scene;
+ if (scene == null) {
+ return false;
+ }
+
+ const viewport = scene.getViewport(VIEWPORT_KEY.VIEW_MAIN);
+ if (viewport == null) {
+ return false;
+ }
+
+ const sheetObject = this._getSheetObject();
+ if (sheetObject == null) {
+ return false;
+ }
+
+ const skeleton = this._sheetSkeletonManagerService.getCurrent()?.skeleton;
+ if (skeleton == null) {
+ return false;
+ }
+
+ const worksheet = this._currentUniverService.getCurrentUniverSheetInstance().getActiveSheet();
+ const {
+ startColumn: freezeStartColumn,
+ startRow: freezeStartRow,
+ ySplit: freezeYSplit,
+ xSplit: freezeXSplit,
+ } = worksheet.getFreeze();
+
+ const bounds = viewport.getBounding();
+ const {
+ startRow: viewportStartRow,
+ startColumn: viewportStartColumn,
+ endRow: viewportEndRow,
+ endColumn: viewportEndColumn,
+ } = skeleton.getRowColumnSegment(bounds);
+
+ let startSheetViewRow: number | undefined;
+ let startSheetViewColumn: number | undefined;
+
+ // vertical overflow only happens when the selection's row is in not the freeze area
+ if (row >= freezeStartRow && column >= freezeStartColumn - freezeXSplit) {
+ // top overflow
+ if (row <= viewportStartRow) {
+ startSheetViewRow = row;
+ }
+
+ // bottom overflow
+ if (row >= viewportEndRow) {
+ const minRowAccumulation = rowHeightAccumulation[row] - viewport.height!;
+ for (let r = viewportStartRow; r <= row; r++) {
+ if (rowHeightAccumulation[r] >= minRowAccumulation) {
+ startSheetViewRow = r + 1;
+ break;
+ }
+ }
+ }
+ }
+ // horizontal overflow only happens when the selection's column is in not the freeze area
+ if (column >= freezeStartColumn && row >= freezeStartRow - freezeYSplit) {
+ // left overflow
+ if (column <= viewportStartColumn) {
+ startSheetViewColumn = column;
+ }
+
+ // right overflow
+ if (column >= viewportEndColumn) {
+ const minColumnAccumulation = columnWidthAccumulation[column] - viewport.width!;
+ for (let c = viewportStartColumn; c <= column; c++) {
+ if (columnWidthAccumulation[c] >= minColumnAccumulation) {
+ startSheetViewColumn = c + 1;
+ break;
+ }
+ }
+ }
+ }
+
+ if (startSheetViewRow === undefined && startSheetViewColumn === undefined) {
+ return false;
+ }
+
+ const { offsetX, offsetY } = this._scrollManagerService.getCurrentScroll() || {};
+ return this._commandService.syncExecuteCommand(ScrollCommand.id, {
+ sheetViewStartRow: startSheetViewRow,
+ sheetViewStartColumn: startSheetViewColumn,
+ offsetX: startSheetViewColumn === undefined ? offsetX : 0,
+ offsetY: startSheetViewRow === undefined ? offsetY : 0,
+ });
+ }
}
diff --git a/packages/sheets-ui/src/controllers/sheet-render.controller.ts b/packages/sheets-ui/src/controllers/sheet-render.controller.ts
index 17ebbdf686..2ee31a85ef 100644
--- a/packages/sheets-ui/src/controllers/sheet-render.controller.ts
+++ b/packages/sheets-ui/src/controllers/sheet-render.controller.ts
@@ -19,12 +19,13 @@ import {
CommandType,
Disposable,
ICommandService,
+ IContextService,
IUniverInstanceService,
LifecycleStages,
OnLifecycle,
} from '@univerjs/core';
-import type { Rect, Spreadsheet, SpreadsheetColumnHeader, SpreadsheetRowHeader } from '@univerjs/engine-render';
-import { IRenderManagerService } from '@univerjs/engine-render';
+import type { Rect, SpreadsheetColumnHeader, SpreadsheetRowHeader } from '@univerjs/engine-render';
+import { IRenderManagerService, RENDER_RAW_FORMULA_KEY, Spreadsheet } from '@univerjs/engine-render';
import {
COMMAND_LISTENER_SKELETON_CHANGE,
COMMAND_LISTENER_VALUE_CHANGE,
@@ -32,6 +33,7 @@ import {
} from '@univerjs/sheets';
import { Inject } from '@wendellhu/redi';
+import { distinctUntilChanged } from 'rxjs';
import { SHEET_VIEW_KEY } from '../common/keys';
import { SheetSkeletonManagerService } from '../services/sheet-skeleton-manager.service';
@@ -44,26 +46,23 @@ interface ISetWorksheetMutationParams {
export class SheetRenderController extends Disposable {
constructor(
@Inject(SheetSkeletonManagerService) private readonly _sheetSkeletonManagerService: SheetSkeletonManagerService,
+ @IContextService private readonly _contextService: IContextService,
@IUniverInstanceService private readonly _currentUniverService: IUniverInstanceService,
@IRenderManagerService private readonly _renderManagerService: IRenderManagerService,
@ICommandService private readonly _commandService: ICommandService
) {
super();
- this._initialize();
-
- this._commandExecutedListener();
- }
-
- override dispose(): void {
- super.dispose();
+ this._init();
}
- private _initialize() {
+ private _init() {
this._initialRenderRefresh();
+ this._initCommandListener();
+ this._initContextListener();
}
- private _initialRenderRefresh() {
+ private _initialRenderRefresh(): void {
this.disposeWithMe(
this._sheetSkeletonManagerService.currentSkeleton$.subscribe((param) => {
if (param == null) {
@@ -106,7 +105,7 @@ export class SheetRenderController extends Disposable {
);
}
- private _commandExecutedListener() {
+ private _initCommandListener(): void {
this.disposeWithMe(
this._commandService.onCommandExecuted((command: ICommandInfo) => {
const workbook = this._currentUniverService.getCurrentUniverSheetInstance();
@@ -149,4 +148,16 @@ export class SheetRenderController extends Disposable {
})
);
}
+
+ private _initContextListener(): void {
+ this._contextService.subscribeContextValue$(RENDER_RAW_FORMULA_KEY).pipe(
+ distinctUntilChanged()
+ ).subscribe(() => {
+ this._renderManagerService.getRenderAll().forEach((renderer) => {
+ if (renderer.mainComponent instanceof Spreadsheet) {
+ renderer.mainComponent.makeForceDirty(true);
+ }
+ });
+ });
+ }
}
diff --git a/packages/sheets-ui/src/controllers/sheet-ui.controller.ts b/packages/sheets-ui/src/controllers/sheet-ui.controller.ts
index ee582db1f7..ccf4acdf7c 100644
--- a/packages/sheets-ui/src/controllers/sheet-ui.controller.ts
+++ b/packages/sheets-ui/src/controllers/sheet-ui.controller.ts
@@ -65,7 +65,7 @@ import {
SetRowFrozenCommand,
SetSelectionFrozenCommand,
} from '../commands/commands/set-frozen.command';
-import { ScrollCommand, SetScrollRelativeCommand } from '../commands/commands/set-scroll.command';
+import { ScrollCommand, ScrollToCellCommand, SetScrollRelativeCommand } from '../commands/commands/set-scroll.command';
import {
ExpandSelectionCommand,
MoveSelectionCommand,
@@ -227,17 +227,26 @@ export class SheetUIController extends Disposable {
constructor(
@Inject(Injector) private readonly _injector: Injector,
@Inject(ComponentManager) private readonly _componentManager: ComponentManager,
+ @ILayoutService private readonly _layoutService: ILayoutService,
@ICommandService private readonly _commandService: ICommandService,
@IShortcutService private readonly _shortcutService: IShortcutService,
@IMenuService private readonly _menuService: IMenuService,
- @IUIController private readonly _uiController: IDesktopUIController,
- @ILayoutService private readonly _layoutService: ILayoutService
+ @IUIController private readonly _uiController: IDesktopUIController
) {
super();
this._init();
}
+ private _init(): void {
+ this._initCustomComponents();
+ this._initCommands();
+ this._initMenus();
+ this._initShortcuts();
+ this._initWorkbenchParts();
+ this._initFocusHandler();
+ }
+
private _initCustomComponents(): void {
const componentManager = this._componentManager;
this.disposeWithMe(componentManager.register(MENU_ITEM_INPUT_COMPONENT, MenuItemInput));
@@ -265,6 +274,7 @@ export class SheetUIController extends Disposable {
HideRowConfirmCommand,
HideColConfirmCommand,
ScrollCommand,
+ ScrollToCellCommand,
SelectAllCommand,
SetActivateCellEditOperation,
SetBoldCommand,
@@ -445,26 +455,12 @@ export class SheetUIController extends Disposable {
}
private _initWorkbenchParts(): void {
- this.disposeWithMe(
- this._uiController.registerHeaderComponent(() => connectInjector(RenderSheetHeader, this._injector))
- );
+ const uc = this._uiController;
+ const j = this._injector;
- this.disposeWithMe(
- this._uiController.registerFooterComponent(() => connectInjector(RenderSheetFooter, this._injector))
- );
-
- this.disposeWithMe(
- this._uiController.registerContentComponent(() => connectInjector(RenderSheetContent, this._injector))
- );
- }
-
- private _init(): void {
- this._initCustomComponents();
- this._initCommands();
- this._initMenus();
- this._initShortcuts();
- this._initWorkbenchParts();
- this._initFocusHandler();
+ this.disposeWithMe(uc.registerHeaderComponent(() => connectInjector(RenderSheetHeader, j)));
+ this.disposeWithMe(uc.registerFooterComponent(() => connectInjector(RenderSheetFooter, j)));
+ this.disposeWithMe(uc.registerContentComponent(() => connectInjector(RenderSheetContent, j)));
}
private _initFocusHandler(): void {
diff --git a/packages/sheets-ui/src/controllers/shortcuts/utils.ts b/packages/sheets-ui/src/controllers/shortcuts/utils.ts
index 55f38dad81..aef02cda0e 100644
--- a/packages/sheets-ui/src/controllers/shortcuts/utils.ts
+++ b/packages/sheets-ui/src/controllers/shortcuts/utils.ts
@@ -30,9 +30,9 @@ export function whenSheetFocused(contextService: IContextService) {
/**
* Requires the currently focused unit to be Workbook and the sheet editor is focused but not activated.
* @param contextService
- * @returns
+ * @returns If the sheet editor is focused but not activated.
*/
-export function whenSheetEditorFocused(contextService: IContextService) {
+export function whenSheetEditorFocused(contextService: IContextService): boolean {
return (
contextService.getContextValue(FOCUSING_SHEET) &&
contextService.getContextValue(FOCUSING_UNIVER_EDITOR) &&
@@ -43,7 +43,7 @@ export function whenSheetEditorFocused(contextService: IContextService) {
/**
* Requires the currently focused unit to be Workbook and the sheet editor is activated.
* @param contextService
- * @returns
+ * @returns If the sheet editor is activated.
*/
export function whenSheetEditorActivated(contextService: IContextService) {
return (
@@ -60,7 +60,7 @@ export function whenEditorActivated(contextService: IContextService) {
/**
* Requires the currently focused editor is a formula editor.
* @param contextService
- * @returns
+ * @returns If the formula editor is focused.
*/
export function whenFormulaEditorFocused(contextService: IContextService) {
return (
@@ -72,7 +72,7 @@ export function whenFormulaEditorFocused(contextService: IContextService) {
/**
* Requires the currently focused editor is a formula editor, and it is activated.
* @param contextService
- * @returns
+ * @returns If the formula editor is activated.
*/
export function whenFormulaEditorActivated(contextService: IContextService) {
return (
@@ -83,6 +83,11 @@ export function whenFormulaEditorActivated(contextService: IContextService) {
);
}
+/**
+ * Requires the currently focused editor is not a formula editor, and it is activated.
+ * @param contextService
+ * @returns If the editor is activated and the editor is not the formula editor.
+ */
export function whenEditorDidNotInputFormulaActivated(contextService: IContextService) {
return (
contextService.getContextValue(FOCUSING_SHEET) &&
diff --git a/packages/sheets-ui/src/index.ts b/packages/sheets-ui/src/index.ts
index 3e3e9007a9..b6d26a2f72 100644
--- a/packages/sheets-ui/src/index.ts
+++ b/packages/sheets-ui/src/index.ts
@@ -20,9 +20,19 @@ export { AutoFillCommand } from './commands/commands/auto-fill.command';
export { SheetPasteCommand } from './commands/commands/clipboard.command';
export { SheetCopyCommand } from './commands/commands/clipboard.command';
export { ExpandSelectionCommand, JumpOver, MoveSelectionCommand } from './commands/commands/set-selection.command';
-export { SetCellEditVisibleArrowOperation } from './commands/operations/cell-edit.operation';
+export { SetCellEditVisibleArrowOperation, SetCellEditVisibleOperation } from './commands/operations/cell-edit.operation';
export { SetScrollOperation } from './commands/operations/scroll.operation';
+export { ScrollController } from './controllers/scroll.controller';
export { SetZoomRatioOperation } from './commands/operations/set-zoom-ratio.operation';
+export {
+ ResetScrollCommand,
+ ScrollCommand,
+ ScrollToCellCommand,
+ SetScrollRelativeCommand,
+ type IScrollCommandParams,
+ type IScrollToCellCommandParams,
+ type ISetScrollRelativeCommandParams,
+} from './commands/commands/set-scroll.command';
export { VIEWPORT_KEY } from './common/keys';
export { AutoFillController } from './controllers/auto-fill.controller';
export { PASTE_SPECIAL_MENU_ID } from './controllers/menu/menu';
diff --git a/packages/sheets-ui/src/services/scroll-manager.service.ts b/packages/sheets-ui/src/services/scroll-manager.service.ts
index 4ab72db766..06827b2b9e 100644
--- a/packages/sheets-ui/src/services/scroll-manager.service.ts
+++ b/packages/sheets-ui/src/services/scroll-manager.service.ts
@@ -36,17 +36,17 @@ export type IScrollInfo = Map<string, Map<string, IScrollManagerParam>>;
/**
* This service manages and sets the virtual scrolling of the canvas content area.
* It triggers service changes through SetScrollOperation.
+ *
* ScrollController subscribes to the changes in service data to refresh the view scrolling.
*/
export class ScrollManagerService {
private readonly _scrollInfo: IScrollInfo = new Map();
- private _currentScroll: Nullable<IScrollManagerSearchParam> = null;
-
private readonly _scrollInfo$ = new BehaviorSubject<Nullable<IScrollManagerParam>>(null);
-
readonly scrollInfo$ = this._scrollInfo$.asObservable();
+ private _currentScroll: Nullable<IScrollManagerSearchParam> = null;
+
dispose(): void {
this._scrollInfo$.complete();
}
@@ -69,6 +69,7 @@ export class ScrollManagerService {
if (this._currentScroll == null) {
return;
}
+
this._addByParam({
...this._currentScroll,
...scroll,
@@ -79,6 +80,7 @@ export class ScrollManagerService {
if (this._currentScroll == null) {
return;
}
+
this._addByParam(
{
...this._currentScroll,
diff --git a/packages/sheets-ui/src/services/selection/__test__/selection-render.test.ts b/packages/sheets-ui/src/services/selection/__test__/selection-render.test.ts
index 5bf60b3e9c..09b4728e4d 100644
--- a/packages/sheets-ui/src/services/selection/__test__/selection-render.test.ts
+++ b/packages/sheets-ui/src/services/selection/__test__/selection-render.test.ts
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-import { LocaleService, ThemeService } from '@univerjs/core';
+import { IContextService, LocaleService, ThemeService } from '@univerjs/core';
import type { CURSOR_TYPE, IMouseEvent } from '@univerjs/engine-render';
import {
DeviceType,
@@ -160,7 +160,6 @@ describe('Test indirect', () => {
let get: Injector['get'];
let themeService: ThemeService;
-
let selectionRenderService: SelectionRenderService;
let selectionStartParam: ISelectionWithCoordAndStyle[];
@@ -181,6 +180,7 @@ describe('Test indirect', () => {
get = testBed.get;
const localeService = get(LocaleService);
+ const contextService = get(IContextService);
themeService = get(ThemeService);
themeService.setTheme(theme);
@@ -198,7 +198,8 @@ describe('Test indirect', () => {
config,
worksheet.getCellMatrix(),
workbook.getStyles(),
- localeService
+ localeService,
+ contextService
);
const scene = new Scene('', new Engine());
diff --git a/packages/sheets-ui/src/services/sheet-skeleton-manager.service.ts b/packages/sheets-ui/src/services/sheet-skeleton-manager.service.ts
index 21f9f06f21..fd74ef8321 100644
--- a/packages/sheets-ui/src/services/sheet-skeleton-manager.service.ts
+++ b/packages/sheets-ui/src/services/sheet-skeleton-manager.service.ts
@@ -18,7 +18,7 @@ import type { Nullable, Workbook, Worksheet } from '@univerjs/core';
import { IUniverInstanceService, LocaleService } from '@univerjs/core';
import { SpreadsheetSkeleton } from '@univerjs/engine-render';
import type { IDisposable } from '@wendellhu/redi';
-import { Inject } from '@wendellhu/redi';
+import { Inject, Injector } from '@wendellhu/redi';
import { BehaviorSubject } from 'rxjs';
export interface ISheetSkeletonManagerParam {
@@ -62,6 +62,7 @@ export class SheetSkeletonManagerService implements IDisposable {
constructor(
@IUniverInstanceService private readonly _currentUniverService: IUniverInstanceService,
+ @Inject(Injector) private readonly _injector: Injector,
@Inject(LocaleService) private readonly _localeService: LocaleService
) { }
@@ -159,13 +160,12 @@ export class SheetSkeletonManagerService implements IDisposable {
}
const workbook = this._currentUniverService.getUniverSheetInstance(searchParam.unitId);
-
const worksheet = workbook?.getSheetBySheetId(searchParam.sheetId);
if (!worksheet || !workbook) {
return;
}
- const newSkeleton = this._buildSkeleton(worksheet, workbook);
+ const newSkeleton = this._buildSkeleton(worksheet, workbook);
this._sheetSkeletonParam.push({
unitId: searchParam.unitId,
sheetId: searchParam.sheetId,
@@ -190,12 +190,12 @@ export class SheetSkeletonManagerService implements IDisposable {
private _buildSkeleton(worksheet: Worksheet, workbook: Workbook) {
const config = worksheet.getConfig();
- const spreadsheetSkeleton = SpreadsheetSkeleton.create(
+ const spreadsheetSkeleton = this._injector.createInstance(
+ SpreadsheetSkeleton,
worksheet,
config,
worksheet.getCellMatrix(),
- workbook.getStyles(),
- this._localeService
+ workbook.getStyles()
);
return spreadsheetSkeleton;
diff --git a/packages/sheets-ui/src/sheets-ui-plugin.ts b/packages/sheets-ui/src/sheets-ui-plugin.ts
index c80f72922b..53d08fc570 100644
--- a/packages/sheets-ui/src/sheets-ui-plugin.ts
+++ b/packages/sheets-ui/src/sheets-ui-plugin.ts
@@ -38,7 +38,6 @@ import { HeaderResizeController } from './controllers/header-resize.controller';
import { HeaderUnhideController } from './controllers/header-unhide.controller';
import { MarkSelectionController } from './controllers/mark-selection.controller';
import { MoveRangeController } from './controllers/move-range.controller';
-import { SheetNavigationController } from './controllers/navigation/navigation.controller';
import { ScrollController } from './controllers/scroll.controller';
import { SelectionController } from './controllers/selection.controller';
import { SheetRenderController } from './controllers/sheet-render.controller';
@@ -124,7 +123,6 @@ export class UniverSheetsUIPlugin extends Plugin {
[SelectionController],
[SheetClipboardController],
[SheetContextMenuController],
- [SheetNavigationController],
[SheetRenderController],
[SheetUIController],
[StartEditController],
diff --git a/packages/sheets/src/commands/commands/__tests__/insert-remove-rows-cols.command.spec.ts b/packages/sheets/src/commands/commands/__tests__/insert-remove-rows-cols.command.spec.ts
index 00a113946f..48b5fae9c2 100644
--- a/packages/sheets/src/commands/commands/__tests__/insert-remove-rows-cols.command.spec.ts
+++ b/packages/sheets/src/commands/commands/__tests__/insert-remove-rows-cols.command.spec.ts
@@ -168,7 +168,7 @@ describe('Test insert and remove rows cols commands', () => {
const currentService = get(IUniverInstanceService);
const workbook = currentService.getCurrentUniverSheetInstance();
const worksheet = workbook.getActiveSheet();
- return worksheet.getMergedCells(row, col)?.[0];
+ return worksheet.getMergedCell(row, col);
}
function getMergeData() {
@@ -263,7 +263,7 @@ describe('Test insert and remove rows cols commands', () => {
const result = await commandService.executeCommand(RemoveRowCommand.id);
expect(result).toBeTruthy();
expect(getRowCount()).toBe(19);
- expect(getMergedInfo(1, 3)).toBeUndefined(); // expect the merged cell info to be deleted
+ expect(getMergedInfo(1, 3)).toBeFalsy(); // expect the merged cell info to be deleted
await commandService.executeCommand(UndoCommand.id);
expect(getRowCount()).toBe(20);
@@ -282,7 +282,7 @@ describe('Test insert and remove rows cols commands', () => {
const result = await commandService.executeCommand(RemoveColCommand.id);
expect(result).toBeTruthy();
expect(getColCount()).toBe(19);
- expect(getMergedInfo(1, 3)).toBeUndefined(); // expect the merged cell info to be deleted
+ expect(getMergedInfo(1, 3)).toBeFalsy(); // expect the merged cell info to be deleted
expect(getMergedInfo(1, 2)).toEqual({ startRow: 1, endRow: 1, startColumn: 1, endColumn: 2 }); // expect the merged cell to be moved left
await commandService.executeCommand(UndoCommand.id);
diff --git a/packages/sheets/src/commands/commands/__tests__/move-range-commands.spec.ts b/packages/sheets/src/commands/commands/__tests__/move-range-commands.spec.ts
index 94fcc84265..d540e1aa10 100644
--- a/packages/sheets/src/commands/commands/__tests__/move-range-commands.spec.ts
+++ b/packages/sheets/src/commands/commands/__tests__/move-range-commands.spec.ts
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-import type { ICellData, IRange, IWorkbookData, Nullable, Univer } from '@univerjs/core';
+import type { IRange, IWorkbookData, Nullable, Univer } from '@univerjs/core';
import { ICommandService, IUniverInstanceService, LocaleType, Tools } from '@univerjs/core';
import type { Injector } from '@wendellhu/redi';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
@@ -136,19 +136,13 @@ describe('Test move range commands', () => {
});
});
- function getCellInfo(row: number, col: number): Nullable<ICellData> {
- const currentService = get(IUniverInstanceService);
- const workbook = currentService.getCurrentUniverSheetInstance();
- const worksheet = workbook.getActiveSheet();
- return worksheet.getCellMatrix().getValue(row, col);
- }
-
function getMergedInfo(row: number, col: number): Nullable<IRange> {
const currentService = get(IUniverInstanceService);
const workbook = currentService.getCurrentUniverSheetInstance();
const worksheet = workbook.getActiveSheet();
- return worksheet.getMergedCells(row, col)?.[0];
+ return worksheet.getMergedCell(row, col);
}
+
function getMergeData() {
const currentService = get(IUniverInstanceService);
const workbook = currentService.getCurrentUniverSheetInstance();
diff --git a/packages/sheets/src/commands/commands/__tests__/move-rows-cols.command.spec.ts b/packages/sheets/src/commands/commands/__tests__/move-rows-cols.command.spec.ts
index 4b6840f816..b0fbd8e876 100644
--- a/packages/sheets/src/commands/commands/__tests__/move-rows-cols.command.spec.ts
+++ b/packages/sheets/src/commands/commands/__tests__/move-rows-cols.command.spec.ts
@@ -144,7 +144,7 @@ describe('Test move rows cols', () => {
const currentService = get(IUniverInstanceService);
const workbook = currentService.getCurrentUniverSheetInstance();
const worksheet = workbook.getActiveSheet();
- return worksheet.getMergedCells(row, col)?.[0];
+ return worksheet.getMergedCell(row, col);
}
function getRowHeight(row: number): number {
diff --git a/packages/sheets/src/commands/commands/set-range-values.command.ts b/packages/sheets/src/commands/commands/set-range-values.command.ts
index 66939f1a66..51b43cdf66 100644
--- a/packages/sheets/src/commands/commands/set-range-values.command.ts
+++ b/packages/sheets/src/commands/commands/set-range-values.command.ts
@@ -30,12 +30,10 @@ import type { IAccessor } from '@wendellhu/redi';
import { SelectionManagerService } from '../../services/selection-manager.service';
import { INTERCEPTOR_POINT } from '../../services/sheet-interceptor/interceptor-const';
import { SheetInterceptorService } from '../../services/sheet-interceptor/sheet-interceptor.service';
-import type { ISetRangeValuesMutationParams } from '../mutations/set-range-values.mutation';
import { SetRangeValuesMutation, SetRangeValuesUndoMutationFactory } from '../mutations/set-range-values.mutation';
+import type { ISheetCommandSharedParams } from '../utils/interface';
-export interface ISetRangeValuesCommandParams {
- subUnitId?: string;
- unitId?: string;
+export interface ISetRangeValuesCommandParams extends Partial<ISheetCommandSharedParams> {
range?: IRange;
/**
@@ -52,7 +50,7 @@ export interface ISetRangeValuesCommandParams {
export const SetRangeValuesCommand: ICommand = {
id: 'sheet.command.set-range-values',
type: CommandType.COMMAND,
- handler: async (accessor: IAccessor, params: ISetRangeValuesCommandParams) => {
+ handler: (accessor: IAccessor, params: ISetRangeValuesCommandParams) => {
const commandService = accessor.get(ICommandService);
const undoRedoService = accessor.get(IUndoRedoService);
const univerInstanceService = accessor.get(IUniverInstanceService);
@@ -97,15 +95,12 @@ export const SetRangeValuesCommand: ICommand = {
realCellValue = value as IObjectMatrixPrimitiveType<ICellData>;
}
- const setRangeValuesMutationParams: ISetRangeValuesMutationParams = {
+ const setRangeValuesMutationParams = {
subUnitId,
unitId,
cellValue: realCellValue ?? cellValue.getMatrix(),
};
- const undoSetRangeValuesMutationParams: ISetRangeValuesMutationParams = SetRangeValuesUndoMutationFactory(
- accessor,
- setRangeValuesMutationParams
- );
+ const undoSetRangeValuesMutationParams = SetRangeValuesUndoMutationFactory(accessor, setRangeValuesMutationParams);
if (
!sheetInterceptorService.fetchThroughInterceptors(INTERCEPTOR_POINT.PERMISSION)(null, {
@@ -121,13 +116,13 @@ export const SetRangeValuesCommand: ICommand = {
setRangeValuesMutationParams
);
+ // may cause performance issues
const { undos, redos } = sheetInterceptorService.onCommandExecute({
id: SetRangeValuesCommand.id,
params: { ...setRangeValuesMutationParams, range: currentSelections },
});
- const result = await sequenceExecute([...redos], commandService);
-
+ const result = sequenceExecute([...redos], commandService);
if (setValueMutationResult && result.result) {
undoRedoService.pushUndoRedo({
unitID: unitId,
diff --git a/packages/sheets/src/commands/commands/set-worksheet-activate.command.ts b/packages/sheets/src/commands/commands/set-worksheet-activate.command.ts
index f6508fcf32..9c052ad049 100644
--- a/packages/sheets/src/commands/commands/set-worksheet-activate.command.ts
+++ b/packages/sheets/src/commands/commands/set-worksheet-activate.command.ts
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-import type { ICommand } from '@univerjs/core';
+import type { ICommand, IExecutionOptions } from '@univerjs/core';
import { CommandType, ICommandService, IUniverInstanceService } from '@univerjs/core';
import type { IAccessor } from '@wendellhu/redi';
@@ -26,11 +26,13 @@ export interface ISetWorksheetActivateCommandParams {
subUnitId?: string;
}
+/** We should delay this command to execute, after focus moves to the correct element. */
+const SET_WORKSHEET_ACTIVE_DELAY = 4;
+
export const SetWorksheetActivateCommand: ICommand = {
type: CommandType.COMMAND,
id: 'sheet.command.set-worksheet-activate',
-
- handler: (accessor: IAccessor, params?: ISetWorksheetActivateCommandParams) => {
+ handler: (accessor: IAccessor, params?: ISetWorksheetActivateCommandParams, options?: IExecutionOptions) => {
const commandService = accessor.get(ICommandService);
const univerInstanceService = accessor.get(IUniverInstanceService);
@@ -42,11 +44,15 @@ export const SetWorksheetActivateCommand: ICommand = {
subUnitId = params.subUnitId ?? subUnitId;
}
- const redoMutationParams: ISetWorksheetActiveOperationParams = {
- unitId,
- subUnitId,
- };
+ return new Promise((resolve) => {
+ setTimeout(() => {
+ const result = commandService.syncExecuteCommand(SetWorksheetActiveOperation.id, {
+ unitId,
+ subUnitId,
+ } as ISetWorksheetActiveOperationParams, options);
- return commandService.syncExecuteCommand(SetWorksheetActiveOperation.id, redoMutationParams);
+ resolve(result);
+ }, SET_WORKSHEET_ACTIVE_DELAY);
+ });
},
};
diff --git a/packages/sheets/src/services/sheet-interceptor/sheet-interceptor.service.ts b/packages/sheets/src/services/sheet-interceptor/sheet-interceptor.service.ts
index ff0e0893e0..59ba8d2f63 100644
--- a/packages/sheets/src/services/sheet-interceptor/sheet-interceptor.service.ts
+++ b/packages/sheets/src/services/sheet-interceptor/sheet-interceptor.service.ts
@@ -152,8 +152,9 @@ export class SheetInterceptorService extends Disposable {
private _interceptWorkbook(workbook: Workbook): void {
const disposables = new DisposableCollection();
const unitId = workbook.getUnitId();
- const self = this;
+ // eslint-disable-next-line ts/no-this-alias
+ const self = this;
const interceptViewModel = (worksheet: Worksheet): void => {
const subUnitId = worksheet.getSheetId();
worksheet.__interceptViewModel((viewModel) => {
diff --git a/packages/slides/src/views/render/adaptors/spreadsheet-adaptor.ts b/packages/slides/src/views/render/adaptors/spreadsheet-adaptor.ts
index ec013dfa54..de5c5b811a 100644
--- a/packages/slides/src/views/render/adaptors/spreadsheet-adaptor.ts
+++ b/packages/slides/src/views/render/adaptors/spreadsheet-adaptor.ts
@@ -15,7 +15,7 @@
*/
import type { EventState, ICellData, IPageElement } from '@univerjs/core';
-import { LocaleService, ObjectMatrix, PageElementType, Styles } from '@univerjs/core';
+import { IContextService, LocaleService, ObjectMatrix, PageElementType, Styles } from '@univerjs/core';
import type { IScrollObserverParam, IWheelEvent } from '@univerjs/engine-render';
import {
EVENT_TYPE,
@@ -53,7 +53,10 @@ export class SpreadsheetAdaptor extends ObjectAdaptor {
override viewKey = PageElementType.SPREADSHEET;
- constructor(@Inject(LocaleService) private readonly _localeService: LocaleService) {
+ constructor(
+ @Inject(LocaleService) private readonly _localeService: LocaleService,
+ @IContextService private readonly _contextService: IContextService
+ ) {
super();
}
@@ -79,8 +82,6 @@ export class SpreadsheetAdaptor extends ObjectAdaptor {
skewY,
flipX,
flipY,
- title,
- description,
spreadsheet: spreadsheetModel,
} = pageElement;
@@ -90,16 +91,17 @@ export class SpreadsheetAdaptor extends ObjectAdaptor {
const { worksheet, styles } = spreadsheetModel;
- const { columnData, rowData, cellData } = worksheet;
+ const { cellData } = worksheet;
const cellDataMatrix = new ObjectMatrix<ICellData>(cellData);
- const spreadsheetSkeleton = SpreadsheetSkeleton.create(
+ const spreadsheetSkeleton = new SpreadsheetSkeleton(
undefined, // FIXME: worksheet in slide doesn't has a Worksheet object
worksheet,
cellDataMatrix,
new Styles(styles),
- this._localeService
+ this._localeService,
+ this._contextService
);
const { rowTotalHeight, columnTotalWidth, rowHeaderWidth, columnHeaderHeight } = spreadsheetSkeleton;
diff --git a/packages/ui/src/controllers/shared-shortcut.controller.ts b/packages/ui/src/controllers/shared-shortcut.controller.ts
index 7dab503684..b486ba0437 100644
--- a/packages/ui/src/controllers/shared-shortcut.controller.ts
+++ b/packages/ui/src/controllers/shared-shortcut.controller.ts
@@ -14,7 +14,8 @@
* limitations under the License.
*/
-import { Disposable, ICommandService, LifecycleStages, OnLifecycle, RedoCommand, UndoCommand } from '@univerjs/core';
+import type { IContextService } from '@univerjs/core';
+import { Disposable, FOCUSING_UNIVER_EDITOR, ICommandService, LifecycleStages, OnLifecycle, RedoCommand, UndoCommand } from '@univerjs/core';
import { Inject, Injector } from '@wendellhu/redi';
import { CopyCommand, CutCommand, PasteCommand } from '../services/clipboard/clipboard.command';
@@ -22,7 +23,6 @@ import { IMenuService } from '../services/menu/menu.service';
import { KeyCode, MetaKeys } from '../services/shortcut/keycode';
import type { IShortcutItem } from '../services/shortcut/shortcut.service';
import { IShortcutService } from '../services/shortcut/shortcut.service';
-import { IClipboardInterfaceService } from '../services/clipboard/clipboard-interface.service';
import { SetEditorResizeOperation } from '../commands/operations/editor/set-editor-resize.operation';
import { RedoMenuItemFactory, UndoMenuItemFactory } from './menus/menus';
@@ -30,11 +30,16 @@ import { RedoMenuItemFactory, UndoMenuItemFactory } from './menus/menus';
// If not, the corresponding shortcut would not be triggered and we will perform clipboard operations
// through clipboard events (editorElement.addEventListener('paste')).
+function whenEditorFocused(contextService: IContextService): boolean {
+ return contextService.getContextValue(FOCUSING_UNIVER_EDITOR);
+}
+
export const CopyShortcutItem: IShortcutItem = {
id: CopyCommand.id,
description: 'shortcut.copy',
group: '1_common-edit',
binding: KeyCode.C | MetaKeys.CTRL_COMMAND,
+ preconditions: whenEditorFocused,
};
export const CutShortcutItem: IShortcutItem = {
@@ -42,6 +47,7 @@ export const CutShortcutItem: IShortcutItem = {
description: 'shortcut.cut',
group: '1_common-edit',
binding: KeyCode.X | MetaKeys.CTRL_COMMAND,
+ preconditions: whenEditorFocused,
};
/**
@@ -70,6 +76,7 @@ export const UndoShortcutItem: IShortcutItem = {
description: 'shortcut.undo',
group: '1_common-edit',
binding: KeyCode.Z | MetaKeys.CTRL_COMMAND,
+ preconditions: whenEditorFocused,
};
export const RedoShortcutItem: IShortcutItem = {
@@ -77,6 +84,7 @@ export const RedoShortcutItem: IShortcutItem = {
description: 'shortcut.redo',
group: '1_common-edit',
binding: KeyCode.Y | MetaKeys.CTRL_COMMAND,
+ preconditions: whenEditorFocused,
};
/**
@@ -88,8 +96,7 @@ export class SharedController extends Disposable {
@Inject(Injector) private readonly _injector: Injector,
@IMenuService private readonly _menuService: IMenuService,
@IShortcutService private readonly _shortcutService: IShortcutService,
- @ICommandService private readonly _commandService: ICommandService,
- @IClipboardInterfaceService private readonly _interfaceService: IClipboardInterfaceService
+ @ICommandService private readonly _commandService: ICommandService
) {
super();
diff --git a/packages/ui/src/controllers/shortcut-display/shortcut-panel.controller.ts b/packages/ui/src/controllers/shortcut-display/shortcut-panel.controller.ts
index da2fc908ae..c62399fe7a 100644
--- a/packages/ui/src/controllers/shortcut-display/shortcut-panel.controller.ts
+++ b/packages/ui/src/controllers/shortcut-display/shortcut-panel.controller.ts
@@ -24,25 +24,40 @@ import {
import { ComponentManager } from '../../common/component-manager';
import { IMenuService } from '../../services/menu/menu.service';
import { ShortcutPanel } from '../../views/components/shortcut-panel/ShortcutPanel';
+import type { IShortcutItem } from '../../services/shortcut/shortcut.service';
+import { IShortcutService } from '../../services/shortcut/shortcut.service';
+import { KeyCode, MetaKeys } from '../../services/shortcut/keycode';
import { ShortcutPanelMenuItemFactory } from './menu';
+const ToggleShortcutPanelShortcut: IShortcutItem = {
+ id: ToggleShortcutPanelOperation.id,
+ binding: MetaKeys.CTRL_COMMAND | KeyCode.BACK_SLASH,
+ description: 'shortcut.shortcut-panel',
+ group: '10_global-shortcut',
+};
+
/**
* This controller add a side panel to the application to display the shortcuts.
*/
@OnLifecycle(LifecycleStages.Steady, ShortcutPanelController)
export class ShortcutPanelController extends Disposable {
constructor(
- @Inject(Injector) private readonly _injector: Injector,
+ @Inject(Injector) injector: Injector,
+ @Inject(ComponentManager) componentManager: ComponentManager,
+ @IShortcutService shortcutService: IShortcutService,
@IMenuService menuService: IMenuService,
- @ICommandService commandService: ICommandService,
- @Inject(ComponentManager) componentManager: ComponentManager
+ @ICommandService commandService: ICommandService
) {
super();
- // Register the menu item.
- this.disposeWithMe(menuService.addMenuItem(this._injector.invoke(ShortcutPanelMenuItemFactory)));
- // Register the panel.
+ // register the menu item
+ this.disposeWithMe(menuService.addMenuItem(injector.invoke(ShortcutPanelMenuItemFactory)));
+
+ // register the panel
this.disposeWithMe(componentManager.register(ShortcutPanelComponentName, ShortcutPanel));
this.disposeWithMe(commandService.registerCommand(ToggleShortcutPanelOperation));
+
+ // register the shortcut
+ this.disposeWithMe(shortcutService.registerShortcut(ToggleShortcutPanelShortcut));
}
}
diff --git a/packages/ui/src/controllers/ui/ui-desktop.controller.tsx b/packages/ui/src/controllers/ui/ui-desktop.controller.tsx
index 309b319766..6af505295a 100644
--- a/packages/ui/src/controllers/ui/ui-desktop.controller.tsx
+++ b/packages/ui/src/controllers/ui/ui-desktop.controller.tsx
@@ -17,7 +17,7 @@
import { Disposable, LifecycleService, LifecycleStages, toDisposable } from '@univerjs/core';
import { IRenderManagerService } from '@univerjs/engine-render';
import type { IDisposable } from '@wendellhu/redi';
-import { Inject, Injector } from '@wendellhu/redi';
+import { Inject, Injector, Optional } from '@wendellhu/redi';
import { connectInjector } from '@wendellhu/redi/react-bindings';
import { render as createRoot, unmount } from 'rc-util/lib/React/render';
import type { ComponentType } from 'react';
@@ -82,7 +82,7 @@ export class DesktopUIController extends Disposable implements IDesktopUIControl
@Inject(Injector) private readonly _injector: Injector,
@Inject(LifecycleService) private readonly _lifecycleService: LifecycleService,
@IRenderManagerService private readonly _renderManagerService: IRenderManagerService,
- @ILayoutService private readonly _layoutService: ILayoutService
+ @Optional(ILayoutService) private readonly _layoutService?: ILayoutService
) {
super();
}
diff --git a/packages/ui/src/index.ts b/packages/ui/src/index.ts
index 78340cb58b..eaf1aec1e4 100644
--- a/packages/ui/src/index.ts
+++ b/packages/ui/src/index.ts
@@ -75,14 +75,10 @@ export { IZenZoneService } from './services/zen-zone/zen-zone.service';
export { UniverUIPlugin } from './ui-plugin';
export * from './utils';
export { type IConfirmPartMethodOptions } from './views/components/confirm-part/interface';
-
export { IEditorService, EditorService } from './services/editor/editor.service';
-
export { TextEditor } from './components/editor/TextEditor';
-
export { SetEditorResizeOperation } from './commands/operations/editor/set-editor-resize.operation';
-
export { RangeSelector } from './components/range-selector/RangeSelector';
-
export { IRangeSelectorService } from './services/range-selector/range-selector.service';
export { DesktopLocalStorageService } from './services/local-storage/local-storage.service';
+export { useActiveWorkbook, useActiveWorksheet } from './views/hooks/active';
diff --git a/packages/ui/src/locale/en-US.ts b/packages/ui/src/locale/en-US.ts
index b315c534da..e451c9cd5d 100644
--- a/packages/ui/src/locale/en-US.ts
+++ b/packages/ui/src/locale/en-US.ts
@@ -52,6 +52,7 @@ const locale: typeof zhCN = {
cut: 'Cut',
copy: 'Copy',
paste: 'Paste',
+ 'shortcut-panel': 'Toggle Shortcut Panel',
},
'common-edit': 'Common Editing Shortcuts',
'toggle-shortcut-panel': 'Toggle Shortcut Panel',
@@ -73,6 +74,7 @@ const locale: typeof zhCN = {
confirm: 'Confirm',
cancel: 'Cancel',
},
+ 'global-shortcut': 'Global Shortcut',
};
export default locale;
diff --git a/packages/ui/src/locale/zh-CN.ts b/packages/ui/src/locale/zh-CN.ts
index 75142b11a4..5ef6b4014b 100644
--- a/packages/ui/src/locale/zh-CN.ts
+++ b/packages/ui/src/locale/zh-CN.ts
@@ -50,6 +50,7 @@ const locale = {
cut: '剪切',
copy: '复制',
paste: '粘贴',
+ 'shortcut-panel': '打开收起快捷键面板',
},
'common-edit': '常用编辑',
'toggle-shortcut-panel': '打开收起快捷键面板',
@@ -71,6 +72,7 @@ const locale = {
confirm: '确认',
cancel: '取消',
},
+ 'global-shortcut': '全局快捷键',
};
export default locale;
diff --git a/packages/ui/src/services/confirm/confirm.service.ts b/packages/ui/src/services/confirm/confirm.service.ts
index edf5f732a7..6933f23454 100644
--- a/packages/ui/src/services/confirm/confirm.service.ts
+++ b/packages/ui/src/services/confirm/confirm.service.ts
@@ -26,8 +26,6 @@ export interface IConfirmService {
readonly confirmOptions$: Subject<IConfirmPartMethodOptions[]>;
open(params: IConfirmPartMethodOptions): IDisposable;
-
confirm(params: IConfirmPartMethodOptions): Promise<boolean>;
-
close(id: string): void;
}
diff --git a/packages/ui/src/services/dialog/dialog.service.ts b/packages/ui/src/services/dialog/dialog.service.ts
index e0582f3b47..7944e4804a 100644
--- a/packages/ui/src/services/dialog/dialog.service.ts
+++ b/packages/ui/src/services/dialog/dialog.service.ts
@@ -20,7 +20,7 @@ import type { Subject } from 'rxjs';
import type { IDialogPartMethodOptions } from '../../views/components/dialog-part/interface';
-export const IDialogService = createIdentifier<IDialogService>('univer.dialog-service');
+export const IDialogService = createIdentifier<IDialogService>('univer.ui.dialog-service');
export interface IDialogService {
open(params: IDialogPartMethodOptions): IDisposable;
close(id: string): void;
diff --git a/packages/ui/src/services/shortcut/keycode.ts b/packages/ui/src/services/shortcut/keycode.ts
index 63c2e56594..125a813402 100644
--- a/packages/ui/src/services/shortcut/keycode.ts
+++ b/packages/ui/src/services/shortcut/keycode.ts
@@ -14,10 +14,12 @@
* limitations under the License.
*/
+/* eslint-disable ts/prefer-literal-enum-member */
+
// Useful keyboard event inspection tool https://www.toptal.com/developers/keycode
/** KeyCode that maps to browser standard keycode. */
-export const enum KeyCode {
+export enum KeyCode {
UNKNOWN = 0,
BACKSPACE = 8,
@@ -89,15 +91,8 @@ export const enum KeyCode {
MINUS = 189,
EQUAL = 187,
-}
-export const enum MetaKeys {
- SHIFT = 1 << 10,
- /** Option key on MacOS. Alt key on other systems. */
- ALT = 1 << 11,
- /** Command key on MacOS. Ctrl key on other systems. */
- CTRL_COMMAND = 1 << 12,
- MAC_CTRL = 1 << 13,
+ BACK_SLASH = 220,
}
export const KeyCodeToChar: { [key: number]: string } = {
@@ -152,4 +147,17 @@ export const KeyCodeToChar: { [key: number]: string } = {
[KeyCode.MINUS]: '-',
[KeyCode.EQUAL]: '=',
+
+ [KeyCode.BACK_SLASH]: '\\',
};
+
+/** Define meta key numbers. */
+export enum MetaKeys {
+ SHIFT = 1 << 10,
+ /** Option key on MacOS. Alt key on other systems. */
+ ALT = 1 << 11,
+ /** Command key on MacOS. Ctrl key on other systems. */
+ CTRL_COMMAND = 1 << 12,
+ /** Ctrl key for MacOS. Not valid on other systems. */
+ MAC_CTRL = 1 << 13,
+}
diff --git a/packages/ui/src/ui-plugin.ts b/packages/ui/src/ui-plugin.ts
index 62ea06ed49..48fe932b4a 100644
--- a/packages/ui/src/ui-plugin.ts
+++ b/packages/ui/src/ui-plugin.ts
@@ -55,7 +55,7 @@ import { IRangeSelectorService, RangeSelectorService } from './services/range-se
const PLUGIN_NAME = 'ui';
-export interface IUniverUIConfig extends IWorkbenchOptions {}
+export interface IUniverUIConfig extends IWorkbenchOptions { }
const DEFAULT_SLIDE_PLUGIN_DATA = {};
diff --git a/packages/ui/src/views/components/dialog-part/DialogPart.tsx b/packages/ui/src/views/components/dialog-part/DialogPart.tsx
index d22a8a63e2..86ae4af320 100644
--- a/packages/ui/src/views/components/dialog-part/DialogPart.tsx
+++ b/packages/ui/src/views/components/dialog-part/DialogPart.tsx
@@ -30,12 +30,12 @@ export function DialogPart() {
useEffect(() => {
const dialog$ = dialogService.getObservableDialog();
- const subscribtion = dialog$.subscribe((options: IDialogPartMethodOptions[]) => {
+ const subscription = dialog$.subscribe((options: IDialogPartMethodOptions[]) => {
setDialogOptions(options);
});
return () => {
- subscribtion.unsubscribe();
+ subscription.unsubscribe();
};
}, []);
diff --git a/packages/ui/src/views/hooks/active.ts b/packages/ui/src/views/hooks/active.ts
new file mode 100644
index 0000000000..7f7a20c7da
--- /dev/null
+++ b/packages/ui/src/views/hooks/active.ts
@@ -0,0 +1,40 @@
+/**
+ * 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 { Nullable, Workbook, Worksheet } from '@univerjs/core';
+import { IUniverInstanceService } from '@univerjs/core';
+import { useDependency } from '@wendellhu/redi/react-bindings';
+import { of } from 'rxjs';
+
+import { useObservable } from '../../components/hooks/observable';
+
+/**
+ * A react hooks to get the active workbook.
+ */
+export function useActiveWorkbook(): Nullable<Workbook> {
+ const univerInstanceService = useDependency(IUniverInstanceService);
+ const activeWorkbook = useObservable(univerInstanceService.currentSheet$);
+ return activeWorkbook;
+}
+
+/**
+ * A react hooks to get the active worksheet.
+ */
+export function useActiveWorksheet(): Nullable<Worksheet> {
+ const activeWorkbook = useActiveWorkbook();
+ const activeWorksheet = useObservable(activeWorkbook ? activeWorkbook?.activeSheet$ : of(null));
+ return activeWorksheet;
+}
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 9ff47681dc..d6150ab312 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -136,7 +136,7 @@ importers:
'@storybook/react-webpack5':
specifier: 8.0.0-rc.3
'@storybook/types':
specifier: ^7.6.17
version: 7.6.17
@@ -163,7 +163,7 @@ importers:
version: 8.0.0-rc.3([email protected])([email protected])
storybook-addon-swc:
specifier: ^1.2.0
- version: 1.2.0(@swc/[email protected])([email protected])
+ version: 1.2.0(@swc/[email protected])([email protected])
style-loader:
specifier: ^3.3.4
version: 3.3.4([email protected])
@@ -655,6 +655,12 @@ importers:
'@univerjs/design':
specifier: workspace:*
version: link:../design
+ '@univerjs/engine-formula':
+ specifier: workspace:*
+ version: link:../engine-formula
+ '@univerjs/engine-render':
+ specifier: workspace:*
+ version: link:../engine-render
'@univerjs/shared':
specifier: workspace:*
version: link:../../common/shared
@@ -762,10 +768,17 @@ importers:
version: 1.3.1(@types/[email protected])([email protected])
packages/sheets-find-replace:
+ dependencies:
+ '@univerjs/ui':
+ specifier: workspace:*
+ version: link:../ui
devDependencies:
'@univerjs/core':
specifier: workspace:*
version: link:../core
+ '@univerjs/engine-formula':
+ specifier: workspace:*
+ version: link:../engine-formula
'@univerjs/engine-render':
specifier: workspace:*
version: link:../engine-render
@@ -784,6 +797,15 @@ importers:
'@wendellhu/redi':
specifier: ^0.13.0
version: 0.13.0
+ less:
+ specifier: ^4.2.0
+ version: 4.2.0
+ react:
+ specifier: ^18.2.0
+ version: 18.2.0
+ rxjs:
+ specifier: '>=7.0.0'
+ version: 7.8.1
typescript:
specifier: ^5.4.2
version: 5.4.2
@@ -792,7 +814,7 @@ importers:
version: 5.1.5(@types/[email protected])([email protected])
vitest:
specifier: ^1.3.1
- version: 1.3.1(@types/[email protected])([email protected])
+ version: 1.3.1(@types/[email protected])([email protected])
packages/sheets-formula:
dependencies:
@@ -4045,7 +4067,7 @@ packages:
webpack: ^5.0.0
dependencies:
'@storybook/node-logger': 7.6.16
- webpack: 5.90.3(@swc/[email protected])([email protected])
+ webpack: 5.90.3(@swc/[email protected])([email protected])
dev: false
/@storybook/[email protected]:
@@ -4062,9 +4084,9 @@ packages:
resolution: {integrity: sha512-5HGgegON/aBu/tDM3IFyEAZfaMmG98Y0OI48kkkc9EipfQRMIrYFizbCjV7388H98wM81TqTEqvzxYpFkPSphg==}
engines: {node: '>=18'}
dependencies:
- '@storybook/core-common': 8.0.0-rc.3
- '@swc/core': 1.4.2
- swc-loader: 0.2.6(@swc/[email protected])([email protected])
+ '@storybook/core-common': 8.1.0-alpha.0
+ '@swc/core': 1.4.4
+ swc-loader: 0.2.6(@swc/[email protected])([email protected])
transitivePeerDependencies:
- '@swc/helpers'
- encoding
@@ -4137,7 +4159,7 @@ packages:
- supports-color
dev: false
resolution: {integrity: sha512-mzm+brHibnedO/osAIJe4LNszIlBvKfedSXcnesWOtWqtRAZyQtTl6+GeRXMw6mgA8u3LHl61XLHW202hWVlhQ==}
peerDependencies:
typescript: '*'
@@ -4170,13 +4192,13 @@ packages:
process: 0.11.10
semver: 7.6.0
style-loader: 3.3.4([email protected])
- terser-webpack-plugin: 5.3.10(@swc/[email protected])([email protected])([email protected])
+ terser-webpack-plugin: 5.3.10(@swc/[email protected])([email protected])([email protected])
ts-dedent: 2.2.0
typescript: 5.4.2
url: 0.11.3
util: 0.12.5
util-deprecate: 1.0.2
- webpack: 5.90.3(@swc/[email protected])([email protected])
+ webpack: 5.90.3(@swc/[email protected])([email protected])
webpack-dev-middleware: 6.1.1([email protected])
webpack-hot-middleware: 2.26.1
webpack-virtual-modules: 0.5.0
@@ -4210,6 +4232,16 @@ packages:
telejson: 7.2.0
tiny-invariant: 1.3.3
+ /@storybook/[email protected]:
+ resolution: {integrity: sha512-DerCtPwmPHsqS/cPGE5DqjxDgzRMXKBVmef62H8BImNdLf3tHRpksRFl+81npVQRR+XSN6D2LQqRf6EPug0Log==}
+ dependencies:
+ '@storybook/client-logger': 8.1.0-alpha.0
+ '@storybook/core-events': 8.1.0-alpha.0
+ '@storybook/global': 5.0.0
+ telejson: 7.2.0
+ tiny-invariant: 1.3.3
+ dev: false
+
resolution: {integrity: sha512-cLdvdP5yojZfr3Ylq1gwyeTtkmglTAlS2nWX+27RoNSWxar/HqdHocqAHs7k6K6ZmARMONWVEKh4+nPj3hLCog==}
hasBin: true
@@ -4271,6 +4303,12 @@ packages:
dependencies:
'@storybook/global': 5.0.0
+ /@storybook/[email protected]:
+ resolution: {integrity: sha512-cAvLyu43xJEmXYKaPhlIjNENTxaZUi+O7jtM/iGL4+ViVbHCc4SFtYZ894AGhXWnw9JC0FKq+cCZI4nb7q9Mkg==}
+ dependencies:
+ '@storybook/global': 5.0.0
+ dev: false
+
/@storybook/[email protected]:
resolution: {integrity: sha512-cLjdgDgyP/sckw5YUrvHQO/bQGw6AeRM6t4i4O97sz7X99HfuFd/HnYCLtKuAWj0Dy7+DcVPOUPsMWXujRoSYA==}
dependencies:
@@ -4349,6 +4387,42 @@ packages:
- encoding
- supports-color
+ /@storybook/[email protected]:
+ resolution: {integrity: sha512-LwCp0Zj0iOKtV3jd2RjdYSdLedC9DrwWBFPhL910EHDPE+Lnk4n1lilTUmI4hrl+Ni3iKBIjNJvZdMkcDdpAlA==}
+ dependencies:
+ '@storybook/core-events': 8.1.0-alpha.0
+ '@storybook/csf-tools': 8.1.0-alpha.0
+ '@storybook/node-logger': 8.1.0-alpha.0
+ '@storybook/types': 8.1.0-alpha.0
+ '@yarnpkg/fslib': 2.10.3
+ '@yarnpkg/libzip': 2.3.0
+ chalk: 4.1.2
+ cross-spawn: 7.0.3
+ esbuild: 0.20.1
+ esbuild-register: 3.5.0([email protected])
+ execa: 5.1.1
+ file-system-cache: 2.3.0
+ find-cache-dir: 3.3.2
+ find-up: 5.0.0
+ fs-extra: 11.2.0
+ glob: 10.3.10
+ handlebars: 4.7.8
+ lazy-universal-dotenv: 4.0.0
+ node-fetch: 2.7.0
+ picomatch: 2.3.1
+ pkg-dir: 5.0.0
+ pretty-hrtime: 1.0.3
+ resolve-from: 5.0.0
+ semver: 7.6.0
+ tempy: 1.0.1
+ tiny-invariant: 1.3.3
+ ts-dedent: 2.2.0
+ util: 0.12.5
+ transitivePeerDependencies:
+ - encoding
+ - supports-color
+ dev: false
+
/@storybook/[email protected]:
resolution: {integrity: sha512-AriWMCm/k1cxlv10f+jZ1wavThTRpLaN3kY019kHWbYT9XgaSuLU67G7GPr3cGnJ6HuA6uhbzu8qtqVCd6OfXA==}
dependencies:
@@ -4360,6 +4434,12 @@ packages:
dependencies:
ts-dedent: 2.2.0
+ /@storybook/[email protected]:
+ resolution: {integrity: sha512-/R8CrhyD7LD2W5/cFH3yl/pSwZMEzEcfg4tfCB8jrC/5vpYlrvPEUcZwgRd6Ofu9p0MrMxtCOD2Chqb5ZU8G7w==}
+ dependencies:
+ ts-dedent: 2.2.0
+ dev: false
+
resolution: {integrity: sha512-xdbUXcJ02aRlPa7699e8pOfQ1iW+IPoGN8ntn25olEP9siXptTZYu4oQq8Q/rHy3z3N/yCOZ4yf7ODJxlzz9kA==}
dependencies:
@@ -4452,6 +4532,22 @@ packages:
transitivePeerDependencies:
- supports-color
+ /@storybook/[email protected]:
+ resolution: {integrity: sha512-1U61GdS89BEmHyVGklCEuC1IHMh8oJDGm2tBo9nfjNnH+B6pi6ariG/tMi+Um+NKzY53/c72Nlp5hjiSXEy1Bw==}
+ dependencies:
+ '@babel/generator': 7.23.6
+ '@babel/parser': 7.23.9
+ '@babel/traverse': 7.23.9
+ '@babel/types': 7.23.9
+ '@storybook/csf': 0.1.2
+ '@storybook/types': 8.1.0-alpha.0
+ fs-extra: 11.2.0
+ recast: 0.23.5
+ ts-dedent: 2.2.0
+ transitivePeerDependencies:
+ - supports-color
+ dev: false
+
/@storybook/[email protected]:
resolution: {integrity: sha512-ePrvE/pS1vsKR9Xr+o+YwdqNgHUyXvg+1Xjx0h9LrVx7Zq4zNe06pd63F5EvzTbCbJsHj7GHr9tkiaqm7U8WRA==}
dependencies:
@@ -4522,7 +4618,11 @@ packages:
/@storybook/[email protected]:
resolution: {integrity: sha512-8VkQSMdU9/NwqQWRibG6hlI/MIq3qJ+qMx4TekTHvPXjJbbW+tRvGsFbyqQSFonZmg25XgUIp2wLc46CS/CEvw==}
+ /@storybook/[email protected]:
+ resolution: {integrity: sha512-byQCgUnKBcP+neOOIVtbWP4VfUGo7jQ+8k84DujTZVCjnQCa2idXPdmCSzukSUbtPBqiOpmbuZhTY763Jwbx/A==}
+ dev: false
+
resolution: {integrity: sha512-2WHNnKdUZHL7o97x2Tol2xawTcQnaBGvbwYo1GxuUI1roPALZ6S588u8JzNDyVNsdRnuIhBfdGZoONmkKhuR0w==}
engines: {node: '>=18.0.0'}
peerDependencies:
@@ -4550,7 +4650,7 @@ packages:
semver: 7.6.0
tsconfig-paths: 4.2.0
typescript: 5.4.2
- webpack: 5.90.3(@swc/[email protected])([email protected])
+ webpack: 5.90.3(@swc/[email protected])([email protected])
transitivePeerDependencies:
- '@swc/core'
- encoding
@@ -4596,7 +4696,7 @@ packages:
react-docgen-typescript: 2.2.2([email protected])
tslib: 2.6.2
typescript: 5.4.2
- webpack: 5.90.3(@swc/[email protected])([email protected])
+ webpack: 5.90.3(@swc/[email protected])([email protected])
transitivePeerDependencies:
- supports-color
dev: false
@@ -4610,7 +4710,7 @@ packages:
react: 18.2.0
react-dom: 18.2.0([email protected])
resolution: {integrity: sha512-RjaTqM3+egPdmaaHOD3pUBWI8cku8I3yizamsRy9KTY5AQvQhPW9wCf2/9fQJFMf/vxo6F9rC5E3LBp0X4v7Jg==}
engines: {node: '>=18.0.0'}
peerDependencies:
@@ -4621,8 +4721,8 @@ packages:
typescript:
optional: true
dependencies:
- '@storybook/builder-webpack5': 8.0.0-rc.3(@swc/[email protected])([email protected])([email protected])
- '@storybook/preset-react-webpack': 8.0.0-rc.3(@swc/[email protected])([email protected])([email protected])([email protected])([email protected])
+ '@storybook/builder-webpack5': 8.0.0-rc.3(@swc/[email protected])([email protected])([email protected])
+ '@storybook/preset-react-webpack': 8.0.0-rc.3(@swc/[email protected])([email protected])([email protected])([email protected])([email protected])
'@storybook/react': 8.0.0-rc.3([email protected])([email protected])([email protected])
'@types/node': 18.19.17
react: 18.2.0
@@ -4736,6 +4836,14 @@ packages:
'@types/express': 4.17.21
file-system-cache: 2.3.0
+ /@storybook/[email protected]:
+ resolution: {integrity: sha512-pahJTjo/awWljApRoYXrsK+zGNJzvj1zQEhSBHRqiEYlBRli536MeSpbMr7Za0A1xUazagV5UEvYoRSRpzwA0A==}
+ dependencies:
+ '@storybook/channels': 8.1.0-alpha.0
+ '@types/express': 4.17.21
+ file-system-cache: 2.3.0
+ dev: false
+
resolution: {integrity: sha512-ckdz51oHxD2FaxgY2piJWJVJiwgp8Uu96s+as2yB3RMwavn3nHBrpliVukXY9S/DmMicPRB2+H8nBk23GDG+qA==}
engines: {node: ^16.0.0 || >=18.0.0}
@@ -4808,8 +4916,8 @@ packages:
- typescript
dev: true
- resolution: {integrity: sha512-1uSdAn1MRK5C1m/TvLZ2RDvr0zLvochgrZ2xL+lRzugLlCTlSA+Q4TWtrZaOz+vnnFVliCpw7c7qu0JouhgQIw==}
+ resolution: {integrity: sha512-goSHS8yvDgha93RHIV2Vn50neYasqbc4K1g/nKOV6T8kiKVv4w/rmqNJu9Aa0mPGVJtjcr0NvX6bBwE0T4HIzg==}
engines: {node: '>=10'}
cpu: [arm64]
os: [darwin]
@@ -4817,8 +4925,8 @@ packages:
dev: false
optional: true
- resolution: {integrity: sha512-TYD28+dCQKeuxxcy7gLJUCFLqrwDZnHtC2z7cdeGfZpbI2mbfppfTf2wUPzqZk3gEC96zHd4Yr37V3Tvzar+lQ==}
+ resolution: {integrity: sha512-PLfgL355qsl5c5kUPsFGITgVXoaqjp9sCd0Y5Z5uN7RtSOvwIX28e23eCxj02dOr7OBr8sq6qBlEMDV03T24Iw==}
engines: {node: '>=10'}
cpu: [x64]
os: [darwin]
@@ -4826,8 +4934,8 @@ packages:
dev: false
optional: true
- resolution: {integrity: sha512-Eyqipf7ZPGj0vplKHo8JUOoU1un2sg5PjJMpEesX0k+6HKE2T8pdyeyXODN0YTFqzndSa/J43EEPXm+rHAsLFQ==}
+ resolution: {integrity: sha512-BVEZVOGnaZvEcHm//KyYzhte46vdF67wLVtmQEXPAlrkRgZ3b/JSySeLXqeocAcOANWb1/SPHlEmPK5azP+JvQ==}
engines: {node: '>=10'}
cpu: [arm]
os: [linux]
@@ -4835,8 +4943,8 @@ packages:
dev: false
optional: true
- resolution: {integrity: sha512-wZn02DH8VYPv3FC0ub4my52Rttsus/rFw+UUfzdb3tHMHXB66LqN+rR0ssIOZrH6K+VLN6qpTw9VizjyoH0BxA==}
+ resolution: {integrity: sha512-ZbOJfVbCjVMKdfvvJDOTpa3tGqU6tfxng1CDjA62RUcqa7sRbovrjSiw6mq5/4EoOF4zK8CtPIG+TlxKPapnuw==}
engines: {node: '>=10'}
cpu: [arm64]
os: [linux]
@@ -4844,8 +4952,8 @@ packages:
dev: false
optional: true
- resolution: {integrity: sha512-3G0D5z9hUj9bXNcwmA1eGiFTwe5rWkuL3DsoviTj73TKLpk7u64ND0XjEfO0huVv4vVu9H1jodrKb7nvln/dlw==}
+ resolution: {integrity: sha512-+Gjo1W4tY/4kgEe5h22iuCWkpKcPMccXwYaSLNvgBCBQADB0zKFfF0lNf7y6U+81NFEjhRsdwXMsRGZtgTpUrg==}
engines: {node: '>=10'}
cpu: [arm64]
os: [linux]
@@ -4853,8 +4961,8 @@ packages:
dev: false
optional: true
- resolution: {integrity: sha512-LFxn9U8cjmYHw3jrdPNqPAkBGglKE3tCZ8rA7hYyp0BFxuo7L2ZcEnPm4RFpmSCCsExFH+LEJWuMGgWERoktvg==}
+ resolution: {integrity: sha512-PR/VbGm0LEkhpm5qClovZWhE/jYoQSyIeyPh8XY39uUI1u2yEfuz5UCW2sJJIWOvNiAfu7+TjW+9H/I7zBBDJA==}
engines: {node: '>=10'}
cpu: [x64]
os: [linux]
@@ -4862,8 +4970,8 @@ packages:
dev: false
optional: true
- resolution: {integrity: sha512-dp0fAmreeVVYTUcb4u9njTPrYzKnbIH0EhH2qvC9GOYNNREUu2GezSIDgonjOXkHiTCvopG4xU7y56XtXj4VrQ==}
+ resolution: {integrity: sha512-poT9zub4CyVcH1cxwGdrGiZD3urfOaYs/Kd52ve3ymPPeQZq7qQwKqAB/9NxoSiJDaSzJv5OwTEfgaBYCyw0iw==}
engines: {node: '>=10'}
cpu: [x64]
os: [linux]
@@ -4871,8 +4979,8 @@ packages:
dev: false
optional: true
- resolution: {integrity: sha512-HlVIiLMQkzthAdqMslQhDkoXJ5+AOLUSTV6fm6shFKZKqc/9cJvr4S8UveNERL9zUficA36yM3bbfo36McwnvQ==}
+ resolution: {integrity: sha512-29V5/fBd6XXFb7J/ri9ZeSS/GTqXfSWa3BiE0zTNbASpQbEXf+YPYiAtO6c1HqNyQobKB9ni+w7sa8KkAGhHXw==}
engines: {node: '>=10'}
cpu: [arm64]
os: [win32]
@@ -4880,8 +4988,8 @@ packages:
dev: false
optional: true
- resolution: {integrity: sha512-WCF8faPGjCl4oIgugkp+kL9nl3nUATlzKXCEGFowMEmVVCFM0GsqlmGdPp1pjZoWc9tpYanoXQDnp5IvlDSLhA==}
+ resolution: {integrity: sha512-2lKEGEjpBOq0z4Nk0tFP9wxVwxgz7FonmjCkzJ95GBb5KNvMrgQQrGNGX6L0hoBo/a1kE752I6V5pOaMyIq5xQ==}
engines: {node: '>=10'}
cpu: [ia32]
os: [win32]
@@ -4889,8 +4997,8 @@ packages:
dev: false
optional: true
- resolution: {integrity: sha512-oV71rwiSpA5xre2C5570BhCsg1HF97SNLsZ/12xv7zayGzqr3yvFALFJN8tHKpqUdCB4FGPjoP3JFdV3i+1wUw==}
+ resolution: {integrity: sha512-xuN0oJhAewga8jNJkT5Wx25RPVnIEMZCYf4irqA5jiK6GckOdcXB8jvEJhggOxnJSW8RDsAtY5q+zw5kNkU+eA==}
engines: {node: '>=10'}
cpu: [x64]
os: [win32]
@@ -4898,8 +5006,8 @@ packages:
dev: false
optional: true
- resolution: {integrity: sha512-vWgY07R/eqj1/a0vsRKLI9o9klGZfpLNOVEnrv4nrccxBgYPjcf22IWwAoaBJ+wpA7Q4fVjCUM8lP0m01dpxcg==}
+ resolution: {integrity: sha512-P88AHGWM8xPY3Tjj5360V6vqKCS5UfsyffPJVnr7BKSr45rlG4/pjEGGmFYQjg6ztgPyrGLYz1jSyzajTqTVIA==}
engines: {node: '>=10'}
requiresBuild: true
peerDependencies:
@@ -4911,16 +5019,16 @@ packages:
'@swc/counter': 0.1.3
'@swc/types': 0.1.5
optionalDependencies:
- '@swc/core-darwin-arm64': 1.4.2
- '@swc/core-darwin-x64': 1.4.2
- '@swc/core-linux-arm-gnueabihf': 1.4.2
- '@swc/core-linux-arm64-gnu': 1.4.2
- '@swc/core-linux-arm64-musl': 1.4.2
- '@swc/core-linux-x64-gnu': 1.4.2
- '@swc/core-linux-x64-musl': 1.4.2
- '@swc/core-win32-arm64-msvc': 1.4.2
- '@swc/core-win32-ia32-msvc': 1.4.2
- '@swc/core-win32-x64-msvc': 1.4.2
+ '@swc/core-darwin-arm64': 1.4.4
+ '@swc/core-darwin-x64': 1.4.4
+ '@swc/core-linux-arm-gnueabihf': 1.4.4
+ '@swc/core-linux-arm64-gnu': 1.4.4
+ '@swc/core-linux-arm64-musl': 1.4.4
+ '@swc/core-linux-x64-gnu': 1.4.4
+ '@swc/core-linux-x64-musl': 1.4.4
+ '@swc/core-win32-arm64-msvc': 1.4.4
+ '@swc/core-win32-ia32-msvc': 1.4.4
+ '@swc/core-win32-x64-msvc': 1.4.4
dev: false
@@ -5567,6 +5675,16 @@ packages:
path-browserify: 1.0.1
dev: false
+ resolution: {integrity: sha512-gj81785z0JNzRcU0Mq98E56e4ltO1yf8k5PQ+tV/7YHnbZkrM0fyFyuttnN8ngJZjbpofWE/m4qjKBiLl8Ju4w==}
+ dependencies:
+ '@babel/parser': 7.23.9
+ '@vue/shared': 3.4.19
+ entities: 4.5.0
+ estree-walker: 2.0.2
+ source-map-js: 1.0.2
+ dev: false
+
resolution: {integrity: sha512-MjXawxZf2SbZszLPYxaFCjxfibYrzr3eYbKxwpLR9EQN+oaziSu3qKVbwBERj1IFIB8OLUewxB5m/BFzi613og==}
dependencies:
@@ -5576,6 +5694,13 @@ packages:
estree-walker: 2.0.2
source-map-js: 1.0.2
+ resolution: {integrity: sha512-vm6+cogWrshjqEHTzIDCp72DKtea8Ry/QVpQRYoyTIg9k7QZDX6D8+HGURjtmatfgM8xgCFtJJaOlCaRYRK3QA==}
+ dependencies:
+ '@vue/compiler-core': 3.4.19
+ '@vue/shared': 3.4.19
+ dev: false
+
resolution: {integrity: sha512-IZC6FKowtT1sl0CR5DpXSiEB5ayw75oT2bma1BEhV7RRR1+cfwLrxc2Z8Zq/RGFzJ8w5r9QtCOvTjQgdn0IKmA==}
dependencies:
@@ -5611,8 +5736,8 @@ packages:
dependencies:
'@volar/language-core': 1.11.1
'@volar/source-map': 1.11.1
- '@vue/compiler-dom': 3.4.21
- '@vue/shared': 3.4.21
+ '@vue/compiler-dom': 3.4.19
+ '@vue/shared': 3.4.19
computeds: 0.0.1
minimatch: 9.0.3
muggle-string: 0.3.1
@@ -5648,6 +5773,10 @@ packages:
'@vue/shared': 3.4.21
vue: 3.4.21([email protected])
+ resolution: {integrity: sha512-/KliRRHMF6LoiThEy+4c1Z4KB/gbPrGjWwJR+crg2otgrf/egKzRaCPvJ51S5oetgsgXLfc4Rm5ZgrKHZrtMSw==}
+ dev: false
+
resolution: {integrity: sha512-PuJe7vDIi6VYSinuEbUIQgMIRZGgM8e4R+G+/dQTk0X1NEdvgvvgv7m+rfmDH1gZzyA1OjjoWskvHlfRNfQf3g==}
@@ -7046,7 +7175,7 @@ packages:
postcss-modules-values: 4.0.0([email protected])
postcss-value-parser: 4.2.0
semver: 7.6.0
- webpack: 5.90.3(@swc/[email protected])([email protected])
+ webpack: 5.90.3(@swc/[email protected])([email protected])
dev: false
@@ -8877,7 +9006,7 @@ packages:
semver: 7.6.0
tapable: 2.2.1
typescript: 5.4.2
- webpack: 5.90.3(@swc/[email protected])([email protected])
+ webpack: 5.90.3(@swc/[email protected])([email protected])
dev: false
@@ -9378,8 +9507,8 @@ packages:
whatwg-encoding: 3.1.1
dev: true
- resolution: {integrity: sha512-igBTJcNNNhvZFRtm8uA6xMY6xYleeDwn3PeBCkDz7tHttv4F2hsDI2aPgNERWzvRcNYHNT3ymRaQzllmXj4YsQ==}
+ resolution: {integrity: sha512-K//PSRMQk4FZ78Kyau+mZurHn3FH0Vwr+H36eE0rPbeYkRRi9YxceYPhuN60UwWorxyKHhqoAJl2OFKa4BVtaA==}
dev: false
@@ -9421,7 +9550,7 @@ packages:
lodash: 4.17.21
pretty-error: 4.0.0
tapable: 2.2.1
- webpack: 5.90.3(@swc/[email protected])([email protected])
+ webpack: 5.90.3(@swc/[email protected])([email protected])
dev: false
@@ -10364,7 +10493,7 @@ packages:
optional: true
dependencies:
less: 4.2.0
- webpack: 5.90.3(@swc/[email protected])([email protected])
+ webpack: 5.90.3(@swc/[email protected])([email protected])
dev: false
@@ -13114,7 +13243,7 @@ packages:
resolution: {integrity: sha512-4QcZ+yx7nzEFiV4BMLnr/pRa5HYzNITX2ri0Zh6sT9EyQHbBHacC6YigllUPU9X3D0f/22QCgfokpKs52YRrUg==}
dev: false
resolution: {integrity: sha512-PEpxhAH+407KTcVDC7uUH4S26qtuBDC/JlZI3NqFYu0Tm2uCBf56On+13lK4iE3Iz8FORl4aSXo2RricJ/UhPQ==}
peerDependencies:
'@swc/core': ^1.2.152
@@ -13127,10 +13256,10 @@ packages:
optional: true
dependencies:
'@babel/runtime': 7.23.9
- '@swc/core': 1.4.2
+ '@swc/core': 1.4.4
deepmerge: 4.3.1
- swc-loader: 0.1.16(@swc/[email protected])([email protected])
- webpack: 5.90.3(@swc/[email protected])([email protected])
+ swc-loader: 0.1.16(@swc/[email protected])([email protected])
+ webpack: 5.90.3(@swc/[email protected])([email protected])
dev: false
@@ -13294,7 +13423,7 @@ packages:
peerDependencies:
webpack: ^5.0.0
dependencies:
- webpack: 5.90.3(@swc/[email protected])([email protected])
+ webpack: 5.90.3(@swc/[email protected])([email protected])
dev: false
@@ -13320,25 +13449,25 @@ packages:
resolution: {integrity: sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w==}
engines: {node: '>= 0.4'}
resolution: {integrity: sha512-NKIm8aJjK/z/yfzk+v7YGwJMjBKaLaUs9ZKI2zoaIGKAjtkwjO92ZLI0fiTZuwzRqVLQl/29fBdSgFCBzquR0w==}
peerDependencies:
'@swc/core': ^1.2.147
webpack: '>=2'
dependencies:
- '@swc/core': 1.4.2
- webpack: 5.90.3(@swc/[email protected])([email protected])
+ '@swc/core': 1.4.4
+ webpack: 5.90.3(@swc/[email protected])([email protected])
dev: false
resolution: {integrity: sha512-9Zi9UP2YmDpgmQVbyOPJClY0dwf58JDyDMQ7uRc4krmc72twNI2fvlBWHLqVekBpPc7h5NJkGVT1zNDxFrqhvg==}
peerDependencies:
'@swc/core': ^1.2.147
webpack: '>=2'
dependencies:
- '@swc/core': 1.4.2
+ '@swc/core': 1.4.4
'@swc/counter': 0.1.3
- webpack: 5.90.3(@swc/[email protected])([email protected])
+ webpack: 5.90.3(@swc/[email protected])([email protected])
dev: false
@@ -13423,7 +13552,7 @@ packages:
type-fest: 0.16.0
unique-string: 2.0.0
resolution: {integrity: sha512-BKFPWlPDndPs+NGGCr1U59t0XScL5317Y0UReNrHaw9/FwhPENlq6bfgs+4yPfyP51vqC1bQ4rp1EfXW5ZSH9w==}
engines: {node: '>= 10.13.0'}
peerDependencies:
@@ -13440,13 +13569,13 @@ packages:
optional: true
dependencies:
'@jridgewell/trace-mapping': 0.3.22
- '@swc/core': 1.4.2
+ '@swc/core': 1.4.4
esbuild: 0.20.1
jest-worker: 27.5.1
schema-utils: 3.3.0
serialize-javascript: 6.0.2
terser: 5.28.1
- webpack: 5.90.3(@swc/[email protected])([email protected])
+ webpack: 5.90.3(@swc/[email protected])([email protected])
dev: false
@@ -14400,14 +14529,14 @@ packages:
mime-types: 2.1.35
range-parser: 1.2.1
schema-utils: 4.2.0
- webpack: 5.90.3(@swc/[email protected])([email protected])
+ webpack: 5.90.3(@swc/[email protected])([email protected])
dev: false
resolution: {integrity: sha512-khZGfAeJx6I8K9zKohEWWYN6KDlVw2DHownoe+6Vtwj1LP9WFgegXnVMSkZ/dBEBtXFwrkkydsaPFlB7f8wU2A==}
dependencies:
ansi-html-community: 0.0.8
- html-entities: 2.4.0
+ html-entities: 2.5.2
strip-ansi: 6.0.1
dev: false
@@ -14424,7 +14553,7 @@ packages:
resolution: {integrity: sha512-poXpCylU7ExuvZK8z+On3kX+S8o/2dQ/SVYueKA0D4WEMXROXgY8Ez50/bQEUmvoSMMrWcrJqCHuhAbsiwg7Dg==}
dev: false
resolution: {integrity: sha512-h6uDYlWCctQRuXBs1oYpVe6sFcWedl0dpcVaTf/YF67J9bKvwJajFulMVSYKHrksMB3I/pIagRzDxwxkebuzKA==}
engines: {node: '>=10.13.0'}
hasBin: true
@@ -14455,7 +14584,7 @@ packages:
neo-async: 2.6.2
schema-utils: 3.3.0
tapable: 2.2.1
- terser-webpack-plugin: 5.3.10(@swc/[email protected])([email protected])([email protected])
+ terser-webpack-plugin: 5.3.10(@swc/[email protected])([email protected])([email protected])
watchpack: 2.4.0
webpack-sources: 3.2.3
transitivePeerDependencies: