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.

refactor(sheets): refactor sheets selections (#2710)

lumix71cfe6a5a3f3
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index c240cced5c..4283fca958 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -185,7 +185,7 @@ pnpm test:e2e
### Clean code
-> Programs are meant to be ready by humans and only icidentally for computers to execute. - Harold Abelson
+> Programs are meant to be ready by humans and only incidentally for computers to execute. - Harold Abelson
- Do not expose properties or methods those are not necessary to be exposed.
- Group related methods or properties together. Do not always use blank lines to separate them.
diff --git a/examples/src/sheets/main.ts b/examples/src/sheets/main.ts
index 756213395d..388c1bf33b 100644
--- a/examples/src/sheets/main.ts
+++ b/examples/src/sheets/main.ts
@@ -45,11 +45,11 @@ import { UniverRPCMainThreadPlugin } from '@univerjs/rpc';
import { UniverSheetsFormulaPlugin } from '@univerjs/sheets-formula';
import { UniverSheetsNumfmtPlugin } from '@univerjs/sheets-numfmt';
import { UniverSheetsDataValidationPlugin } from '@univerjs/sheets-data-validation';
-import { UniverSheetsDrawingUIPlugin } from '@univerjs/sheets-drawing-ui';
import { FUniver } from '@univerjs/facade';
import { UniverSheetsZenEditorPlugin } from '@univerjs/sheets-zen-editor';
import { UniverSheetsSortPlugin } from '@univerjs/sheets-sort';
import { UniverSheetsSortUIPlugin } from '@univerjs/sheets-sort-ui';
+import { UniverSheetsDrawingUIPlugin } from '@univerjs/sheets-drawing-ui';
import { enUS, ruRU, zhCN } from '../locales';
import { DEFAULT_WORKBOOK_DATA_DEMO } from '../data/sheets/demo/default-workbook-data-demo';
/* eslint-disable-next-line node/prefer-global/process */
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index 4a0dee713e..257316a11b 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -107,7 +107,7 @@ export {
UndoCommandId,
} from './services/undoredo/undoredo.service';
export * from './shared';
-export { fromCallback } from './shared/rxjs';
+export { fromCallback, takeAfter } from './shared/rxjs';
export { UserManagerService, type IUser } from './services/user-manager/user-manager.service';
// #region sheet
diff --git a/packages/core/src/services/lifecycle/lifecycle.service.ts b/packages/core/src/services/lifecycle/lifecycle.service.ts
index cc75848deb..b233c52a3e 100644
--- a/packages/core/src/services/lifecycle/lifecycle.service.ts
+++ b/packages/core/src/services/lifecycle/lifecycle.service.ts
@@ -16,10 +16,12 @@
import type { DependencyIdentifier } from '@wendellhu/redi';
import { Inject, Injector } from '@wendellhu/redi';
-import { BehaviorSubject, Observable } from 'rxjs';
+import type { Observable } from 'rxjs';
+import { BehaviorSubject, merge, of, skip } from 'rxjs';
import { Disposable } from '../../shared/lifecycle';
import { ILogService } from '../log/log.service';
+import { takeAfter } from '../../shared/rxjs';
import { LifecycleNameMap, LifecycleStages, LifecycleToModules } from './lifecycle';
/**
@@ -75,31 +77,8 @@ export class LifecycleService extends Disposable {
* @returns
*/
subscribeWithPrevious(): Observable<LifecycleStages> {
- return new Observable<LifecycleStages>((subscriber) => {
- // Before subscribe, emit the current stage and all previous stages.
- // Since `this._lifecycle$` is a BehaviorSubject, it will emit the current stage immediately.
- // So we just need to manually next all previous stages.
- if (this.stage === LifecycleStages.Starting) {
- // do nothing
- } else if (this.stage === LifecycleStages.Ready) {
- subscriber.next(LifecycleStages.Starting);
- } else if (this.stage === LifecycleStages.Rendered) {
- subscriber.next(LifecycleStages.Starting);
- subscriber.next(LifecycleStages.Ready);
- } else {
- subscriber.next(LifecycleStages.Starting);
- subscriber.next(LifecycleStages.Ready);
- subscriber.next(LifecycleStages.Rendered);
- }
-
- this._lifecycle$.subscribe((stage) => {
- subscriber.next(stage);
-
- if (stage === LifecycleStages.Steady) {
- subscriber.complete();
- }
- });
- });
+ return merge(getLifecycleStagesAndBefore(this.stage), this._lifecycle$.pipe(skip(1)))
+ .pipe(takeAfter((s) => s === LifecycleStages.Steady));
}
private _reportProgress(stage: LifecycleStages): void {
@@ -117,7 +96,6 @@ export class LifecycleInitializerService extends Disposable {
private _seenTokens = new Set<DependencyIdentifier<unknown>>();
constructor(
- @Inject(LifecycleService) private _lifecycleService: LifecycleService,
@Inject(Injector) private readonly _injector: Injector
) {
super();
@@ -134,3 +112,21 @@ export class LifecycleInitializerService extends Disposable {
});
}
}
+
+export function getLifecycleStagesAndBefore(lifecycleStage: LifecycleStages): Observable<LifecycleStages> {
+ switch (lifecycleStage) {
+ case LifecycleStages.Starting:
+ return of(LifecycleStages.Starting);
+ case LifecycleStages.Ready:
+ return of(LifecycleStages.Starting, LifecycleStages.Ready);
+ case LifecycleStages.Rendered:
+ return of(LifecycleStages.Starting, LifecycleStages.Ready, LifecycleStages.Rendered);
+ default:
+ return of(
+ LifecycleStages.Starting,
+ LifecycleStages.Ready,
+ LifecycleStages.Rendered,
+ LifecycleStages.Steady
+ );
+ }
+}
diff --git a/packages/core/src/services/plugin/plugin.service.ts b/packages/core/src/services/plugin/plugin.service.ts
index 1aa9fe5e8a..7bac5ea5a7 100644
--- a/packages/core/src/services/plugin/plugin.service.ts
+++ b/packages/core/src/services/plugin/plugin.service.ts
@@ -16,12 +16,12 @@
import type { Ctor, IDisposable } from '@wendellhu/redi';
import { Inject, Injector } from '@wendellhu/redi';
-import { finalize } from 'rxjs';
+import { skip } from 'rxjs';
import { Disposable } from '../../shared/lifecycle';
import { type UnitType, UniverInstanceType } from '../../common/unit';
import { LifecycleStages } from '../lifecycle/lifecycle';
-import { LifecycleInitializerService, LifecycleService } from '../lifecycle/lifecycle.service';
+import { getLifecycleStagesAndBefore, LifecycleInitializerService, LifecycleService } from '../lifecycle/lifecycle.service';
import { ILogService } from '../log/log.service';
import { DependentOnSymbol, type Plugin, type PluginCtor, PluginRegistry, PluginStore } from './plugin';
@@ -180,6 +180,8 @@ export class PluginHolder extends Disposable {
/** Stores initialized plugin instances. */
protected readonly _pluginStore = new PluginStore();
+ private readonly _awaitingPlugins: Plugin[][] = [];
+
constructor(
private _checkPluginRegistered: (pluginCtor: PluginCtor) => boolean,
private _registerPlugin: <T extends PluginCtor>(plugin: T, config?: ConstructorParameters<T>[0]) => void,
@@ -189,6 +191,10 @@ export class PluginHolder extends Disposable {
@Inject(LifecycleInitializerService) protected readonly _lifecycleInitializerService: LifecycleInitializerService
) {
super();
+
+ this.disposeWithMe(this._lifecycleService.lifecycle$.pipe(skip(1)).subscribe((stage) => {
+ this._awaitingPlugins.forEach((plugins) => this._runStage(plugins, stage));
+ }));
}
override dispose(): void {
@@ -198,6 +204,8 @@ export class PluginHolder extends Disposable {
this._pluginStore.removePlugins();
this._pluginRegistry.removePlugins();
+
+ this._awaitingPlugins.length = 0;
}
register<T extends PluginCtor<Plugin>>(pluginCtor: T, config?: ConstructorParameters<T>[0]): void {
@@ -222,6 +230,10 @@ export class PluginHolder extends Disposable {
};
const plugins = this._pluginRegistry.getRegisterPlugins().map(({ plugin, options }) => this._initPlugin(plugin, options));
+ if (!plugins.length) {
+ return;
+ }
+
this._pluginsRunLifecycle(plugins);
this._pluginRegistry.removePlugins();
}
@@ -257,31 +269,35 @@ export class PluginHolder extends Disposable {
return pluginInstance;
}
+ // Here we should be careful with the sequence of which plugin should run first. We should manually add a queue here.
+ // Because laterly registered plugins may get executed first.
+
protected _pluginsRunLifecycle(plugins: Plugin[]): void {
- const run = (lifecycle: LifecycleStages) => {
- plugins.forEach((p) => {
- switch (lifecycle) {
- case LifecycleStages.Starting:
- p.onStarting(this._injector);
- break;
- case LifecycleStages.Ready:
- p.onReady();
- break;
- case LifecycleStages.Rendered:
- p.onRendered();
- break;
- case LifecycleStages.Steady:
- p.onSteady();
- break;
- }
- this._lifecycleInitializerService.initModulesOnStage(lifecycle);
- });
- };
+ // Let plugins go through already reached lifecycle stages.
+ getLifecycleStagesAndBefore(this._lifecycleService.stage).subscribe((stage) => this._runStage(plugins, stage));
+ // Push to the queue for later lifecycles.
+ this._awaitingPlugins.push(plugins);
+ }
+
+ private _runStage(plugins: Plugin[], stage: LifecycleStages): void {
+ plugins.forEach((p) => {
+ switch (stage) {
+ case LifecycleStages.Starting:
+ p.onStarting(this._injector);
+ break;
+ case LifecycleStages.Ready:
+ p.onReady();
+ break;
+ case LifecycleStages.Rendered:
+ p.onRendered();
+ break;
+ case LifecycleStages.Steady:
+ p.onSteady();
+ break;
+ }
+ });
- const subscription = this.disposeWithMe(this._lifecycleService.subscribeWithPrevious()
- // It has to been async because the finalize may execute synchronously after we
- // make the subscription. For example, the lifecycle service is already in stage "steady".
- .pipe(finalize(() => { Promise.resolve().then(() => subscription.dispose()); }))
- .subscribe((stage) => { run(stage); }));
+ // Plugins run first, and then we should run the modules.
+ this._lifecycleInitializerService.initModulesOnStage(stage);
}
}
diff --git a/packages/core/src/shared/__tests__/rxjs.spec.ts b/packages/core/src/shared/__tests__/rxjs.spec.ts
new file mode 100644
index 0000000000..1e90df1e25
--- /dev/null
+++ b/packages/core/src/shared/__tests__/rxjs.spec.ts
@@ -0,0 +1,29 @@
+/**
+ * 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 { of } from 'rxjs';
+import { describe, expect, it } from 'vitest';
+import { takeAfter } from '../rxjs';
+
+describe('test custom rxjs utils', () => {
+ it('should terminate when a condition is met with "takeAfter"', () => {
+ const acculated: number[] = [];
+ const nums$ = of(1, 2, 3, 4, 5);
+ nums$.pipe(takeAfter((val) => val === 3)).subscribe((v) => acculated.push(v));
+ expect(acculated).toEqual([1, 2, 3]);
+ });
+});
+
diff --git a/packages/core/src/shared/common.ts b/packages/core/src/shared/common.ts
index 464e5d534e..5320faff71 100644
--- a/packages/core/src/shared/common.ts
+++ b/packages/core/src/shared/common.ts
@@ -31,11 +31,7 @@ import { ColorBuilder } from './color/color';
import { Tools } from './tools';
import type { Nullable } from './types';
-export function makeCellToSelection(cellInfo: Nullable<ISelectionCellWithMergeInfo>): Nullable<IRangeWithCoord> {
- if (!cellInfo) {
- return;
- }
-
+export function makeCellToSelection(cellInfo: ISelectionCellWithMergeInfo): IRangeWithCoord {
const { actualRow, actualColumn, isMerged, isMergedMainCell, mergeInfo } = cellInfo;
let { startY, endY, startX, endX } = cellInfo;
let startRow = actualRow;
diff --git a/packages/core/src/shared/rxjs.ts b/packages/core/src/shared/rxjs.ts
index ea22df6f3e..a7e326ac96 100644
--- a/packages/core/src/shared/rxjs.ts
+++ b/packages/core/src/shared/rxjs.ts
@@ -34,3 +34,26 @@ export function fromCallback<T extends readonly unknown[]>(callback: CallbackFn<
return () => disposable?.dispose();
});
};
+
+/**
+ * An operator that would complete the stream once a condition is met. Consider it as a shortcut of `takeUntil`.
+ */
+export function takeAfter<T>(callback: (value: T) => boolean) {
+ return function complateAfter(source: Observable<T>) {
+ return new Observable<T>((subscriber) => {
+ source.subscribe({
+ next: (v) => {
+ subscriber.next(v);
+ if (callback(v)) {
+ subscriber.complete();
+ }
+ },
+ complete: () => subscriber.complete(),
+ error: (error) => subscriber.error(error),
+ });
+
+ return () => subscriber.unsubscribe();
+ });
+ };
+}
+
diff --git a/packages/core/src/sheets/workbook.ts b/packages/core/src/sheets/workbook.ts
index e1cc72739c..c38dc76833 100644
--- a/packages/core/src/sheets/workbook.ts
+++ b/packages/core/src/sheets/workbook.ts
@@ -107,7 +107,7 @@ export class Workbook extends UnitModel<IWorkbookData, UniverInstanceType.UNIVER
this._name$ = new BehaviorSubject(workbookData.name || '');
this.name$ = this._name$.asObservable();
- this._passWorksheetSnapshots();
+ this._parseWorksheetSnapshots();
}
override dispose(): void {
@@ -205,9 +205,16 @@ export class Workbook extends UnitModel<IWorkbookData, UniverInstanceType.UNIVER
}
/**
- * Get the active sheet
+ * Get the active sheet.
*/
- getActiveSheet(): Nullable<Worksheet> {
+
+ getActiveSheet(): Worksheet;
+ getActiveSheet(allowNull: true): Nullable<Worksheet>;
+ getActiveSheet(allowNull?: true): Nullable<Worksheet> {
+ if (!this._activeSheet && typeof allowNull === 'undefined') {
+ throw new Error(`[Workbook]: no active Worksheet on Workbook ${this._unitId}!`);
+ }
+
return this._activeSheet;
}
@@ -217,13 +224,14 @@ export class Workbook extends UnitModel<IWorkbookData, UniverInstanceType.UNIVER
* @returns
*/
ensureActiveSheet() {
- const currentActive = this.getActiveSheet();
+ const currentActive = this._activeSheet;
if (currentActive) {
return currentActive;
}
- /**
- * If the first sheet is hidden, we should set the first unhidden sheet to be active.
- */
+
+ /**
+ * If the first sheet is hidden, we should set the first unhidden sheet to be active.
+ */
const sheetOrder = this._snapshot.sheetOrder;
for (let i = 0, len = sheetOrder.length; i < len; i++) {
const worksheet = this._worksheets.get(sheetOrder[i]);
@@ -382,7 +390,7 @@ export class Workbook extends UnitModel<IWorkbookData, UniverInstanceType.UNIVER
/**
* Get Default Sheet
*/
- private _passWorksheetSnapshots(): void {
+ private _parseWorksheetSnapshots(): void {
const { _snapshot, _worksheets } = this;
const { sheets, sheetOrder } = _snapshot;
diff --git a/packages/core/src/types/interfaces/i-range.ts b/packages/core/src/types/interfaces/i-range.ts
index 06970edb5d..a6cf9f917a 100644
--- a/packages/core/src/types/interfaces/i-range.ts
+++ b/packages/core/src/types/interfaces/i-range.ts
@@ -48,6 +48,20 @@ export interface IRowRange {
endRow: number;
}
+export interface IColumnRange {
+ /**
+ * The start column (inclusive) of the range
+ * startColumn
+ */
+ startColumn: number;
+
+ /**
+ * The end column (exclusive) of the range
+ * endColumn
+ */
+ endColumn: number;
+}
+
/**
* Range data structure
*
@@ -63,18 +77,7 @@ export interface IRowRange {
*
* means "A1:B2"
*/
-export interface IRange extends IRowRange {
- /**
- * The start column (inclusive) of the range
- * startColumn
- */
- startColumn: number;
-
- /**
- * The end column (exclusive) of the range
- * endColumn
- */
- endColumn: number;
+export interface IRange extends IRowRange, IColumnRange {
rangeType?: RANGE_TYPE;
diff --git a/packages/data-validation/src/common/util.ts b/packages/data-validation/src/common/util.ts
index 5c6592c69d..413f138f30 100644
--- a/packages/data-validation/src/common/util.ts
+++ b/packages/data-validation/src/common/util.ts
@@ -15,7 +15,7 @@
*/
import { DataValidationOperator, DataValidationType, type IDataValidationRuleBase, type IDataValidationRuleOptions, Tools } from '@univerjs/core';
-import { SelectionManagerService } from '@univerjs/sheets';
+import { SheetsSelectionsService } from '@univerjs/sheets';
import type { IAccessor } from '@wendellhu/redi';
export function getRuleSetting(rule: IDataValidationRuleBase): IDataValidationRuleBase {
@@ -44,8 +44,8 @@ export function getRuleOptions(rule: IDataValidationRuleOptions): IDataValidatio
}
export function createDefaultNewRule(accessor: IAccessor) {
- const selectionManagerService = accessor.get(SelectionManagerService);
- const currentRanges = selectionManagerService.getSelectionRanges();
+ const selectionManagerService = accessor.get(SheetsSelectionsService);
+ const currentRanges = selectionManagerService.getCurrentSelections().map((s) => s.range);
const uid = Tools.generateRandomId(6);
const rule = {
uid,
diff --git a/packages/docs-drawing-ui/src/plugin.ts b/packages/docs-drawing-ui/src/plugin.ts
index 1747fe8d22..f227ff05cd 100644
--- a/packages/docs-drawing-ui/src/plugin.ts
+++ b/packages/docs-drawing-ui/src/plugin.ts
@@ -51,7 +51,7 @@ export class UniverDocsDrawingUIPlugin extends Plugin {
override onReady(): void {
([
- DocDrawingUpdateRenderController,
- ]).forEach((m) => this._renderManagerSrv.registerRenderModule(UniverInstanceType.UNIVER_DOC, m));
+ [DocDrawingUpdateRenderController],
+ ] as Dependency[]).forEach((m) => this._renderManagerSrv.registerRenderModule(UniverInstanceType.UNIVER_DOC, m));
}
}
diff --git a/packages/docs-hyper-link-ui/src/plugin.ts b/packages/docs-hyper-link-ui/src/plugin.ts
index b7d050ec97..b52258034e 100644
--- a/packages/docs-hyper-link-ui/src/plugin.ts
+++ b/packages/docs-hyper-link-ui/src/plugin.ts
@@ -63,7 +63,7 @@ export class UniverDocsHyperLinkUIPlugin extends Plugin {
private _initRenderModule() {
[DocHyperLinkRenderController].forEach((dep) => {
- this._renderManagerSrv.registerRenderModule(UniverInstanceType.UNIVER_DOC, dep);
+ this._renderManagerSrv.registerRenderModule(UniverInstanceType.UNIVER_DOC, dep as unknown as Dependency);
});
}
}
diff --git a/packages/docs-thread-comment-ui/src/plugin.ts b/packages/docs-thread-comment-ui/src/plugin.ts
index 02ae4b065e..05bf08bbac 100644
--- a/packages/docs-thread-comment-ui/src/plugin.ts
+++ b/packages/docs-thread-comment-ui/src/plugin.ts
@@ -61,7 +61,7 @@ export class UniverDocsThreadCommentUIPlugin extends Plugin {
private _initRenderModule() {
[DocThreadCommentRenderController].forEach((dep) => {
- this._renderManagerSrv.registerRenderModule(UniverInstanceType.UNIVER_DOC, dep);
+ this._renderManagerSrv.registerRenderModule(UniverInstanceType.UNIVER_DOC, dep as unknown as Dependency);
});
}
}
diff --git a/packages/docs-ui/src/docs-ui-plugin.ts b/packages/docs-ui/src/docs-ui-plugin.ts
index 546bee66da..a1ad0bad3d 100644
--- a/packages/docs-ui/src/docs-ui-plugin.ts
+++ b/packages/docs-ui/src/docs-ui-plugin.ts
@@ -27,7 +27,7 @@ import { Inject, Injector } from '@wendellhu/redi';
import { IEditorService, IShortcutService } from '@univerjs/ui';
import { IRenderManagerService } from '@univerjs/engine-render';
-import { DocInterceptorService, DocSkeletonManagerService } from '@univerjs/docs';
+import { DocSkeletonManagerService } from '@univerjs/docs';
import {
MoveCursorDownShortcut,
MoveCursorLeftShortcut,
@@ -140,22 +140,21 @@ export class UniverDocsUIPlugin extends Plugin {
private _initRenderBasics(): void {
([
- DocSkeletonManagerService,
- DocInterceptorService,
- DocRenderController,
- DocZoomRenderController,
- ]).forEach((m) => {
+ [DocSkeletonManagerService],
+ [DocRenderController],
+ [DocZoomRenderController],
+ ] as Dependency[]).forEach((m) => {
this._renderManagerSrv.registerRenderModule(UniverInstanceType.UNIVER_DOC, m);
});
}
private _initRenderModules(): void {
([
- DocBackScrollRenderController,
- DocFloatingObjectRenderController,
- DocTextSelectionRenderController,
- DocHeaderFooterController,
- ]).forEach((m) => {
+ [DocBackScrollRenderController],
+ [DocFloatingObjectRenderController],
+ [DocTextSelectionRenderController],
+ [DocHeaderFooterController],
+ ] as Dependency[]).forEach((m) => {
this._renderManagerSrv.registerRenderModule(UniverInstanceType.UNIVER_DOC, m);
});
}
diff --git a/packages/docs-ui/src/services/clipboard/clipboard.service.ts b/packages/docs-ui/src/services/clipboard/clipboard.service.ts
index 29a5822cb2..86e1970cf1 100644
--- a/packages/docs-ui/src/services/clipboard/clipboard.service.ts
+++ b/packages/docs-ui/src/services/clipboard/clipboard.service.ts
@@ -125,7 +125,7 @@ export class DocClipboardService extends Disposable implements IDocClipboardServ
endOffset: activeEndOffset,
style,
} = this._textSelectionManagerService.getActiveRange() ?? {};
- const ranges = this._textSelectionManagerService.getSelections();
+ const ranges = this._textSelectionManagerService.getCurrentSelections();
if (segmentId == null) {
this._logService.error('[DocClipboardController] segmentId is not existed');
@@ -177,7 +177,7 @@ export class DocClipboardService extends Disposable implements IDocClipboardServ
});
const activeRange = this._textSelectionManagerService.getActiveRange();
const { segmentId, endOffset: activeEndOffset, style } = activeRange || {};
- const ranges = this._textSelectionManagerService.getSelections();
+ const ranges = this._textSelectionManagerService.getCurrentSelections();
if (segmentId == null) {
this._logService.error('[DocClipboardController] segmentId does not exist!');
@@ -247,7 +247,7 @@ export class DocClipboardService extends Disposable implements IDocClipboardServ
}
private _getDocumentBodyInRanges(): IDocumentBody[] {
- const ranges = this._textSelectionManagerService.getSelections();
+ const ranges = this._textSelectionManagerService.getCurrentSelections();
const activeRange = this._textSelectionManagerService.getActiveRange();
const docDataModel = this._univerInstanceService.getCurrentUniverDocInstance();
const results: IDocumentBody[] = [];
diff --git a/packages/docs/src/commands/commands/__tests__/create-command-test-bed.ts b/packages/docs/src/commands/commands/__tests__/create-command-test-bed.ts
index 0cae288102..15839c6347 100644
--- a/packages/docs/src/commands/commands/__tests__/create-command-test-bed.ts
+++ b/packages/docs/src/commands/commands/__tests__/create-command-test-bed.ts
@@ -160,7 +160,7 @@ export function createCommandTestBed(workbookData?: IDocumentData, dependencies?
export class MockRenderManagerService implements Pick<IRenderManagerService, 'getRenderById'> {
constructor(
@Inject(Injector) private readonly _injector: Injector
- ) {}
+ ) { }
getRenderById(_unitId: string): Nullable<IRender> {
return {
diff --git a/packages/docs/src/commands/commands/clipboard.inner.command.ts b/packages/docs/src/commands/commands/clipboard.inner.command.ts
index 61d1dd3ef6..05c41c65a7 100644
--- a/packages/docs/src/commands/commands/clipboard.inner.command.ts
+++ b/packages/docs/src/commands/commands/clipboard.inner.command.ts
@@ -59,7 +59,7 @@ export const InnerPasteCommand: ICommand<IInnerPasteCommandParams> = {
const textSelectionManagerService = accessor.get(TextSelectionManagerService);
const univerInstanceService = accessor.get(IUniverInstanceService);
- const selections = textSelectionManagerService.getSelections();
+ const selections = textSelectionManagerService.getCurrentSelections();
if (!Array.isArray(selections) || selections.length === 0) {
return false;
}
@@ -143,7 +143,7 @@ export const CutContentCommand: ICommand<IInnerCutCommandParams> = {
const textSelectionManagerService = accessor.get(TextSelectionManagerService);
const univerInstanceService = accessor.get(IUniverInstanceService);
- const selections = textSelectionManagerService.getSelections();
+ const selections = textSelectionManagerService.getCurrentSelections();
if (!Array.isArray(selections) || selections.length === 0) {
return false;
diff --git a/packages/docs/src/commands/commands/delete.command.ts b/packages/docs/src/commands/commands/delete.command.ts
index 266a1f7d56..42cb9f2337 100644
--- a/packages/docs/src/commands/commands/delete.command.ts
+++ b/packages/docs/src/commands/commands/delete.command.ts
@@ -57,7 +57,7 @@ export const MergeTwoParagraphCommand: ICommand<IMergeTwoParagraphParams> = {
const { direction, range } = params;
const activeRange = textSelectionManagerService.getActiveRange();
- const ranges = textSelectionManagerService.getSelections();
+ const ranges = textSelectionManagerService.getCurrentSelections();
if (activeRange == null || ranges == null) {
return false;
@@ -168,7 +168,7 @@ export const DeleteLeftCommand: ICommand = {
const unitId = docDataModel.getUnitId();
const docSkeletonManagerService = getCommandSkeleton(accessor, unitId);
const activeRange = textSelectionManagerService.getActiveRange();
- const ranges = textSelectionManagerService.getSelections();
+ const ranges = textSelectionManagerService.getCurrentSelections();
const skeleton = docSkeletonManagerService?.getSkeleton();
if (activeRange == null || skeleton == null || ranges == null) {
return false;
@@ -317,8 +317,7 @@ export const DeleteRightCommand: ICommand = {
const commandService = accessor.get(ICommandService);
const activeRange = textSelectionManagerService.getActiveRange();
- const ranges = textSelectionManagerService.getSelections();
-
+ const ranges = textSelectionManagerService.getCurrentSelections();
const skeleton = docSkeletonManagerService?.getSkeleton();
if (activeRange == null || skeleton == null || ranges == null) {
return false;
diff --git a/packages/docs/src/commands/commands/inline-format.command.ts b/packages/docs/src/commands/commands/inline-format.command.ts
index d596c327f5..826d032a50 100644
--- a/packages/docs/src/commands/commands/inline-format.command.ts
+++ b/packages/docs/src/commands/commands/inline-format.command.ts
@@ -266,7 +266,7 @@ export const SetInlineFormatCommand: ICommand<ISetInlineFormatCommandParams> = {
const textSelectionManagerService = accessor.get(TextSelectionManagerService);
const univerInstanceService = accessor.get(IUniverInstanceService);
- const selections = textSelectionManagerService.getSelections();
+ const selections = textSelectionManagerService.getCurrentSelections();
if (!Array.isArray(selections) || selections.length === 0) {
return false;
diff --git a/packages/docs/src/commands/commands/list.command.ts b/packages/docs/src/commands/commands/list.command.ts
index c718ba9820..dafc4fad11 100644
--- a/packages/docs/src/commands/commands/list.command.ts
+++ b/packages/docs/src/commands/commands/list.command.ts
@@ -60,7 +60,7 @@ export const ListOperationCommand: ICommand<IListOperationCommandParams> = {
const { segmentId } = activeRange;
- const selections = textSelectionManagerService.getSelections() ?? [];
+ const selections = textSelectionManagerService.getCurrentSelections() ?? [];
const paragraphs = docDataModel.getSelfOrHeaderFooterModel(segmentId).getBody()?.paragraphs;
const serializedSelections = selections.map(serializeTextRange);
diff --git a/packages/docs/src/commands/commands/paragraph-align.command.ts b/packages/docs/src/commands/commands/paragraph-align.command.ts
index 9139146742..8da6660335 100644
--- a/packages/docs/src/commands/commands/paragraph-align.command.ts
+++ b/packages/docs/src/commands/commands/paragraph-align.command.ts
@@ -55,7 +55,7 @@ export const AlignOperationCommand: ICommand<IAlignOperationCommandParams> = {
return false;
}
const { segmentId } = activeRange;
- const selections = textSelectionManagerService.getSelections() ?? [];
+ const selections = textSelectionManagerService.getCurrentSelections() ?? [];
const paragraphs = docDataModel.getSelfOrHeaderFooterModel(segmentId).getBody()?.paragraphs;
const serializedSelections = selections.map(serializeTextRange);
diff --git a/packages/docs/src/commands/commands/replace-content.command.ts b/packages/docs/src/commands/commands/replace-content.command.ts
index c966430700..ade66dad8f 100644
--- a/packages/docs/src/commands/commands/replace-content.command.ts
+++ b/packages/docs/src/commands/commands/replace-content.command.ts
@@ -28,6 +28,7 @@ interface IReplaceContentCommandParams {
body: IDocumentBody; // Do not contain `\r\n` at the end.
textRanges: ITextRangeWithStyle[];
segmentId?: string;
+ options: { [key: string]: boolean };
}
// Replace all content with new body, and reserve undo/redo stack.
@@ -44,7 +45,7 @@ export const ReplaceContentCommand: ICommand<IReplaceContentCommandParams> = {
const docDataModel = univerInstanceService.getUniverDocInstance(unitId);
const prevBody = docDataModel?.getSnapshot().body;
- const selections = textSelectionManagerService.getSelections();
+ const selections = textSelectionManagerService.getCurrentSelections();
if (docDataModel == null || prevBody == null) {
return false;
diff --git a/packages/docs/src/commands/mutations/core-editing.mutation.ts b/packages/docs/src/commands/mutations/core-editing.mutation.ts
index f39c4f34a0..42f0675889 100644
--- a/packages/docs/src/commands/mutations/core-editing.mutation.ts
+++ b/packages/docs/src/commands/mutations/core-editing.mutation.ts
@@ -34,6 +34,7 @@ export interface IRichTextEditingMutationParams extends IMutationCommonParams {
noHistory?: boolean;
// Do you need to compose the undo and redo of history, and compose of the change states.
debounce?: boolean;
+ options?: { [key: string]: boolean };
}
const RichTextEditingMutationId = 'doc.mutation.rich-text-editing';
@@ -71,7 +72,7 @@ export const RichTextEditingMutation: IMutation<IRichTextEditingMutationParams,
}
const textSelectionManagerService = accessor.get(TextSelectionManagerService);
- const selections = textSelectionManagerService.getSelections() ?? [];
+ const selections = textSelectionManagerService.getCurrentSelections() ?? [];
const serializedSelections = selections.map(serializeTextRange);
@@ -108,7 +109,7 @@ export const RichTextEditingMutation: IMutation<IRichTextEditingMutationParams,
// Make sure update cursor & selection after doc skeleton is calculated.
if (!noNeedSetTextRange && textRanges && trigger != null) {
queueMicrotask(() => {
- textSelectionManagerService.replaceTextRanges(textRanges);
+ textSelectionManagerService.replaceTextRanges(textRanges, true, params.options);
});
}
diff --git a/packages/docs/src/controllers/move-cursor.controller.ts b/packages/docs/src/controllers/move-cursor.controller.ts
index 69f90c02b6..dfe0e6e336 100644
--- a/packages/docs/src/controllers/move-cursor.controller.ts
+++ b/packages/docs/src/controllers/move-cursor.controller.ts
@@ -92,7 +92,7 @@ export class MoveCursorController extends Disposable {
// eslint-disable-next-line max-lines-per-function, complexity
private _handleShiftMoveSelection(direction: Direction) {
const activeRange = this._textSelectionManagerService.getActiveRange();
- const allRanges = this._textSelectionManagerService.getSelections()!;
+ const allRanges = this._textSelectionManagerService.getCurrentSelections()!;
const docDataModel = this._univerInstanceService.getCurrentUniverDocInstance();
if (!docDataModel) {
return;
@@ -201,7 +201,7 @@ export class MoveCursorController extends Disposable {
// eslint-disable-next-line max-lines-per-function, complexity
private _handleMoveCursor(direction: Direction) {
const activeRange = this._textSelectionManagerService.getActiveRange();
- const allRanges = this._textSelectionManagerService.getSelections();
+ const allRanges = this._textSelectionManagerService.getCurrentSelections();
const docDataModel = this._univerInstanceService.getCurrentUniverDocInstance();
if (!docDataModel) {
return false;
diff --git a/packages/docs/src/services/text-selection-manager.service.ts b/packages/docs/src/services/text-selection-manager.service.ts
index 9074fad222..1e358734cb 100644
--- a/packages/docs/src/services/text-selection-manager.service.ts
+++ b/packages/docs/src/services/text-selection-manager.service.ts
@@ -118,7 +118,7 @@ export class TextSelectionManagerService extends RxDisposable {
this._currentSelection = param;
}
- getSelections(): Readonly<Nullable<TextRange[]>> {
+ getCurrentSelections(): Readonly<Nullable<TextRange[]>> {
return this._getTextRanges(this._currentSelection)?.textRanges;
}
@@ -180,7 +180,7 @@ export class TextSelectionManagerService extends RxDisposable {
});
}
- replaceTextRanges(textRanges: ISuccinctTextRangeParam[], isEditing = true) {
+ replaceTextRanges(textRanges: ISuccinctTextRangeParam[], isEditing = true, options?: { [key: string]: boolean }) {
if (this._currentSelection == null) {
return;
}
@@ -188,7 +188,7 @@ export class TextSelectionManagerService extends RxDisposable {
// Remove all textRanges.
this._textSelectionRenderManager.removeAllTextRanges();
// Add new textRanges.
- this._textSelectionRenderManager.addTextRanges(textRanges, isEditing);
+ this._textSelectionRenderManager.addTextRanges(textRanges, isEditing, options);
}
// All textRanges should be synchronized from the render layer.
diff --git a/packages/engine-render/src/components/docs/text-selection/text-selection-render-manager.ts b/packages/engine-render/src/components/docs/text-selection/text-selection-render-manager.ts
index fe1a28582a..da97c8ec9f 100644
--- a/packages/engine-render/src/components/docs/text-selection/text-selection-render-manager.ts
+++ b/packages/engine-render/src/components/docs/text-selection/text-selection-render-manager.ts
@@ -104,6 +104,7 @@ export interface ITextSelectionInnerParam {
isEditing: boolean;
style: ITextSelectionStyle;
segmentPage: number;
+ options?: { [key: string]: boolean };
}
export interface IActiveTextRange {
@@ -122,6 +123,7 @@ export interface ITextSelectionRenderManager {
readonly onInputBefore$: Observable<Nullable<IEditorInputConfig>>;
readonly onKeydown$: Observable<Nullable<IEditorInputConfig>>;
readonly onInput$: Observable<Nullable<IEditorInputConfig>>;
+ readonly onPointerDown$: Observable<void>;
readonly onCompositionstart$: Observable<Nullable<IEditorInputConfig>>;
readonly onCompositionupdate$: Observable<Nullable<IEditorInputConfig>>;
readonly onCompositionend$: Observable<Nullable<IEditorInputConfig>>;
@@ -141,7 +143,9 @@ export interface ITextSelectionRenderManager {
setStyle(style: ITextSelectionStyle): void;
resetStyle(): void;
removeAllTextRanges(): void;
- addTextRanges(ranges: ISuccinctTextRangeParam[], isEditing?: boolean): void;
+
+ addTextRanges(ranges: ISuccinctTextRangeParam[], isEditing?: boolean, options?: { [key: string]: boolean }): void;
+
sync(): void;
activate(x: number, y: number): void;
deactivate(): void;
@@ -196,6 +200,10 @@ export class TextSelectionRenderManager extends RxDisposable implements ITextSel
private readonly _onBlur$ = new Subject<Nullable<IEditorInputConfig>>();
readonly onBlur$ = this._onBlur$.asObservable();
+
+ private readonly _onPointerDown$ = new Subject<void>();
+ readonly onPointerDown$ = this._onPointerDown$.asObservable();
+
private _container!: HTMLDivElement;
private _inputParent!: HTMLDivElement;
private _input!: HTMLDivElement;
@@ -267,7 +275,7 @@ export class TextSelectionRenderManager extends RxDisposable implements ITextSel
this._isSelectionEnabled = false;
}
- addTextRanges(ranges: ISuccinctTextRangeParam[], isEditing = true) {
+ addTextRanges(ranges: ISuccinctTextRangeParam[], isEditing = true, options?: { [key: string]: boolean }) {
const {
_scene: scene, _docSkeleton: docSkeleton, _document: document,
_currentSegmentId: segmentId, _currentSegmentPage: segmentPage,
@@ -291,6 +299,7 @@ export class TextSelectionRenderManager extends RxDisposable implements ITextSel
segmentPage,
style,
isEditing,
+ options,
});
this._updateInputPosition();
@@ -992,6 +1001,14 @@ export class TextSelectionRenderManager extends RxDisposable implements ITextSel
})
);
+ this.disposeWithMe(
+ fromEvent(this._input, 'pointerdown').subscribe((e) => {
+ this._eventHandle(e, () => {
+ this._onBlur$.next();
+ });
+ })
+ );
+
this.disposeWithMe(
fromEvent(this._input, 'blur').subscribe((e) => {
this._eventHandle(e, (config) => {
diff --git a/packages/engine-render/src/components/sheets/sheet-skeleton.ts b/packages/engine-render/src/components/sheets/sheet-skeleton.ts
index 624ac806f2..a067b050eb 100644
--- a/packages/engine-render/src/components/sheets/sheet-skeleton.ts
+++ b/packages/engine-render/src/components/sheets/sheet-skeleton.ts
@@ -624,7 +624,7 @@ export class SpreadsheetSkeleton extends Skeleton {
return this._getBounding(this._rowHeightAccumulation, this._columnWidthAccumulation, bound);
}
- getMergeBounding(startRow: number, startColumn: number, endRow: number, endColumn: number) {
+ getMergeBounding(startRow: number, startColumn: number, endRow: number, endColumn: number): IRange {
const mergeData = this._worksheetData.mergeData;
if (!mergeData) {
return {
@@ -1064,7 +1064,7 @@ export class SpreadsheetSkeleton extends Skeleton {
return offsetY;
}
- getSelectionBounding(startRow: number, startColumn: number, endRow: number, endColumn: number): IRange {
+ getSelectionMergeBounding(startRow: number, startColumn: number, endRow: number, endColumn: number): IRange {
return this.getMergeBounding(startRow, startColumn, endRow, endColumn);
}
diff --git a/packages/engine-render/src/components/sheets/spreadsheet.ts b/packages/engine-render/src/components/sheets/spreadsheet.ts
index db13368c7f..338bf6843a 100644
--- a/packages/engine-render/src/components/sheets/spreadsheet.ts
+++ b/packages/engine-render/src/components/sheets/spreadsheet.ts
@@ -185,7 +185,7 @@ export class Spreadsheet extends SheetComponent {
const scene = this.getParent() as Scene;
let x = 0;
let y = 0;
- const viewPort = scene.getActiveViewportByRelativeCoord(coord);
+ const viewPort = scene.findViewportByPosToViewport(coord);
if (viewPort) {
const actualX = viewPort.viewportScrollX || 0;
const actualY = viewPort.viewportScrollY || 0;
diff --git a/packages/engine-render/src/engine.ts b/packages/engine-render/src/engine.ts
index cf050c0d5d..a49e23e0ca 100644
--- a/packages/engine-render/src/engine.ts
+++ b/packages/engine-render/src/engine.ts
@@ -530,7 +530,6 @@ export class Engine extends ThinEngine<Scene> {
deviceEvent.currentState = this.pointer[PointerInput.Horizontal];
this.onInputChanged$.emitEvent(deviceEvent);
- // console.log('pointerDownEvent_clientX');
}
if (previousVertical !== evt.clientY) {
deviceEvent.inputIndex = PointerInput.Vertical;
@@ -538,7 +537,6 @@ export class Engine extends ThinEngine<Scene> {
deviceEvent.currentState = this.pointer[PointerInput.Vertical];
this.onInputChanged$.emitEvent(deviceEvent);
- // console.log('pointerDownEvent_clientY');
}
// evt.button + 2 ---> leftClick: 2, middleClick: 3, rightClick:4
@@ -546,7 +544,6 @@ export class Engine extends ThinEngine<Scene> {
deviceEvent.previousState = previousButton;
deviceEvent.currentState = this.pointer[evt.button + 2];
this.onInputChanged$.emitEvent(deviceEvent);
- // console.log('pointerDownEvent_2', previousHorizontal, evt.clientX, previousVertical, evt.clientY, this._pointer);
};
this._pointerUpEvent = (_evt: Event) => {
@@ -647,11 +644,13 @@ export class Engine extends ThinEngine<Scene> {
this.onInputChanged$.emitEvent(deviceEvent);
};
- this._pointerBlurEvent = (evt: any) => {
+ this._pointerBlurEvent = () => {
if (this._mouseId >= 0 && this.getCanvasElement().hasPointerCapture(this._mouseId)) {
- this.getCanvasElement().releasePointerCapture(this._mouseId);
- this._remainCapture = this._mouseId;
- this._mouseId = -1;
+ // NOTE: @wzhudev comment so the canvas could keep capturing pointer events.
+ // May lead to unknown problems.
+ // this.getCanvasElement().releasePointerCapture(this._mouseId);
+ // this._remainCapture = this._mouseId;
+ // this._mouseId = -1;
}
this.pointer = {};
diff --git a/packages/engine-render/src/index.ts b/packages/engine-render/src/index.ts
index f38fa53869..7a802577d0 100644
--- a/packages/engine-render/src/index.ts
+++ b/packages/engine-render/src/index.ts
@@ -25,7 +25,7 @@ export * from './group';
export * from './layer';
export { IRenderingEngine, UniverRenderEnginePlugin } from './render-engine';
export { type RenderComponentType, IRenderManagerService, RenderManagerService } from './render-manager/render-manager.service';
-export { RenderUnit, type IRender, type IRenderModuleCtor, type IRenderModule, type IRenderContext } from './render-manager/render-unit';
+export { RenderUnit, type IRender, type IRenderModule, type IRenderContext } from './render-manager/render-unit';
export * from './scene';
export * from './scene-viewer';
export * from './scroll-timer';
diff --git a/packages/engine-render/src/render-manager/render-manager.service.ts b/packages/engine-render/src/render-manager/render-manager.service.ts
index c0a8f0ce3a..490e32e734 100644
--- a/packages/engine-render/src/render-manager/render-manager.service.ts
+++ b/packages/engine-render/src/render-manager/render-manager.service.ts
@@ -15,8 +15,8 @@
*/
import type { Nullable, UnitModel, UnitType, UniverInstanceType } from '@univerjs/core';
-import { Disposable, IUniverInstanceService, toDisposable } from '@univerjs/core';
-import type { DependencyIdentifier, IDisposable } from '@wendellhu/redi';
+import { Disposable, IUniverInstanceService, remove, toDisposable } from '@univerjs/core';
+import type { Dependency, DependencyIdentifier, IDisposable } from '@wendellhu/redi';
import { createIdentifier, Inject, Injector } from '@wendellhu/redi';
import type { Observable } from 'rxjs';
import { BehaviorSubject, Subject } from 'rxjs';
@@ -27,7 +27,7 @@ import type { SheetComponent } from '../components/sheets/sheet-component';
import type { Slide } from '../components/slides/slide';
import { Engine } from '../engine';
import { Scene } from '../scene';
-import { type IRender, type IRenderModuleCtor, RenderUnit } from './render-unit';
+import { type IRender, RenderUnit } from './render-unit';
export type RenderComponentType = SheetComponent | DocComponent | Slide | BaseObject;
@@ -39,6 +39,7 @@ export interface IRenderManagerService extends IDisposable {
removeRender(unitId: string): void;
setCurrent(unitId: string): void;
getRenderById(unitId: string): Nullable<IRender>;
+ getCurrentTypeOfRenderer(type: UniverInstanceType): Nullable<RenderUnit>;
getRenderAll(): Map<string, IRender>;
defaultEngine: Engine;
@@ -59,7 +60,7 @@ export interface IRenderManagerService extends IDisposable {
has(unitId: string): boolean;
withCurrentTypeOfUnit<T>(type: UniverInstanceType, id: DependencyIdentifier<T>): Nullable<T>;
- registerRenderModule<T extends UnitModel>(type: UnitType, ctor: IRenderModuleCtor<T>): IDisposable;
+ registerRenderModule<T extends UnitModel>(type: UnitType, dep: Dependency<T>): IDisposable;
}
const DEFAULT_SCENE_SIZE = { width: 1500, height: 1000 };
@@ -87,7 +88,7 @@ export class RenderManagerService extends Disposable implements IRenderManagerSe
return this._defaultEngine;
}
- private readonly _renderControllers = new Map<UnitType, Set<IRenderModuleCtor>>();
+ private readonly _renderDependencies = new Map<UnitType, Dependency[]>();
constructor(
@Inject(Injector) private readonly _injector: Injector,
@@ -100,31 +101,51 @@ export class RenderManagerService extends Disposable implements IRenderManagerSe
super.dispose();
this._renderMap.forEach((item) => this._disposeItem(item));
- this._renderControllers.clear();
+ this._renderDependencies.clear();
this._renderMap.clear();
this._currentRender$.complete();
}
- registerRenderModule(type: UnitType, ctor: IRenderModuleCtor): IDisposable {
- if (!this._renderControllers.has(type)) {
- this._renderControllers.set(type, new Set());
+ registerRenderModules(type: UnitType, deps: Dependency[]): IDisposable {
+ if (!this._renderDependencies.has(type)) {
+ this._renderDependencies.set(type, []);
}
- const set = this._renderControllers.get(type)!;
- set.add(ctor);
+ const dependencies = this._renderDependencies.get(type)!;
+ dependencies.push(...deps);
for (const [renderUnitId, render] of this._renderMap) {
const renderType = this._univerInstanceService.getUnitType(renderUnitId);
if (renderType === type) {
- (render as RenderUnit).addRenderControllers([ctor]);
+ (render as RenderUnit).addRenderDependencies(deps);
}
}
- return toDisposable(() => set.delete(ctor));
+ return toDisposable(() => {
+ deps.forEach((dep) => remove(dependencies, dep));
+ });
}
- private _getRenderControllersForType(type: UnitType): Array<IRenderModuleCtor> {
- return Array.from(this._renderControllers.get(type) ?? []);
+ registerRenderModule(type: UnitType, ctor: Dependency): IDisposable {
+ if (!this._renderDependencies.has(type)) {
+ this._renderDependencies.set(type, []);
+ }
+
+ const dependencies = this._renderDependencies.get(type)!;
+ dependencies.push(ctor);
+
+ for (const [renderUnitId, render] of this._renderMap) {
+ const renderType = this._univerInstanceService.getUnitType(renderUnitId);
+ if (renderType === type) {
+ (render as RenderUnit).addRenderDependencies([ctor]);
+ }
+ }
+
+ return toDisposable(() => remove(dependencies, ctor));
+ }
+
+ private _getRenderControllersForType(type: UnitType): Array<Dependency> {
+ return Array.from(this._renderDependencies.get(type) ?? []);
}
create(unitId: string) {
@@ -135,6 +156,13 @@ export class RenderManagerService extends Disposable implements IRenderManagerSe
return this._createRender(unitId, new Engine());
}
+ getCurrentTypeOfRenderer(type: UniverInstanceType): Nullable<RenderUnit> {
+ const current = this._univerInstanceService.getCurrentUnitForType(type);
+ if (!current) return null;
+
+ return this.getRenderById(current.getUnitId()) as RenderUnit;
+ }
+
withCurrentTypeOfUnit<T>(type: UniverInstanceType, id: DependencyIdentifier<T>): Nullable<T> {
const current = this._univerInstanceService.getCurrentUnitForType(type);
if (!current) return null;
@@ -175,7 +203,7 @@ export class RenderManagerService extends Disposable implements IRenderManagerSe
isMainScene,
});
- (renderUnit as RenderUnit).addRenderControllers(ctors);
+ (renderUnit as RenderUnit).addRenderDependencies(ctors);
} else {
// For slide pages
renderUnit = {
@@ -263,6 +291,6 @@ export class RenderManagerService extends Disposable implements IRenderManagerSe
export const IRenderManagerService = createIdentifier<IRenderManagerService>('engine-render.render-manager.service');
export function isDisposable(thing: unknown): thing is IDisposable {
- // eslint-disable-next-line ts/no-explicit-any
+ // eslint-disable-next-line ts/no-explicit-any
return !!thing && typeof (thing as any).dispose === 'function';
}
diff --git a/packages/engine-render/src/render-manager/render-unit.ts b/packages/engine-render/src/render-manager/render-unit.ts
index 2d25cfcf57..d4b60e15e7 100644
--- a/packages/engine-render/src/render-manager/render-unit.ts
+++ b/packages/engine-render/src/render-manager/render-unit.ts
@@ -16,7 +16,7 @@
import type { Nullable, UnitModel, UnitType } from '@univerjs/core';
import { Disposable } from '@univerjs/core';
-import type { DependencyIdentifier, IDisposable, Injector } from '@wendellhu/redi';
+import { type Dependency, type DependencyIdentifier, type IDisposable, type Injector, isClassDependencyItem } from '@wendellhu/redi';
import type { Engine } from '../engine';
import type { Scene } from '../scene';
import type { RenderComponentType } from './render-manager.service';
@@ -32,8 +32,6 @@ export interface IRender {
with<T>(dependency: DependencyIdentifier<T>): T;
}
-// eslint-disable-next-line ts/no-explicit-any
-export interface IRenderModuleCtor<T extends UnitModel = UnitModel> { new(unit: IRenderContext<T>, ...args: any[]): IRenderModule }
export interface IRenderModule extends IDisposable {}
/**
@@ -100,14 +98,28 @@ export class RenderUnit extends Disposable implements IRender {
return this._injector.get(dependency);
}
- addRenderControllers(ctors: IRenderModuleCtor[]) {
- this._initControllers(ctors);
+ addRenderDependencies(dependencies: Dependency[]) {
+ this._initDependencies(dependencies);
}
- private _initControllers(ctors: IRenderModuleCtor[]): void {
+ private _initDependencies(dependencies: Dependency[]): void {
const j = this._injector;
- ctors.forEach((ctor) => j.add([ctor, { useFactory: () => j.createInstance(ctor, this._renderContext) }]));
- ctors.forEach((ctor) => j.get(ctor));
+ dependencies.forEach((dep) => {
+ const [identifier, implOrNull] = Array.isArray(dep) ? dep : [dep, null];
+
+ if (!implOrNull) {
+ j.add([identifier, { useFactory: () => j.createInstance(identifier, this._renderContext) }]);
+ } else if (isClassDependencyItem(implOrNull)) {
+ j.add([identifier, { useFactory: () => j.createInstance(implOrNull.useClass, this._renderContext) }]);
+ } else {
+ throw new Error('[RenderUnit]: render dependency could only be an class!');
+ }
+ });
+
+ dependencies.forEach((dep) => {
+ const [identifier] = Array.isArray(dep) ? dep : [dep, null];
+ j.get(identifier);
+ });
}
}
diff --git a/packages/engine-render/src/scene.transformer.ts b/packages/engine-render/src/scene.transformer.ts
index 6e47dca489..22eb74d33c 100644
--- a/packages/engine-render/src/scene.transformer.ts
+++ b/packages/engine-render/src/scene.transformer.ts
@@ -995,7 +995,7 @@ export class Transformer extends Disposable implements ITransformerConfig {
topScene.disableEvent();
- const viewportActualXY = topScene.getScrollXYByRelativeCoords(Vector2.create(evtOffsetX, evtOffsetY));
+ const viewportActualXY = topScene.getVpScrollXYInfoByPosToVp(Vector2.create(evtOffsetX, evtOffsetY));
this._viewportScrollX = viewportActualXY.x;
this._viewportScrollY = viewportActualXY.y;
diff --git a/packages/engine-render/src/scene.ts b/packages/engine-render/src/scene.ts
index 2f3e1dfe2e..0ede690621 100644
--- a/packages/engine-render/src/scene.ts
+++ b/packages/engine-render/src/scene.ts
@@ -586,7 +586,12 @@ export class Scene extends ThinScene {
return this._transformer;
}
- getActiveViewportByRelativeCoord(coord: Vector2) {
+ /**
+ * prev getActiveViewportByRelativeCoord
+ * @param coord
+ * @returns
+ */
+ findViewportByPosToViewport(coord: Vector2) {
return this._viewports.find((vp) => vp.isHit(coord));
}
@@ -600,13 +605,19 @@ export class Scene extends ThinScene {
// }
// parent = parent?.getParent && parent?.getParent();
// }
- coord = this.getRelativeCoord(coord);
- return this.getActiveViewportByRelativeCoord(coord);
+ coord = this.getRelativeToViewportCoord(coord);
+ return this.findViewportByPosToViewport(coord);
}
- getScrollXYByRelativeCoords(coord: Vector2, viewPort?: Viewport) {
+ /**
+ * getViewportScrollXYInfo by viewport under cursor position
+ * prev getScrollXYByRelativeCoords
+ * @param pos
+ * @param viewPort
+ */
+ getVpScrollXYInfoByPosToVp(pos: Vector2, viewPort?: Viewport) {
if (!viewPort) {
- viewPort = this.getActiveViewportByRelativeCoord(coord);
+ viewPort = this.findViewportByPosToViewport(pos);
}
if (!viewPort) {
return {
@@ -614,10 +625,10 @@ export class Scene extends ThinScene {
y: 0,
};
}
- return this.getScrollXY(viewPort);
+ return this.getViewportScrollXY(viewPort);
}
- getScrollXY(viewPort: Viewport) {
+ getViewportScrollXY(viewPort: Viewport) {
let x = 0;
let y = 0;
if (viewPort) {
@@ -637,7 +648,7 @@ export class Scene extends ThinScene {
* @param coord Coordinates to be converted.
* @returns
*/
- getRelativeCoord(coord: Vector2) {
+ getRelativeToViewportCoord(coord: Vector2) {
let parent: any = this.getParent();
const parentList: any[] = [];
diff --git a/packages/engine-render/src/scroll-timer.ts b/packages/engine-render/src/scroll-timer.ts
index b645454e7a..5eff3bf6b1 100644
--- a/packages/engine-render/src/scroll-timer.ts
+++ b/packages/engine-render/src/scroll-timer.ts
@@ -175,7 +175,7 @@ export class ScrollTimer {
getViewportByCoord(scene?: Scene) {
// return scene?.getActiveViewportByCoord(Vector2.FromArray([this._offsetX, this._offsetY]));
- return scene?.getActiveViewportByRelativeCoord(Vector2.FromArray([this._offsetX, this._offsetY]));
+ return scene?.findViewportByPosToViewport(Vector2.FromArray([this._offsetX, this._offsetY]));
}
getScene() {
diff --git a/packages/facade/src/apis/__tests__/create-test-bed.ts b/packages/facade/src/apis/__tests__/create-test-bed.ts
index 290e718fe9..84c1d3d368 100644
--- a/packages/facade/src/apis/__tests__/create-test-bed.ts
+++ b/packages/facade/src/apis/__tests__/create-test-bed.ts
@@ -32,7 +32,7 @@ import {
} from '@univerjs/core';
import { FormulaDataModel, FunctionService, IFunctionService, LexerTreeBuilder } from '@univerjs/engine-formula';
import { ISocketService, WebSocketService } from '@univerjs/network';
-import { RangeProtectionRuleModel, SelectionManagerService, SheetInterceptorService, WorkbookPermissionService, WorksheetPermissionService, WorksheetProtectionPointModel, WorksheetProtectionRuleModel } from '@univerjs/sheets';
+import { RangeProtectionRuleModel, SheetInterceptorService, SheetsSelectionsService, WorkbookPermissionService, WorksheetPermissionService, WorksheetProtectionPointModel, WorksheetProtectionRuleModel } from '@univerjs/sheets';
import {
DescriptionService,
FormulaCustomFunctionService,
@@ -47,7 +47,7 @@ import type { Dependency } from '@wendellhu/redi';
import { Inject, Injector } from '@wendellhu/redi';
import { Engine, IRenderingEngine, IRenderManagerService, RenderManagerService } from '@univerjs/engine-render';
-import { ISelectionRenderService, SelectionRenderService, SheetRenderController, SheetSkeletonManagerService, SheetsRenderService } from '@univerjs/sheets-ui';
+import { ISheetSelectionRenderService, SheetRenderController, SheetSelectionRenderService, SheetSkeletonManagerService, SheetsRenderService } from '@univerjs/sheets-ui';
import { IPlatformService, IShortcutService, PlatformService, ShortcutService } from '@univerjs/ui';
import { ConditionalFormattingFormulaService, ConditionalFormattingRuleModel, ConditionalFormattingService, ConditionalFormattingViewModel } from '@univerjs/sheets-conditional-formatting';
@@ -126,7 +126,7 @@ export function createFacadeTestBed(workbookData?: IWorkbookData, dependencies?:
}
override onStarting(injector: Injector): void {
- injector.add([SelectionManagerService]);
+ injector.add([SheetsSelectionsService]);
injector.add([SheetInterceptorService]);
injector.add([IRegisterFunctionService, { useClass: RegisterFunctionService }]);
injector.add([
@@ -141,7 +141,7 @@ export function createFacadeTestBed(workbookData?: IWorkbookData, dependencies?:
injector.add([ISocketService, { useClass: WebSocketService }]);
injector.add([IRenderingEngine, { useFactory: () => new Engine() }]);
injector.add([IRenderManagerService, { useClass: RenderManagerService }]);
- injector.add([ISelectionRenderService, { useClass: SelectionRenderService }]);
+ injector.add([ISheetSelectionRenderService, { useClass: SheetSelectionRenderService }]);
injector.add([SheetsRenderService]);
injector.add([IShortcutService, { useClass: ShortcutService }]);
injector.add([IPlatformService, { useClass: PlatformService }]);
@@ -156,8 +156,8 @@ export function createFacadeTestBed(workbookData?: IWorkbookData, dependencies?:
injector.add([WorksheetProtectionRuleModel]);
const renderManagerService = injector.get(IRenderManagerService);
- renderManagerService.registerRenderModule(UniverInstanceType.UNIVER_SHEET, SheetSkeletonManagerService);
- renderManagerService.registerRenderModule(UniverInstanceType.UNIVER_SHEET, SheetRenderController);
+ renderManagerService.registerRenderModule(UniverInstanceType.UNIVER_SHEET, [SheetSkeletonManagerService] as Dependency);
+ renderManagerService.registerRenderModule(UniverInstanceType.UNIVER_SHEET, [SheetRenderController] as Dependency);
([
[ConditionalFormattingService],
diff --git a/packages/facade/src/apis/docs/__tests__/create-test-bed.ts b/packages/facade/src/apis/docs/__tests__/create-test-bed.ts
index daa65b5be3..c3dc26f3be 100644
--- a/packages/facade/src/apis/docs/__tests__/create-test-bed.ts
+++ b/packages/facade/src/apis/docs/__tests__/create-test-bed.ts
@@ -87,7 +87,7 @@ export function createTestBed(documentConfig?: IDocumentData, dependencies?: Dep
dependencies?.forEach((d) => injector.add(d));
const renderManagerService = injector.get(IRenderManagerService);
- renderManagerService.registerRenderModule(UniverInstanceType.UNIVER_DOC, DocSkeletonManagerService);
+ renderManagerService.registerRenderModule(UniverInstanceType.UNIVER_DOC, [DocSkeletonManagerService] as Dependency);
}
}
diff --git a/packages/facade/src/apis/sheets/__tests__/create-test-bed.ts b/packages/facade/src/apis/sheets/__tests__/create-test-bed.ts
index 27c7a0e52b..31532261d0 100644
--- a/packages/facade/src/apis/sheets/__tests__/create-test-bed.ts
+++ b/packages/facade/src/apis/sheets/__tests__/create-test-bed.ts
@@ -27,7 +27,7 @@ import {
} from '@univerjs/core';
import { FunctionService, IFunctionService } from '@univerjs/engine-formula';
import { ISocketService, WebSocketService } from '@univerjs/network';
-import { SelectionManagerService, SheetInterceptorService } from '@univerjs/sheets';
+import { SheetInterceptorService, SheetsSelectionsService } from '@univerjs/sheets';
import {
DescriptionService,
FormulaCustomFunctionService,
@@ -86,7 +86,7 @@ export function createTestBed(workbookData?: IWorkbookData, dependencies?: Depen
}
override onStarting(injector: Injector): void {
- injector.add([SelectionManagerService]);
+ injector.add([SheetsSelectionsService]);
injector.add([SheetInterceptorService]);
injector.add([IRegisterFunctionService, { useClass: RegisterFunctionService }]);
injector.add([
diff --git a/packages/facade/src/apis/sheets/f-range.ts b/packages/facade/src/apis/sheets/f-range.ts
index 575e10d7b9..176bd79ad6 100644
--- a/packages/facade/src/apis/sheets/f-range.ts
+++ b/packages/facade/src/apis/sheets/f-range.ts
@@ -107,7 +107,7 @@ export class FRange {
const unitId = this._workbook.getUnitId();
const subUnitId = this._worksheet.getSheetId();
const skeleton = this._renderManagerService.getRenderById(unitId)!
- .with(SheetSkeletonManagerService).getUnitSkeleton(unitId, subUnitId)!.skeleton;
+ .with(SheetSkeletonManagerService).getWorksheetSkeleton(subUnitId)!.skeleton;
return skeleton.getCellByIndex(this._range.startRow, this._range.startColumn);
}
diff --git a/packages/facade/src/apis/sheets/f-workbook.ts b/packages/facade/src/apis/sheets/f-workbook.ts
index 0a435a1cd4..7a4b08f276 100644
--- a/packages/facade/src/apis/sheets/f-workbook.ts
+++ b/packages/facade/src/apis/sheets/f-workbook.ts
@@ -29,7 +29,7 @@ import {
import type {
ISheetCommandSharedParams,
} from '@univerjs/sheets';
-import { InsertSheetCommand, RemoveSheetCommand, SelectionManagerService, SetWorksheetActiveOperation, WorkbookEditablePermission } from '@univerjs/sheets';
+import { InsertSheetCommand, RemoveSheetCommand, SetWorksheetActiveOperation, SheetsSelectionsService, WorkbookEditablePermission } from '@univerjs/sheets';
import type { IDisposable } from '@wendellhu/redi';
import { Inject, Injector } from '@wendellhu/redi';
@@ -42,7 +42,7 @@ export class FWorkbook {
private readonly _workbook: Workbook,
@Inject(Injector) private readonly _injector: Injector,
@Inject(IResourceLoaderService) private readonly _resourceLoaderService: IResourceLoaderService,
- @Inject(SelectionManagerService) private readonly _selectionManagerService: SelectionManagerService,
+ @Inject(SheetsSelectionsService) private readonly _selectionManagerService: SheetsSelectionsService,
@IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService,
@ICommandService private readonly _commandService: ICommandService,
@IPermissionService private readonly _permissionService: IPermissionService
diff --git a/packages/facade/src/apis/sheets/f-worksheet.ts b/packages/facade/src/apis/sheets/f-worksheet.ts
index c6745ecf48..004c819673 100644
--- a/packages/facade/src/apis/sheets/f-worksheet.ts
+++ b/packages/facade/src/apis/sheets/f-worksheet.ts
@@ -16,7 +16,7 @@
import { ICommandService, type IRange, type Workbook, type Worksheet } from '@univerjs/core';
import type { ISetWorksheetColWidthMutationParams, ISetWorksheetRowHeightMutationParams } from '@univerjs/sheets';
-import { SelectionManagerService, SetWorksheetColWidthMutation, SetWorksheetRowHeightMutation } from '@univerjs/sheets';
+import { SetWorksheetColWidthMutation, SetWorksheetRowHeightMutation, SheetsSelectionsService } from '@univerjs/sheets';
import { Inject, Injector } from '@wendellhu/redi';
import { FRange } from './f-range';
@@ -27,7 +27,7 @@ export class FWorksheet {
private readonly _workbook: Workbook,
private readonly _worksheet: Worksheet,
@Inject(Injector) private readonly _injector: Injector,
- @Inject(SelectionManagerService) private readonly _selectionManagerService: SelectionManagerService,
+ @Inject(SheetsSelectionsService) private readonly _selectionManagerService: SheetsSelectionsService,
@ICommandService private readonly _commandService: ICommandService
) {
// empty
@@ -50,7 +50,7 @@ export class FWorksheet {
}
getSelection(): FSelection | null {
- const selections = this._selectionManagerService.getSelections();
+ const selections = this._selectionManagerService.getCurrentSelections();
if (!selections) {
return null;
}
diff --git a/packages/sheets-conditional-formatting-ui/src/commands/commands/clear-range-cf.command.ts b/packages/sheets-conditional-formatting-ui/src/commands/commands/clear-range-cf.command.ts
index 3d5d416d9c..bf6afebb79 100644
--- a/packages/sheets-conditional-formatting-ui/src/commands/commands/clear-range-cf.command.ts
+++ b/packages/sheets-conditional-formatting-ui/src/commands/commands/clear-range-cf.command.ts
@@ -26,7 +26,7 @@ import {
Range,
sequenceExecute,
} from '@univerjs/core';
-import { createTopMatrixFromMatrix, findAllRectangle, getSheetCommandTarget, SelectionManagerService } from '@univerjs/sheets';
+import { createTopMatrixFromMatrix, findAllRectangle, getSheetCommandTarget, SheetsSelectionsService } from '@univerjs/sheets';
import { ConditionalFormattingRuleModel, DeleteConditionalRuleMutation, DeleteConditionalRuleMutationUndoFactory, SetConditionalRuleMutation, setConditionalRuleMutationUndoFactory } from '@univerjs/sheets-conditional-formatting';
import type { IConditionFormattingRule, IDeleteConditionalRuleMutationParams, ISetConditionalRuleMutationParams } from '@univerjs/sheets-conditional-formatting';
@@ -47,13 +47,13 @@ export const ClearRangeCfCommand: ICommand<IClearRangeCfParams> = {
const univerInstanceService = accessor.get(IUniverInstanceService);
const commandService = accessor.get(ICommandService);
const undoRedoService = accessor.get(IUndoRedoService);
- const selectionManagerService = accessor.get(SelectionManagerService);
+ const selectionManagerService = accessor.get(SheetsSelectionsService);
const target = getSheetCommandTarget(univerInstanceService, params);
if (!target) return false;
const { unitId, subUnitId } = target;
- const ranges = selectionManagerService.getSelections()?.map((selection) => selection.range) || [];
+ const ranges = selectionManagerService.getCurrentSelections()?.map((selection) => selection.range) || [];
const allRuleList = conditionalFormattingRuleModel.getSubunitRules(unitId, subUnitId);
if (!allRuleList?.length || !ranges.length) {
return false;
diff --git a/packages/sheets-conditional-formatting-ui/src/commands/operations/open-conditional-formatting-panel.ts b/packages/sheets-conditional-formatting-ui/src/commands/operations/open-conditional-formatting-panel.ts
index 6ccaddb806..6ffa56ac7e 100644
--- a/packages/sheets-conditional-formatting-ui/src/commands/operations/open-conditional-formatting-panel.ts
+++ b/packages/sheets-conditional-formatting-ui/src/commands/operations/open-conditional-formatting-panel.ts
@@ -17,7 +17,7 @@
import type { ICommand } from '@univerjs/core';
import { CommandType, ICommandService } from '@univerjs/core';
import type { IAccessor } from '@wendellhu/redi';
-import { SelectionManagerService } from '@univerjs/sheets';
+import { SheetsSelectionsService } from '@univerjs/sheets';
import { CFRuleType, CFSubRuleType, createDefaultRule } from '@univerjs/sheets-conditional-formatting';
import type { IColorScale, IConditionFormattingRule, IDataBar, IFormulaHighlightCell, IIconSet, IRankHighlightCell } from '@univerjs/sheets-conditional-formatting';
import { ConditionalFormattingMenuController } from '../../controllers/cf.menu.controller';
@@ -46,10 +46,10 @@ export const OpenConditionalFormattingOperator: ICommand = {
type: CommandType.OPERATION,
handler: (accessor: IAccessor, params: IOpenConditionalFormattingOperatorParams) => {
const conditionalFormattingMenuController = accessor.get(ConditionalFormattingMenuController);
- const selectionManagerService = accessor.get(SelectionManagerService);
+ const selectionManagerService = accessor.get(SheetsSelectionsService);
const commandService = accessor.get(ICommandService);
- const ranges = selectionManagerService.getSelectionRanges() || [];
+ const ranges = selectionManagerService.getCurrentSelections()?.map((s) => s.range) || [];
const type = params.value;
switch (type) {
diff --git a/packages/sheets-conditional-formatting-ui/src/components/panel/rule-edit/index.tsx b/packages/sheets-conditional-formatting-ui/src/components/panel/rule-edit/index.tsx
index d7d8676456..a4908fb078 100644
--- a/packages/sheets-conditional-formatting-ui/src/components/panel/rule-edit/index.tsx
+++ b/packages/sheets-conditional-formatting-ui/src/components/panel/rule-edit/index.tsx
@@ -23,7 +23,7 @@ import { Button, Select } from '@univerjs/design';
import { RangeSelector } from '@univerjs/ui';
import type { IRemoveSheetMutationParams } from '@univerjs/sheets';
-import { RemoveSheetMutation, SelectionManagerService, setEndForRange, SetWorksheetActiveOperation } from '@univerjs/sheets';
+import { RemoveSheetMutation, setEndForRange, SetWorksheetActiveOperation, SheetsSelectionsService } from '@univerjs/sheets';
import type { IConditionFormattingRule } from '@univerjs/sheets-conditional-formatting';
import { CFRuleType, CFSubRuleType, ConditionalFormattingRuleModel, SHEET_CONDITIONAL_FORMATTING_PLUGIN } from '@univerjs/sheets-conditional-formatting';
import type { IAddCfCommandParams } from '../../../commands/commands/add-cf.command';
@@ -55,7 +55,7 @@ export const RuleEdit = (props: IRuleEditProps) => {
const commandService = useDependency(ICommandService);
const univerInstanceService = useDependency(IUniverInstanceService);
const conditionalFormattingRuleModel = useDependency(ConditionalFormattingRuleModel);
- const selectionManagerService = useDependency(SelectionManagerService);
+ const selectionManagerService = useDependency(SheetsSelectionsService);
const unitId = getUnitId(univerInstanceService);
const subUnitId = getSubUnitId(univerInstanceService);
@@ -64,7 +64,7 @@ export const RuleEdit = (props: IRuleEditProps) => {
const rangeString = useMemo(() => {
let ranges = props.rule?.ranges;
if (!ranges?.length) {
- ranges = selectionManagerService.getSelectionRanges() ?? [];
+ ranges = selectionManagerService.getCurrentSelections()?.map((s) => s.range) ?? [];
}
rangeResult.current = ranges;
if (!ranges?.length) {
diff --git a/packages/sheets-conditional-formatting-ui/src/components/panel/rule-list/index.tsx b/packages/sheets-conditional-formatting-ui/src/components/panel/rule-list/index.tsx
index b1687a742e..2212441e22 100644
--- a/packages/sheets-conditional-formatting-ui/src/components/panel/rule-list/index.tsx
+++ b/packages/sheets-conditional-formatting-ui/src/components/panel/rule-list/index.tsx
@@ -22,7 +22,7 @@ import { useDependency } from '@wendellhu/redi/react-bindings';
import type { ICellDataForSheetInterceptor, IRange, Workbook } from '@univerjs/core';
import { ICommandService, IUniverInstanceService, LocaleService, Rectangle, UniverInstanceType } from '@univerjs/core';
import type { ICellPermission } from '@univerjs/sheets';
-import { SelectionManagerService, SetSelectionsOperation, SetWorksheetActiveOperation } from '@univerjs/sheets';
+import { SetSelectionsOperation, SetWorksheetActiveOperation, SheetsSelectionsService } from '@univerjs/sheets';
import { serializeRange } from '@univerjs/engine-formula';
import { DeleteSingle, IncreaseSingle, SequenceSingle } from '@univerjs/icons';
import GridLayout from 'react-grid-layout';
@@ -110,7 +110,7 @@ export const RuleList = (props: IRuleListProps) => {
const { onClick } = props;
const conditionalFormattingRuleModel = useDependency(ConditionalFormattingRuleModel);
const univerInstanceService = useDependency(IUniverInstanceService);
- const selectionManagerService = useDependency(SelectionManagerService);
+ const selectionManagerService = useDependency(SheetsSelectionsService);
const commandService = useDependency(ICommandService);
const localeService = useDependency(LocaleService);
const conditionalFormattingI18nController = useDependency(ConditionalFormattingI18nController);
@@ -142,7 +142,7 @@ export const RuleList = (props: IRuleListProps) => {
return [];
}
if (selectValue === '1') {
- const selection = selectionManagerService.getLast();
+ const selection = selectionManagerService.getCurrentLastSelection();
if (!selection) {
return [];
}
diff --git a/packages/sheets-conditional-formatting-ui/src/controllers/cf.clear.controller.ts b/packages/sheets-conditional-formatting-ui/src/controllers/cf.clear.controller.ts
index c0bbb3fb0e..655682ed41 100644
--- a/packages/sheets-conditional-formatting-ui/src/controllers/cf.clear.controller.ts
+++ b/packages/sheets-conditional-formatting-ui/src/controllers/cf.clear.controller.ts
@@ -16,7 +16,7 @@
import type { IMutationInfo, Workbook } from '@univerjs/core';
import { Disposable, IUniverInstanceService, LifecycleStages, OnLifecycle, Rectangle, UniverInstanceType } from '@univerjs/core';
-import { ClearSelectionAllCommand, ClearSelectionFormatCommand, RangeMergeUtil, SelectionManagerService, SheetInterceptorService } from '@univerjs/sheets';
+import { ClearSelectionAllCommand, ClearSelectionFormatCommand, RangeMergeUtil, SheetInterceptorService, SheetsSelectionsService } from '@univerjs/sheets';
import { Inject, Injector } from '@wendellhu/redi';
import { ConditionalFormattingRuleModel, DeleteConditionalRuleMutation, DeleteConditionalRuleMutationUndoFactory, SetConditionalRuleMutation, setConditionalRuleMutationUndoFactory } from '@univerjs/sheets-conditional-formatting';
import type { IDeleteConditionalRuleMutationParams, ISetConditionalRuleMutationParams } from '@univerjs/sheets-conditional-formatting';
@@ -27,7 +27,7 @@ export class ConditionalFormattingClearController extends Disposable {
@Inject(Injector) private _injector: Injector,
@Inject(IUniverInstanceService) private _univerInstanceService: IUniverInstanceService,
@Inject(SheetInterceptorService) private _sheetInterceptorService: SheetInterceptorService,
- @Inject(SelectionManagerService) private _selectionManagerService: SelectionManagerService,
+ @Inject(SheetsSelectionsService) private _selectionManagerService: SheetsSelectionsService,
@Inject(ConditionalFormattingRuleModel) private _conditionalFormattingRuleModel: ConditionalFormattingRuleModel
) {
@@ -43,7 +43,7 @@ export class ConditionalFormattingClearController extends Disposable {
const undos: IMutationInfo[] = [];
const defaultV = { redos, undos };
if ([ClearSelectionFormatCommand.id, ClearSelectionAllCommand.id].includes(commandInfo.id)) {
- const ranges = this._selectionManagerService.getSelectionRanges();
+ const ranges = this._selectionManagerService.getCurrentSelections()?.map((s) => s.range);
if (!ranges) {
return defaultV;
}
diff --git a/packages/sheets-conditional-formatting-ui/src/menu/manage-rule.ts b/packages/sheets-conditional-formatting-ui/src/menu/manage-rule.ts
index 659ffcea81..2d8820a3e8 100644
--- a/packages/sheets-conditional-formatting-ui/src/menu/manage-rule.ts
+++ b/packages/sheets-conditional-formatting-ui/src/menu/manage-rule.ts
@@ -18,7 +18,7 @@ import { merge, Observable } from 'rxjs';
import type { IMenuSelectorItem } from '@univerjs/ui';
import type { IAccessor } from '@wendellhu/redi';
import { getMenuHiddenObservable, MenuGroup, MenuItemType, MenuPosition } from '@univerjs/ui';
-import { RangeProtectionPermissionEditPoint, SelectionManagerService, SetWorksheetActiveOperation, WorkbookEditablePermission, WorksheetEditPermission, WorksheetSetCellStylePermission } from '@univerjs/sheets';
+import { RangeProtectionPermissionEditPoint, SetWorksheetActiveOperation, SheetsSelectionsService, WorkbookEditablePermission, WorksheetEditPermission, WorksheetSetCellStylePermission } from '@univerjs/sheets';
import { debounceTime } from 'rxjs/operators';
import type { ICellDataForSheetInterceptor, IRange, Workbook } from '@univerjs/core';
@@ -77,7 +77,7 @@ export const FactoryManageConditionalFormattingRule = (accessor: IAccessor): IMe
},
];
- const selectionManagerService = accessor.get(SelectionManagerService);
+ const selectionManagerService = accessor.get(SheetsSelectionsService);
const commandService = accessor.get(ICommandService);
const univerInstanceService = accessor.get(IUniverInstanceService);
const conditionalFormattingRuleModel = accessor.get(ConditionalFormattingRuleModel);
@@ -95,7 +95,7 @@ export const FactoryManageConditionalFormattingRule = (accessor: IAccessor): IMe
return () => disposable.dispose();
})
).pipe(debounceTime(16)).subscribe(() => {
- const ranges = selectionManagerService.getSelections()?.map((selection) => selection.range) || [];
+ const ranges = selectionManagerService.getCurrentSelections()?.map((selection) => selection.range) || [];
const workbook = univerInstanceService.getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET);
if (!workbook) return;
const worksheet = workbook.getActiveSheet();
diff --git a/packages/sheets-data-validation/src/controllers/dv-render.controller.ts b/packages/sheets-data-validation/src/controllers/dv-render.controller.ts
index ea03c0fbad..27d67c681d 100644
--- a/packages/sheets-data-validation/src/controllers/dv-render.controller.ts
+++ b/packages/sheets-data-validation/src/controllers/dv-render.controller.ts
@@ -191,7 +191,7 @@ export class SheetsDataValidationRenderController extends RxDisposable {
if (!subUnitId) return;
const skeleton = this._renderManagerService.getRenderById(unitId)
- ?.with(SheetSkeletonManagerService).getUnitSkeleton(unitId, subUnitId)
+ ?.with(SheetSkeletonManagerService).getWorksheetSkeleton(subUnitId)
?.skeleton;
const currentRender = this._renderManagerService.getRenderById(unitId);
@@ -223,7 +223,7 @@ export class SheetsDataValidationRenderController extends RxDisposable {
}
const skeleton = this._renderManagerService.getRenderById(unitId)
- ?.with(SheetSkeletonManagerService).getUnitSkeleton(unitId, subUnitId)
+ ?.with(SheetSkeletonManagerService).getWorksheetSkeleton(subUnitId)
?.skeleton;
if (!skeleton) {
return next(cell);
@@ -383,7 +383,7 @@ export class SheetsDataValidationMobileRenderController extends RxDisposable {
if (!subUnitId) return;
const skeleton = this._renderManagerService.getRenderById(unitId)
- ?.with(SheetSkeletonManagerService).getUnitSkeleton(unitId, subUnitId)
+ ?.with(SheetSkeletonManagerService).getWorksheetSkeleton(subUnitId)
?.skeleton;
const currentRender = this._renderManagerService.getRenderById(unitId);
@@ -415,7 +415,7 @@ export class SheetsDataValidationMobileRenderController extends RxDisposable {
}
const skeleton = this._renderManagerService.getRenderById(unitId)
- ?.with(SheetSkeletonManagerService).getUnitSkeleton(unitId, subUnitId)
+ ?.with(SheetSkeletonManagerService).getWorksheetSkeleton(subUnitId)
?.skeleton;
if (!skeleton) {
return next(cell);
diff --git a/packages/sheets-data-validation/src/controllers/dv.controller.ts b/packages/sheets-data-validation/src/controllers/dv.controller.ts
index 19b739c51b..1b135ff43b 100644
--- a/packages/sheets-data-validation/src/controllers/dv.controller.ts
+++ b/packages/sheets-data-validation/src/controllers/dv.controller.ts
@@ -20,7 +20,7 @@ import { DataValidationModel, DataValidatorRegistryService } from '@univerjs/dat
import { Inject, Injector } from '@wendellhu/redi';
import { DataValidationSingle } from '@univerjs/icons';
import { ComponentManager } from '@univerjs/ui';
-import { ClearSelectionAllCommand, SelectionManagerService, SheetInterceptorService } from '@univerjs/sheets';
+import { ClearSelectionAllCommand, SheetInterceptorService, SheetsSelectionsService } from '@univerjs/sheets';
import { SheetDataValidationService } from '../services/dv.service';
import { CustomFormulaValidator } from '../validators/custom-validator';
import { CheckboxValidator, DateValidator, DecimalValidator, ListValidator, TextLengthValidator } from '../validators';
@@ -38,7 +38,7 @@ export class DataValidationController extends RxDisposable {
@Inject(DataValidatorRegistryService) private readonly _dataValidatorRegistryService: DataValidatorRegistryService,
@Inject(Injector) private readonly _injector: Injector,
@Inject(ComponentManager) private readonly _componentManger: ComponentManager,
- @Inject(SelectionManagerService) private _selectionManagerService: SelectionManagerService,
+ @Inject(SheetsSelectionsService) private _selectionManagerService: SheetsSelectionsService,
@Inject(SheetInterceptorService) private readonly _sheetInterceptorService: SheetInterceptorService,
@Inject(DataValidationModel) private readonly _dataValidationModel: DataValidationModel
) {
@@ -115,7 +115,7 @@ export class DataValidationController extends RxDisposable {
}
const subUnitId = worksheet.getSheetId();
- const selections = this._selectionManagerService.getSelectionRanges();
+ const selections = this._selectionManagerService.getCurrentSelections()?.map((s) => s.range);
const manager = this._dataValidationModel.ensureManager(unitId, subUnitId) as SheetDataValidationManager;
diff --git a/packages/sheets-drawing-ui/src/basics/transform-position.ts b/packages/sheets-drawing-ui/src/basics/transform-position.ts
index 7e076fd571..813dc1ce37 100644
--- a/packages/sheets-drawing-ui/src/basics/transform-position.ts
+++ b/packages/sheets-drawing-ui/src/basics/transform-position.ts
@@ -18,14 +18,17 @@ import type { Nullable } from '@univerjs/core';
import type { ITransformState } from '@univerjs/drawing';
import { precisionTo } from '@univerjs/engine-render';
import type { ISheetDrawingPosition } from '@univerjs/sheets-drawing';
-import type { ISelectionRenderService, SheetSkeletonManagerService } from '@univerjs/sheets-ui';
+import type { ISheetSelectionRenderService, SheetSkeletonManagerService } from '@univerjs/sheets-ui';
-export function drawingPositionToTransform(position: ISheetDrawingPosition, selectionRenderService: ISelectionRenderService, sheetSkeletonManagerService: SheetSkeletonManagerService): Nullable<ITransformState> {
+export function drawingPositionToTransform(
+ position: ISheetDrawingPosition,
+ selectionRenderService: ISheetSelectionRenderService,
+ sheetSkeletonManagerService: SheetSkeletonManagerService): Nullable<ITransformState> {
const { from, to, flipY = false, flipX = false, angle = 0, skewX = 0, skewY = 0 } = position;
const { column: fromColumn, columnOffset: fromColumnOffset, row: fromRow, rowOffset: fromRowOffset } = from;
const { column: toColumn, columnOffset: toColumnOffset, row: toRow, rowOffset: toRowOffset } = to;
- const startSelectionCell = selectionRenderService.attachRangeWithCoord({
+ const startSelectionCell = sheetSkeletonManagerService.attachRangeWithCoord({
startColumn: fromColumn,
endColumn: fromColumn,
startRow: fromRow,
@@ -36,7 +39,7 @@ export function drawingPositionToTransform(position: ISheetDrawingPosition, sele
return;
}
- const endSelectionCell = selectionRenderService.attachRangeWithCoord({
+ const endSelectionCell = sheetSkeletonManagerService.attachRangeWithCoord({
startColumn: toColumn,
endColumn: toColumn,
startRow: toRow,
@@ -86,7 +89,7 @@ export function drawingPositionToTransform(position: ISheetDrawingPosition, sele
}
// use transform and originSize convert to ISheetDrawingPosition
-export function transformToDrawingPosition(transform: ITransformState, selectionRenderService: ISelectionRenderService): Nullable<ISheetDrawingPosition> {
+export function transformToDrawingPosition(transform: ITransformState, selectionRenderService: ISheetSelectionRenderService): Nullable<ISheetDrawingPosition> {
const { left = 0, top = 0, width = 0, height = 0, flipY = false, flipX = false, angle = 0, skewX = 0, skewY = 0 } = transform;
const startSelectionCell = selectionRenderService.getSelectionCellByPosition(left, top);
diff --git a/packages/sheets-drawing-ui/src/commands/commands/move-drawings.command.ts b/packages/sheets-drawing-ui/src/commands/commands/move-drawings.command.ts
index 42cd251fef..b087be6487 100644
--- a/packages/sheets-drawing-ui/src/commands/commands/move-drawings.command.ts
+++ b/packages/sheets-drawing-ui/src/commands/commands/move-drawings.command.ts
@@ -19,7 +19,7 @@ import { CommandType, Direction, ICommandService } from '@univerjs/core';
import type { ISheetDrawing } from '@univerjs/sheets-drawing';
import { ISheetDrawingService } from '@univerjs/sheets-drawing';
import type { IAccessor } from '@wendellhu/redi';
-import { ISelectionRenderService } from '@univerjs/sheets-ui';
+import { ISheetSelectionRenderService } from '@univerjs/sheets-ui';
import { transformToDrawingPosition } from '../../basics/transform-position';
import { ClearSheetDrawingTransformerOperation } from '../operations/clear-drawing-transformer.operation';
@@ -36,7 +36,7 @@ export const MoveDrawingsCommand: ICommand = {
handler: (accessor: IAccessor, params: IMoveDrawingsCommandParams) => {
const commandService = accessor.get(ICommandService);
const drawingManagerService = accessor.get(ISheetDrawingService);
- const selectionRenderService = accessor.get(ISelectionRenderService);
+ const selectionRenderService = accessor.get(ISheetSelectionRenderService);
const { direction } = params;
diff --git a/packages/sheets-drawing-ui/src/controllers/sheet-drawing-copy-paste.controller.ts b/packages/sheets-drawing-ui/src/controllers/sheet-drawing-copy-paste.controller.ts
index d7080535e7..54d23296a7 100644
--- a/packages/sheets-drawing-ui/src/controllers/sheet-drawing-copy-paste.controller.ts
+++ b/packages/sheets-drawing-ui/src/controllers/sheet-drawing-copy-paste.controller.ts
@@ -16,12 +16,12 @@
import type { IMutationInfo, IRange, Nullable } from '@univerjs/core';
import { Disposable, LifecycleStages, OnLifecycle, Tools } from '@univerjs/core';
-import type { IDiscreteRange, ISheetDiscreteRangeLocation } from '@univerjs/sheets-ui';
-import { COPY_TYPE, ISelectionRenderService, ISheetClipboardService, PREDEFINED_HOOK_NAME, virtualizeDiscreteRanges } from '@univerjs/sheets-ui';
-import { Inject, Injector } from '@wendellhu/redi';
+import type { IDrawingJsonUndo1 } from '@univerjs/drawing';
+import { IRenderManagerService } from '@univerjs/engine-render';
import type { ISheetDrawing } from '@univerjs/sheets-drawing';
import { DrawingApplyType, ISheetDrawingService, SetDrawingApplyMutation, SheetDrawingAnchorType } from '@univerjs/sheets-drawing';
-import type { IDrawingJsonUndo1 } from '@univerjs/drawing';
+import type { IDiscreteRange, ISheetDiscreteRangeLocation } from '@univerjs/sheets-ui';
+import { COPY_TYPE, ISheetClipboardService, PREDEFINED_HOOK_NAME, SheetSkeletonManagerService, virtualizeDiscreteRanges } from '@univerjs/sheets-ui';
@OnLifecycle(LifecycleStages.Ready, SheetsDrawingCopyPasteController)
export class SheetsDrawingCopyPasteController extends Disposable {
@@ -33,9 +33,12 @@ export class SheetsDrawingCopyPasteController extends Disposable {
constructor(
@ISheetClipboardService private _sheetClipboardService: ISheetClipboardService,
- @ISelectionRenderService private readonly _selectionRenderService: ISelectionRenderService,
- @ISheetDrawingService private readonly _sheetDrawingService: ISheetDrawingService,
- @Inject(Injector) private _injector: Injector
+ // @Inject(ISheetSelectionRenderService) private readonly _selectionRenderService: ISheetSelectionRenderService,
+
+ @IRenderManagerService private readonly _renderManagerService: IRenderManagerService,
+
+ @ISheetDrawingService private readonly _sheetDrawingService: ISheetDrawingService
+ // @Inject(Injector) private _injector: Injector
) {
super();
this._initCopyPaste();
@@ -58,7 +61,10 @@ export class SheetsDrawingCopyPasteController extends Disposable {
}
private _collect(unitId: string, subUnitId: string, range: IRange) {
- const selectionRect = this._selectionRenderService.attachRangeWithCoord(range);
+ const skeletonManagetService = this._renderManagerService.getRenderById(unitId)?.with(SheetSkeletonManagerService);
+ if (!skeletonManagetService) return;
+
+ const selectionRect = skeletonManagetService.attachRangeWithCoord(range);
if (!selectionRect) {
return;
}
@@ -133,13 +139,19 @@ export class SheetsDrawingCopyPasteController extends Disposable {
const { row: copyRow, col: copyCol } = mapFunc(vCopyRange.startRow, vCopyRange.startColumn);
const { row: pasteRow, col: pasteCol } = mapFunc(vPastedRange.startRow, vPastedRange.startColumn);
- const copyRect = this._selectionRenderService.attachRangeWithCoord({
+ const skeletonManagetService = this._renderManagerService.getRenderById(unitId)?.with(SheetSkeletonManagerService);
+
+ if (!skeletonManagetService) {
+ return { redos: [], undos: [] };
+ }
+
+ const copyRect = skeletonManagetService.attachRangeWithCoord({
startRow: copyRow,
endRow: copyRow,
startColumn: copyCol,
endColumn: copyCol,
});
- const pasteRect = this._selectionRenderService.attachRangeWithCoord({
+ const pasteRect = skeletonManagetService.attachRangeWithCoord({
startRow: pasteRow,
endRow: pasteRow,
startColumn: pasteCol,
diff --git a/packages/sheets-drawing-ui/src/controllers/sheet-drawing-printing.controller.ts b/packages/sheets-drawing-ui/src/controllers/sheet-drawing-printing.controller.ts
index aa32634433..a3f4116743 100644
--- a/packages/sheets-drawing-ui/src/controllers/sheet-drawing-printing.controller.ts
+++ b/packages/sheets-drawing-ui/src/controllers/sheet-drawing-printing.controller.ts
@@ -67,7 +67,7 @@ export class SheetDrawingPrintingController extends Disposable {
return next(range);
}
- const skeleton = renderer.with(SheetSkeletonManagerService).getUnitSkeleton(unitId, subUnitId);
+ const skeleton = renderer.with(SheetSkeletonManagerService).getWorksheetSkeleton(subUnitId);
if (!skeleton) {
return next(range);
}
diff --git a/packages/sheets-drawing-ui/src/controllers/sheet-drawing-transform-affected.controller.ts b/packages/sheets-drawing-ui/src/controllers/sheet-drawing-transform-affected.controller.ts
index 73e336b0b8..942b5b7927 100644
--- a/packages/sheets-drawing-ui/src/controllers/sheet-drawing-transform-affected.controller.ts
+++ b/packages/sheets-drawing-ui/src/controllers/sheet-drawing-transform-affected.controller.ts
@@ -14,16 +14,16 @@
* limitations under the License.
*/
-import type { ICommandInfo, IMutationInfo, IRange, Nullable, Workbook } from '@univerjs/core';
-import { Disposable, ICommandService, IUniverInstanceService, LifecycleStages, OnLifecycle, Rectangle } from '@univerjs/core';
+import type { ICommandInfo, IMutationInfo, IRange, Nullable } from '@univerjs/core';
+import { Disposable, ICommandService, IUniverInstanceService, LifecycleStages, OnLifecycle, Rectangle, UniverInstanceType } from '@univerjs/core';
import { Inject } from '@wendellhu/redi';
-import { ISelectionRenderService, SheetSkeletonManagerService } from '@univerjs/sheets-ui';
+import { ISheetSelectionRenderService, SheetSkeletonManagerService } from '@univerjs/sheets-ui';
import { type IDrawingJsonUndo1, IDrawingManagerService, type IDrawingParam, type ITransformState } from '@univerjs/drawing';
-import type { IInsertColCommandParams, IInsertRowCommandParams, IMoveRangeCommandParams, IRemoveRowColCommandParams, ISetColHiddenMutationParams, ISetColVisibleMutationParams, ISetRowHiddenMutationParams, ISetRowVisibleMutationParams, ISetSpecificColsVisibleCommandParams, ISetSpecificRowsVisibleCommandParams, ISetWorksheetActiveOperationParams, ISetWorksheetColWidthMutationParams, ISetWorksheetRowHeightMutationParams, ISetWorksheetRowIsAutoHeightMutationParams } from '@univerjs/sheets';
-import { DeleteRangeMoveLeftCommand, DeleteRangeMoveUpCommand, DeltaColumnWidthCommand, DeltaRowHeightCommand, getSheetCommandTarget, InsertColCommand, InsertRangeMoveDownCommand, InsertRangeMoveRightCommand, InsertRowCommand, MoveRangeCommand, RemoveColCommand, RemoveRowCommand, SetColHiddenCommand, SetColHiddenMutation, SetColVisibleMutation, SetColWidthCommand, SetRowHeightCommand, SetRowHiddenCommand, SetRowHiddenMutation, SetRowVisibleMutation, SetSpecificColsVisibleCommand, SetSpecificRowsVisibleCommand, SetWorksheetActiveOperation, SetWorksheetColWidthMutation, SetWorksheetRowHeightMutation, SheetInterceptorService } from '@univerjs/sheets';
+import type { IInsertColCommandParams, IInsertRowCommandParams, IRemoveRowColCommandParams, ISetColHiddenMutationParams, ISetColVisibleMutationParams, ISetRowHiddenMutationParams, ISetRowVisibleMutationParams, ISetSpecificColsVisibleCommandParams, ISetSpecificRowsVisibleCommandParams, ISetWorksheetActiveOperationParams, ISetWorksheetColWidthMutationParams, ISetWorksheetRowHeightMutationParams, ISetWorksheetRowIsAutoHeightMutationParams } from '@univerjs/sheets';
+import { DeleteRangeMoveLeftCommand, DeleteRangeMoveUpCommand, DeltaColumnWidthCommand, DeltaRowHeightCommand, getSheetCommandTarget, InsertColCommand, InsertRangeMoveDownCommand, InsertRangeMoveRightCommand, InsertRowCommand, RemoveColCommand, RemoveRowCommand, SetColHiddenCommand, SetColHiddenMutation, SetColVisibleMutation, SetColWidthCommand, SetRowHeightCommand, SetRowHiddenCommand, SetRowHiddenMutation, SetRowVisibleMutation, SetSpecificColsVisibleCommand, SetSpecificRowsVisibleCommand, SetWorksheetActiveOperation, SetWorksheetColWidthMutation, SetWorksheetRowHeightMutation, SheetInterceptorService } from '@univerjs/sheets';
import type { ISheetDrawing, ISheetDrawingPosition } from '@univerjs/sheets-drawing';
import { DrawingApplyType, ISheetDrawingService, SetDrawingApplyMutation, SheetDrawingAnchorType } from '@univerjs/sheets-drawing';
-import type { IRenderContext, IRenderModule } from '@univerjs/engine-render';
+import { IRenderManagerService } from '@univerjs/engine-render';
import { drawingPositionToTransform, transformToDrawingPosition } from '../basics/transform-position';
import { ClearSheetDrawingTransformerOperation } from '../commands/operations/clear-drawing-transformer.operation';
@@ -51,7 +51,6 @@ const UPDATE_COMMANDS = [
SetSpecificRowsVisibleCommand.id,
SetSpecificColsVisibleCommand.id,
SetColHiddenCommand.id,
- MoveRangeCommand.id,
];
const REFRESH_MUTATIONS = [
@@ -64,16 +63,28 @@ const REFRESH_MUTATIONS = [
];
@OnLifecycle(LifecycleStages.Rendered, SheetDrawingTransformAffectedController)
-export class SheetDrawingTransformAffectedController extends Disposable implements IRenderModule {
+export class SheetDrawingTransformAffectedController extends Disposable {
+ // TODO@wzhudev: selection render service would be a render unit, we we cannot
+ // easily access it here.
+ private get _selectionRenderService(): ISheetSelectionRenderService {
+ return this._renderManagerService.getRenderById(
+ this._univerInstanceService.getCurrentUnitForType(UniverInstanceType.UNIVER_SHEET)!.getUnitId()
+ )!.with(ISheetSelectionRenderService);
+ }
+
+ private get _skeletonManagerService(): SheetSkeletonManagerService {
+ return this._renderManagerService.getRenderById(
+ this._univerInstanceService.getCurrentUnitForType(UniverInstanceType.UNIVER_SHEET)!.getUnitId()
+ )!.with(SheetSkeletonManagerService);
+ }
+
constructor(
- private readonly _context: IRenderContext<Workbook>,
@ICommandService private readonly _commandService: ICommandService,
@Inject(SheetInterceptorService) private readonly _sheetInterceptorService: SheetInterceptorService,
+ @IRenderManagerService private readonly _renderManagerService: IRenderManagerService,
@ISheetDrawingService private readonly _sheetDrawingService: ISheetDrawingService,
@IDrawingManagerService private readonly _drawingManagerService: IDrawingManagerService,
- @ISelectionRenderService private readonly _selectionRenderService: ISelectionRenderService,
- @IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService,
- @Inject(SheetSkeletonManagerService) private readonly _sheetSkeletonManagerService: SheetSkeletonManagerService
+ @IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService
) {
super();
@@ -91,6 +102,7 @@ export class SheetDrawingTransformAffectedController extends Disposable implemen
private _sheetInterceptorListener() {
this.disposeWithMe(
this._sheetInterceptorService.interceptCommand({
+
getMutations: (commandInfo) => {
if (!UPDATE_COMMANDS.includes(commandInfo.id)) {
return { redos: [], undos: [] };
@@ -107,8 +119,6 @@ export class SheetDrawingTransformAffectedController extends Disposable implemen
return this._moveRowInterceptor(commandInfo.params as IRemoveRowColCommandParams, 'remove');
} else if (cId === RemoveColCommand.id) {
return this._moveColInterceptor(commandInfo.params as IRemoveRowColCommandParams, 'remove');
- } else if (cId === MoveRangeCommand.id) {
- return this._moveRangeInterceptor(commandInfo.params as IMoveRangeCommandParams);
} else if (cId === DeleteRangeMoveLeftCommand.id) {
const { range } = commandInfo.params as IRemoveRowColCommandParams;
return this._getRangeMoveUndo(range, RangeMoveUndoType.deleteLeft);
@@ -248,7 +258,7 @@ export class SheetDrawingTransformAffectedController extends Disposable implemen
}
if (newSheetTransform != null && newTransform != null) {
- const newTransform = drawingPositionToTransform(newSheetTransform, this._selectionRenderService, this._sheetSkeletonManagerService);
+ const newTransform = drawingPositionToTransform(newSheetTransform, this._selectionRenderService, this._skeletonManagerService);
updateDrawings.push({ ...drawing, sheetTransform: newSheetTransform, transform: newTransform });
}
@@ -290,7 +300,7 @@ export class SheetDrawingTransformAffectedController extends Disposable implemen
let newSheetTransform: Nullable<ISheetDrawingPosition> = null;
let newTransform: Nullable<ITransformState> = null;
if (fromColumn >= startColumn && fromColumn <= endColumn) {
- const selectionCell = this._selectionRenderService.attachRangeWithCoord({ startColumn: fromColumn, endColumn, startRow: from.row, endRow: to.row });
+ const selectionCell = this._skeletonManagerService.attachRangeWithCoord({ startColumn: fromColumn, endColumn, startRow: from.row, endRow: to.row });
if (selectionCell == null) {
return;
}
@@ -315,7 +325,7 @@ export class SheetDrawingTransformAffectedController extends Disposable implemen
let newTransform: Nullable<ITransformState> = null;
if (fromColumn >= startColumn && fromColumn <= endColumn) {
- const selectionCell = this._selectionRenderService.attachRangeWithCoord({ startColumn: fromColumn, endColumn, startRow: from.row, endRow: to.row });
+ const selectionCell = this._skeletonManagerService.attachRangeWithCoord({ startColumn: fromColumn, endColumn, startRow: from.row, endRow: to.row });
if (selectionCell == null) {
return;
}
@@ -325,7 +335,7 @@ export class SheetDrawingTransformAffectedController extends Disposable implemen
width: (transform?.width || 0) - selectionCell.endX + selectionCell.startX,
};
} else if (toColumn >= startColumn && toColumn <= endColumn) {
- const selectionCell = this._selectionRenderService.attachRangeWithCoord({ startColumn, endColumn: toColumn, startRow: from.row, endRow: to.row });
+ const selectionCell = this._skeletonManagerService.attachRangeWithCoord({ startColumn, endColumn: toColumn, startRow: from.row, endRow: to.row });
if (selectionCell == null) {
return;
}
@@ -334,7 +344,7 @@ export class SheetDrawingTransformAffectedController extends Disposable implemen
left: selectionCell.startX - (transform?.width || 0),
};
} else {
- const selectionCell = this._selectionRenderService.attachRangeWithCoord({ startColumn, endColumn, startRow: from.row, endRow: to.row });
+ const selectionCell = this._skeletonManagerService.attachRangeWithCoord({ startColumn, endColumn, startRow: from.row, endRow: to.row });
if (selectionCell == null) {
return;
}
@@ -429,7 +439,7 @@ export class SheetDrawingTransformAffectedController extends Disposable implemen
let newSheetTransform: Nullable<ISheetDrawingPosition> = null;
let newTransform: Nullable<ITransformState> = null;
if (fromRow >= startRow && fromRow <= endRow) {
- const selectionCell = this._selectionRenderService.attachRangeWithCoord({ startColumn: from.column, endColumn: to.column, startRow: fromRow, endRow });
+ const selectionCell = this._skeletonManagerService.attachRangeWithCoord({ startColumn: from.column, endColumn: to.column, startRow: fromRow, endRow });
if (selectionCell == null) {
return;
}
@@ -454,7 +464,7 @@ export class SheetDrawingTransformAffectedController extends Disposable implemen
let newTransform: Nullable<ITransformState> = null;
if (fromRow >= startRow && fromRow <= endRow) {
- const selectionCell = this._selectionRenderService.attachRangeWithCoord({ startColumn: from.column, endColumn: to.column, startRow: fromRow, endRow });
+ const selectionCell = this._skeletonManagerService.attachRangeWithCoord({ startColumn: from.column, endColumn: to.column, startRow: fromRow, endRow });
if (selectionCell == null) {
return;
}
@@ -464,7 +474,7 @@ export class SheetDrawingTransformAffectedController extends Disposable implemen
height: (transform?.height || 0) - selectionCell.endY + selectionCell.startY,
};
} else if (toRow >= startRow && toRow <= endRow) {
- const selectionCell = this._selectionRenderService.attachRangeWithCoord({ startColumn: from.column, endColumn: to.column, startRow, endRow: toRow });
+ const selectionCell = this._skeletonManagerService.attachRangeWithCoord({ startColumn: from.column, endColumn: to.column, startRow, endRow: toRow });
if (selectionCell == null) {
return;
}
@@ -473,7 +483,7 @@ export class SheetDrawingTransformAffectedController extends Disposable implemen
top: selectionCell.startY - (transform?.height || 0),
};
} else {
- const selectionCell = this._selectionRenderService.attachRangeWithCoord({ startColumn: from.column, endColumn: to.column, startRow, endRow });
+ const selectionCell = this._skeletonManagerService.attachRangeWithCoord({ startColumn: from.column, endColumn: to.column, startRow, endRow });
if (selectionCell == null) {
return;
}
@@ -553,7 +563,8 @@ export class SheetDrawingTransformAffectedController extends Disposable implemen
}
}
- const newTransform = drawingPositionToTransform({ ...sheetTransform }, this._selectionRenderService, this._sheetSkeletonManagerService);
+ const newTransform = drawingPositionToTransform({ ...sheetTransform },
+ this._selectionRenderService, this._skeletonManagerService);
if (newTransform != null) {
updateDrawings.push({
...drawing,
@@ -625,7 +636,7 @@ export class SheetDrawingTransformAffectedController extends Disposable implemen
const { from, to } = sheetTransform;
const { row: fromRow } = from;
const { row: toRow } = to;
- if (anchorType === SheetDrawingAnchorType.Both && fromRow >= rowStartIndex && toRow <= rowEndIndex) {
+ if (fromRow >= rowStartIndex && toRow <= rowEndIndex) {
// delete drawing
deleteDrawings.push({ unitId, subUnitId, drawingId });
} else {
@@ -670,111 +681,6 @@ export class SheetDrawingTransformAffectedController extends Disposable implemen
};
}
- private _moveRangeInterceptor(params: IMoveRangeCommandParams) {
- const { fromRange, toRange } = params;
- const target = getSheetCommandTarget(this._univerInstanceService);
- if (!target) {
- return { redos: [], undos: [] };
- }
- const { unitId, subUnitId } = target;
- const data = this._sheetDrawingService.getDrawingData(unitId, subUnitId);
- const drawings: Partial<ISheetDrawing>[] = [];
- // get rect info of toRange and fromRange
- const fromRangeRect = this._selectionRenderService.attachRangeWithCoord(fromRange);
- const toRangeRect = this._selectionRenderService.attachRangeWithCoord(toRange);
- if (!fromRangeRect || !toRangeRect) {
- return { redos: [], undos: [] };
- }
- Object.keys(data).forEach((drawingId) => {
- const drawing = data[drawingId];
- const { sheetTransform, transform, anchorType = SheetDrawingAnchorType.Position } = drawing;
-
- if (
- !sheetTransform || !transform || anchorType === SheetDrawingAnchorType.None) {
- return;
- }
-
- const { left = 0, top = 0, width = 0, height = 0 } = transform;
- const { drawingStartX, drawingEndX, drawingStartY, drawingEndY } = {
- drawingStartX: left,
- drawingEndX: left + width,
- drawingStartY: top,
- drawingEndY: top + height,
- };
-
- const contained = fromRangeRect.startX <= drawingStartX && drawingEndX <= fromRangeRect.endX && fromRangeRect.startY <= drawingEndY && drawingStartY <= fromRangeRect.endY;
- // If range does not contain drawing, skip
- if (!contained) {
- return;
- }
-
- const { to, from } = sheetTransform;
-
- const rowOffset = toRange.startRow - fromRange.startRow;
- const colOffset = toRange.startColumn - fromRange.startColumn;
-
- let newSheetTransform: Nullable<ISheetDrawingPosition>;
- let newTransform: Nullable<ITransformState>;
- if (anchorType === SheetDrawingAnchorType.Both) {
- const drawingFromRect = this._selectionRenderService.attachRangeWithCoord({
- startRow: to.row,
- endRow: from.row,
- startColumn: to.column,
- endColumn: from.column,
- });
- const drawingToRect = this._selectionRenderService.attachRangeWithCoord({
- startRow: to.row + rowOffset,
- endRow: from.row + rowOffset,
- startColumn: to.column + colOffset,
- endColumn: from.column + colOffset,
- });
- if (!drawingToRect || !drawingFromRect) {
- return;
- }
- // Both anchor drawing should calculate the offset of the width and height
- const widthOffset = (drawingToRect.endX - drawingToRect.startX) - (drawingFromRect.endX - drawingFromRect.startX);
- const heightOffset = (drawingToRect.endY - drawingToRect.startY) - (drawingFromRect.endY - drawingFromRect.startY);
-
- newSheetTransform = {
- to: { ...to, row: to.row + rowOffset, column: to.column + colOffset, columnOffset: to.columnOffset + widthOffset },
- from: { ...from, row: from.row + rowOffset, column: from.column + colOffset, columnOffset: to.columnOffset + widthOffset, rowOffset: to.rowOffset + heightOffset },
- };
- newTransform = drawingPositionToTransform(newSheetTransform, this._selectionRenderService, this._sheetSkeletonManagerService);
- } else {
- // Position anchor drawing only do the position offset
- const xOffset = toRangeRect.startX - fromRangeRect.startX;
- const yOffset = toRangeRect.startY - fromRangeRect.startY;
-
- newTransform = {
- ...transform,
- left: left + xOffset,
- top: top + yOffset,
- };
-
- newSheetTransform = transformToDrawingPosition(newTransform, this._selectionRenderService);
- }
-
- if (!newSheetTransform || !newTransform) {
- return;
- }
-
- const params = { unitId, subUnitId, drawingId, transform: newTransform, sheetTransform: newSheetTransform };
- drawings.push(params);
- });
-
- const redos: IMutationInfo[] = [];
- const undos: IMutationInfo[] = [];
-
- if (drawings.length > 0) {
- const updateJsonOp = this._sheetDrawingService.getBatchUpdateOp(drawings as ISheetDrawing[]) as IDrawingJsonUndo1;
- const { undo, redo, objects } = updateJsonOp;
- redos.push({ id: SetDrawingApplyMutation.id, params: { unitId, subUnitId, op: redo, objects, type: DrawingApplyType.UPDATE } });
- undos.push({ id: SetDrawingApplyMutation.id, params: { unitId, subUnitId, op: undo, objects, type: DrawingApplyType.UPDATE } });
- }
-
- return { redos, undos };
- }
-
private _moveColInterceptor(params: IInsertColCommandParams | IRemoveRowColCommandParams, type: 'insert' | 'remove') {
const ids = this._getUnitIdAndSubUnitId(params, type);
if (ids == null) {
@@ -810,8 +716,7 @@ export class SheetDrawingTransformAffectedController extends Disposable implemen
const { from, to } = sheetTransform;
const { column: fromColumn } = from;
const { column: toColumn } = to;
- const contained = fromColumn >= colStartIndex && toColumn <= colEndIndex;
- if (contained && anchorType === SheetDrawingAnchorType.Both) {
+ if (fromColumn >= colStartIndex && toColumn <= colEndIndex) {
// delete drawing
deleteDrawings.push({ unitId, subUnitId, drawingId });
} else {
@@ -879,9 +784,9 @@ export class SheetDrawingTransformAffectedController extends Disposable implemen
// from: { ...from, column: fromColumn + colCount },
// to: { ...to, column: toColumn + colCount },
// };
- // newTransform = drawingPositionToTransform(newSheetTransform, this._selectionRenderService, this._sheetSkeletonManagerService);
+ // newTransform = drawingPositionToTransform(newSheetTransform, this._selectionRenderService);
- const selectionCell = this._selectionRenderService.attachRangeWithCoord({ startColumn: colStartIndex, endColumn: colEndIndex, startRow: from.row, endRow: to.row });
+ const selectionCell = this._skeletonManagerService.attachRangeWithCoord({ startColumn: colStartIndex, endColumn: colEndIndex, startRow: from.row, endRow: to.row });
if (selectionCell == null) {
return;
}
@@ -894,7 +799,7 @@ export class SheetDrawingTransformAffectedController extends Disposable implemen
from: { ...from },
to: { ...to, column: toColumn + colCount },
};
- newTransform = drawingPositionToTransform(newSheetTransform, this._selectionRenderService, this._sheetSkeletonManagerService);
+ newTransform = drawingPositionToTransform(newSheetTransform, this._selectionRenderService, this._skeletonManagerService);
} else {
return {
newSheetTransform: transformToDrawingPosition({ ...transform }, this._selectionRenderService),
@@ -929,30 +834,14 @@ export class SheetDrawingTransformAffectedController extends Disposable implemen
if (fromColumn > colEndIndex) {
// shrink start and end col left only
- const selectionCell = this._selectionRenderService.attachRangeWithCoord({ startColumn: colStartIndex, endColumn: colEndIndex, startRow: from.row, endRow: to.row });
- if (selectionCell == null) {
- return;
- }
- newTransform = { ...transform, left: (transform.left || 0) - (selectionCell.endX - selectionCell.startX) };
- newSheetTransform = transformToDrawingPosition(newTransform, this._selectionRenderService);
- } else if (fromColumn >= colStartIndex && toColumn <= colEndIndex) {
- // delete drawing
- const selectionRect = this._selectionRenderService.attachRangeWithCoord({
- startColumn: colStartIndex,
- endColumn: colEndIndex,
- startRow: 0,
- endRow: 0,
- });
-
newSheetTransform = {
- from: { ...from, columnOffset: 0 },
- to: { ...to, columnOffset: to.columnOffset - from.columnOffset },
- };
-
- newTransform = {
- ...transform,
- left: selectionRect?.startX,
+ from: { ...from, column: fromColumn - colCount },
+ to: { ...to, column: toColumn - colCount },
};
+ newTransform = drawingPositionToTransform(newSheetTransform, this._selectionRenderService, this._skeletonManagerService);
+ } else if (fromColumn >= colStartIndex && toColumn <= colEndIndex) {
+ // delete drawing
+ return null;
} else if (fromColumn < colStartIndex && toColumn > colEndIndex) {
// shrink end left only
if (anchorType === SheetDrawingAnchorType.Both) {
@@ -960,7 +849,7 @@ export class SheetDrawingTransformAffectedController extends Disposable implemen
from: { ...from },
to: { ...to, column: toColumn - colCount },
};
- newTransform = drawingPositionToTransform(newSheetTransform, this._selectionRenderService, this._sheetSkeletonManagerService);
+ newTransform = drawingPositionToTransform(newSheetTransform, this._selectionRenderService, this._skeletonManagerService);
} else {
return {
newSheetTransform: transformToDrawingPosition({ ...transform }, this._selectionRenderService),
@@ -971,7 +860,7 @@ export class SheetDrawingTransformAffectedController extends Disposable implemen
if (fromColumn === colStartIndex) {
newTransform = { ...transform, left: (transform.left || 0) - sheetTransform.from.columnOffset };
} else {
- const selectionCell = this._selectionRenderService.attachRangeWithCoord({ startColumn: colStartIndex, endColumn: fromColumn - 1, startRow: from.row, endRow: to.row });
+ const selectionCell = this._skeletonManagerService.attachRangeWithCoord({ startColumn: colStartIndex, endColumn: fromColumn - 1, startRow: from.row, endRow: to.row });
if (selectionCell == null) {
return;
}
@@ -980,7 +869,7 @@ export class SheetDrawingTransformAffectedController extends Disposable implemen
newSheetTransform = transformToDrawingPosition(newTransform, this._selectionRenderService);
} else if (toColumn >= colStartIndex && toColumn <= colEndIndex && anchorType === SheetDrawingAnchorType.Both) {
// shrink end col left, then set toColOffset to full cell width
- const selectionCell = this._selectionRenderService.attachRangeWithCoord({
+ const selectionCell = this._skeletonManagerService.attachRangeWithCoord({
startColumn: colStartIndex - 1,
endColumn: colStartIndex - 1,
startRow: from.row,
@@ -994,7 +883,7 @@ export class SheetDrawingTransformAffectedController extends Disposable implemen
from: { ...from },
to: { ...to, column: colStartIndex - 1, columnOffset: selectionCell.endX - selectionCell.startX },
};
- newTransform = drawingPositionToTransform(newSheetTransform, this._selectionRenderService, this._sheetSkeletonManagerService);
+ newTransform = drawingPositionToTransform(newSheetTransform, this._selectionRenderService, this._skeletonManagerService);
}
if (newSheetTransform != null && newTransform != null) {
@@ -1027,7 +916,7 @@ export class SheetDrawingTransformAffectedController extends Disposable implemen
if (fromRow >= rowStartIndex) {
// move start and end row down
- const selectionCell = this._selectionRenderService.attachRangeWithCoord({ startRow: rowStartIndex, endRow: rowEndIndex, startColumn: from.column, endColumn: to.column });
+ const selectionCell = this._skeletonManagerService.attachRangeWithCoord({ startRow: rowStartIndex, endRow: rowEndIndex, startColumn: from.column, endColumn: to.column });
if (selectionCell == null) {
return;
}
@@ -1043,7 +932,7 @@ export class SheetDrawingTransformAffectedController extends Disposable implemen
row: toRow + rowCount,
},
};
- newTransform = drawingPositionToTransform(newSheetTransform, this._selectionRenderService, this._sheetSkeletonManagerService);
+ newTransform = drawingPositionToTransform(newSheetTransform, this._selectionRenderService, this._skeletonManagerService);
} else {
return {
newSheetTransform: transformToDrawingPosition({ ...transform }, this._selectionRenderService),
@@ -1086,25 +975,10 @@ export class SheetDrawingTransformAffectedController extends Disposable implemen
from: { ...from, row: fromRow - rowCount },
to: { ...to, row: toRow - rowCount },
};
- newTransform = drawingPositionToTransform(newSheetTransform, this._selectionRenderService, this._sheetSkeletonManagerService);
+ newTransform = drawingPositionToTransform(newSheetTransform, this._selectionRenderService, this._skeletonManagerService);
} else if (fromRow >= rowStartIndex && toRow <= rowEndIndex) {
// delete drawing
- const selectionRect = this._selectionRenderService.attachRangeWithCoord({
- startColumn: 0,
- endColumn: 0,
- startRow: rowStartIndex,
- endRow: rowEndIndex,
- });
-
- newSheetTransform = {
- from: { ...from, rowOffset: 0 },
- to: { ...to, rowOffset: to.rowOffset - from.rowOffset },
- };
-
- newTransform = {
- ...transform,
- top: selectionRect?.startY,
- };
+ return null;
} else if (fromRow < rowStartIndex && toRow > rowEndIndex) {
// shrink end up only
if (anchorType === SheetDrawingAnchorType.Both) {
@@ -1112,7 +986,7 @@ export class SheetDrawingTransformAffectedController extends Disposable implemen
from: { ...from },
to: { ...to, row: toRow - rowCount },
};
- newTransform = drawingPositionToTransform(newSheetTransform, this._selectionRenderService, this._sheetSkeletonManagerService);
+ newTransform = drawingPositionToTransform(newSheetTransform, this._selectionRenderService, this._skeletonManagerService);
} else {
return {
newSheetTransform: transformToDrawingPosition({ ...transform }, this._selectionRenderService),
@@ -1120,11 +994,11 @@ export class SheetDrawingTransformAffectedController extends Disposable implemen
};
}
} else if (fromRow >= rowStartIndex && fromRow <= rowEndIndex) {
- // shrink start and end row up, then set fromRowOffset to 0
+ // shrink start and end row up, then set fromRowOffset to 0
if (fromRow === rowStartIndex) {
newTransform = { ...transform, top: (transform.top || 0) - sheetTransform.from.rowOffset };
} else {
- const selectionCell = this._selectionRenderService.attachRangeWithCoord({ startRow: rowStartIndex, endRow: fromRow - 1, startColumn: from.column, endColumn: to.column });
+ const selectionCell = this._skeletonManagerService.attachRangeWithCoord({ startRow: rowStartIndex, endRow: fromRow - 1, startColumn: from.column, endColumn: to.column });
if (selectionCell == null) {
return;
}
@@ -1133,7 +1007,7 @@ export class SheetDrawingTransformAffectedController extends Disposable implemen
newSheetTransform = transformToDrawingPosition(newTransform, this._selectionRenderService);
} else if (toRow >= rowStartIndex && toRow <= rowEndIndex && anchorType === SheetDrawingAnchorType.Both) {
// shrink end row up, then set toRowOffset to full cell height
- const selectionCell = this._selectionRenderService.attachRangeWithCoord({ startColumn: from.column, endColumn: from.column, startRow: rowStartIndex - 1, endRow: rowStartIndex - 1 });
+ const selectionCell = this._skeletonManagerService.attachRangeWithCoord({ startColumn: from.column, endColumn: from.column, startRow: rowStartIndex - 1, endRow: rowStartIndex - 1 });
if (selectionCell == null) {
return;
@@ -1142,7 +1016,7 @@ export class SheetDrawingTransformAffectedController extends Disposable implemen
from: { ...from },
to: { ...to, row: rowStartIndex - 1, rowOffset: selectionCell.endY - selectionCell.startY },
};
- newTransform = drawingPositionToTransform(newSheetTransform, this._selectionRenderService, this._sheetSkeletonManagerService);
+ newTransform = drawingPositionToTransform(newSheetTransform, this._selectionRenderService, this._skeletonManagerService);
}
if (newSheetTransform != null && newTransform != null) {
@@ -1179,7 +1053,7 @@ export class SheetDrawingTransformAffectedController extends Disposable implemen
Object.keys(drawingData).forEach((drawingId) => {
if (unitId === showUnitId && subUnitId === showSubunitId) {
const drawing = drawingData[drawingId] as ISheetDrawing;
- drawing.transform = drawingPositionToTransform(drawing.sheetTransform, this._selectionRenderService, this._sheetSkeletonManagerService);
+ drawing.transform = drawingPositionToTransform(drawing.sheetTransform, this._selectionRenderService, this._skeletonManagerService);
insertDrawings.push(drawingData[drawingId]);
} else {
removeDrawings.push(drawingData[drawingId]);
@@ -1240,7 +1114,7 @@ export class SheetDrawingTransformAffectedController extends Disposable implemen
) || fromRow > endRow || fromColumn > endColumn) {
updateDrawings.push({
...drawing,
- transform: drawingPositionToTransform(sheetTransform, this._selectionRenderService, this._sheetSkeletonManagerService),
+ transform: drawingPositionToTransform(sheetTransform, this._selectionRenderService, this._skeletonManagerService),
});
break;
}
diff --git a/packages/sheets-drawing-ui/src/controllers/sheet-drawing-update.controller.ts b/packages/sheets-drawing-ui/src/controllers/sheet-drawing-update.controller.ts
index 981a013d9c..ce04c298b1 100644
--- a/packages/sheets-drawing-ui/src/controllers/sheet-drawing-update.controller.ts
+++ b/packages/sheets-drawing-ui/src/controllers/sheet-drawing-update.controller.ts
@@ -14,18 +14,17 @@
* limitations under the License.
*/
-import type { ICommandInfo, IRange, Nullable, Workbook } from '@univerjs/core';
+import type { ICommandInfo, IDrawingSearch, IRange, Nullable, Workbook } from '@univerjs/core';
import { Disposable, FOCUSING_COMMON_DRAWINGS, ICommandService, IContextService, IUniverInstanceService, LifecycleStages, LocaleService, OnLifecycle, UniverInstanceType } from '@univerjs/core';
import { Inject } from '@wendellhu/redi';
-import type { IDrawingSearch, IImageData, IImageIoServiceParam } from '@univerjs/drawing';
+import type { IImageData, IImageIoServiceParam } from '@univerjs/drawing';
import { DRAWING_IMAGE_ALLOW_SIZE, DRAWING_IMAGE_COUNT_LIMIT, DRAWING_IMAGE_HEIGHT_LIMIT, DRAWING_IMAGE_WIDTH_LIMIT, DrawingTypeEnum, getImageSize, IDrawingManagerService, IImageIoService, ImageUploadStatusType } from '@univerjs/drawing';
import type { ISheetDrawing, ISheetDrawingPosition } from '@univerjs/sheets-drawing';
import { ISheetDrawingService } from '@univerjs/sheets-drawing';
-import { SelectionManagerService } from '@univerjs/sheets';
-import { ISelectionRenderService, SheetSkeletonManagerService } from '@univerjs/sheets-ui';
+import { SheetsSelectionsService } from '@univerjs/sheets';
+import { attachRangeWithCoord, ISheetSelectionRenderService, SheetSkeletonManagerService } from '@univerjs/sheets-ui';
import { IMessageService } from '@univerjs/ui';
import { MessageType } from '@univerjs/design';
-import type { IRenderContext, IRenderModule } from '@univerjs/engine-render';
import { IRenderManagerService } from '@univerjs/engine-render';
import type { IInsertImageOperationParams } from '../commands/operations/insert-image.operation';
import { InsertCellImageOperation, InsertFloatImageOperation } from '../commands/operations/insert-image.operation';
@@ -39,21 +38,32 @@ import { UngroupSheetDrawingCommand } from '../commands/commands/ungroup-sheet-d
import { drawingPositionToTransform, transformToDrawingPosition } from '../basics/transform-position';
@OnLifecycle(LifecycleStages.Rendered, SheetDrawingUpdateController)
-export class SheetDrawingUpdateController extends Disposable implements IRenderModule {
+export class SheetDrawingUpdateController extends Disposable {
+ // TODO@wzhudev: selection render service would be a render unit, we we cannot
+ // easily access it here.
+ private get _selectionRenderService(): ISheetSelectionRenderService {
+ return this._renderManagerService.getRenderById(
+ this._univerInstanceService.getCurrentUnitForType(UniverInstanceType.UNIVER_SHEET)!.getUnitId()
+ )!.with(ISheetSelectionRenderService);
+ }
+
+ private get _skeletonManagerService(): SheetSkeletonManagerService {
+ return this._renderManagerService.getRenderById(
+ this._univerInstanceService.getCurrentUnitForType(UniverInstanceType.UNIVER_SHEET)!.getUnitId()
+ )!.with(SheetSkeletonManagerService);
+ }
+
constructor(
- private readonly _context: IRenderContext<Workbook>,
@ICommandService private readonly _commandService: ICommandService,
@IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService,
- @Inject(SelectionManagerService) private readonly _selectionManagerService: SelectionManagerService,
- @ISelectionRenderService private readonly _selectionRenderService: ISelectionRenderService,
+ @Inject(SheetsSelectionsService) private readonly _selectionManagerService: SheetsSelectionsService,
@IImageIoService private readonly _imageIoService: IImageIoService,
@ISheetDrawingService private readonly _sheetDrawingService: ISheetDrawingService,
@IDrawingManagerService private readonly _drawingManagerService: IDrawingManagerService,
@IContextService private readonly _contextService: IContextService,
@IMessageService private readonly _messageService: IMessageService,
@Inject(LocaleService) private readonly _localeService: LocaleService,
- @IRenderManagerService private readonly _renderManagerService: IRenderManagerService,
- @Inject(SheetSkeletonManagerService) private readonly _sheetSkeletonManagerService: SheetSkeletonManagerService
+ @IRenderManagerService private readonly _renderManagerService: IRenderManagerService
) {
super();
@@ -70,8 +80,6 @@ export class SheetDrawingUpdateController extends Disposable implements IRenderM
this._groupDrawingListener();
this._focusDrawingListener();
-
- this._drawingAddListener();
}
/**
@@ -182,7 +190,7 @@ export class SheetDrawingUpdateController extends Disposable implements IRenderM
drawingType: DrawingTypeEnum.DRAWING_IMAGE,
imageSourceType,
source,
- transform: drawingPositionToTransform(sheetTransform, this._selectionRenderService, this._sheetSkeletonManagerService),
+ transform: drawingPositionToTransform(sheetTransform, this._selectionRenderService, this._skeletonManagerService),
sheetTransform,
};
@@ -213,7 +221,7 @@ export class SheetDrawingUpdateController extends Disposable implements IRenderM
}
private _getImagePosition(imageWidth: number, imageHeight: number, sceneWidth: number, sceneHeight: number): Nullable<ISheetDrawingPosition> {
- const selections = this._selectionManagerService.getSelections();
+ const selections = this._selectionManagerService.getCurrentSelections();
let range: IRange = {
startRow: 0,
endRow: 0,
@@ -224,7 +232,7 @@ export class SheetDrawingUpdateController extends Disposable implements IRenderM
range = selections[selections.length - 1].range;
}
- const rangeWithCoord = this._selectionRenderService.attachRangeWithCoord(range);
+ const rangeWithCoord = attachRangeWithCoord(this._skeletonManagerService.getCurrent()!.skeleton, range);
if (rangeWithCoord == null) {
return;
}
@@ -338,7 +346,7 @@ export class SheetDrawingUpdateController extends Disposable implements IRenderM
const newDrawing: Partial<ISheetDrawing> = {
...param,
- transform: { ...sheetDrawing.transform, ...transform, ...drawingPositionToTransform(sheetTransform, this._selectionRenderService, this._sheetSkeletonManagerService) },
+ transform: { ...sheetDrawing.transform, ...transform, ...drawingPositionToTransform(sheetTransform, this._selectionRenderService, this._skeletonManagerService) },
sheetTransform: { ...sheetTransform },
};
@@ -398,7 +406,7 @@ export class SheetDrawingUpdateController extends Disposable implements IRenderM
const { sheetTransform } = drawingParam;
- drawingParam.transform = drawingPositionToTransform(sheetTransform, this._selectionRenderService, this._sheetSkeletonManagerService);
+ drawingParam.transform = drawingPositionToTransform(sheetTransform, this._selectionRenderService, this._skeletonManagerService);
});
const unitId = params[0].unitId;
diff --git a/packages/sheets-drawing-ui/src/plugin.ts b/packages/sheets-drawing-ui/src/plugin.ts
index b470fbb811..596fe799fb 100644
--- a/packages/sheets-drawing-ui/src/plugin.ts
+++ b/packages/sheets-drawing-ui/src/plugin.ts
@@ -56,6 +56,10 @@ export class UniverSheetsDrawingUIPlugin extends Plugin {
this._initDependencies(_injector);
}
+ override onRendered(): void {
+ this._registerRenderModules();
+ }
+
private _initDependencies(injector: Injector): void {
const dependencies: Dependency[] = [
@@ -80,6 +84,15 @@ export class UniverSheetsDrawingUIPlugin extends Plugin {
];
dependencies.forEach((dependency) => injector.add(dependency));
- renderModules.forEach((controller) => this._renderManagerService.registerRenderModule(UniverInstanceType.UNIVER_SHEET, controller));
+ renderModules.forEach((controller) => this._renderManagerService.registerRenderModule(UniverInstanceType.UNIVER_SHEET, controller as unknown as Dependency));
+ }
+
+ private _registerRenderModules(): void {
+ ([
+ [SheetsDrawingCopyPasteController],
+
+ ] as Dependency[]).forEach((m) => {
+ this.disposeWithMe(this._renderManagerService.registerRenderModule(UniverInstanceType.UNIVER_SHEET, m));
+ });
}
}
diff --git a/packages/sheets-drawing-ui/src/services/canvas-float-dom-manager.service.ts b/packages/sheets-drawing-ui/src/services/canvas-float-dom-manager.service.ts
index fd61538a1a..ede44524ea 100644
--- a/packages/sheets-drawing-ui/src/services/canvas-float-dom-manager.service.ts
+++ b/packages/sheets-drawing-ui/src/services/canvas-float-dom-manager.service.ts
@@ -24,7 +24,7 @@ import type { ISetFrozenMutationParams } from '@univerjs/sheets';
import { getSheetCommandTarget, SetFrozenMutation } from '@univerjs/sheets';
import type { IFloatDomData, ISheetDrawingPosition, ISheetFloatDom } from '@univerjs/sheets-drawing';
import { DrawingApplyType, ISheetDrawingService, SetDrawingApplyMutation } from '@univerjs/sheets-drawing';
-import { ISelectionRenderService, SetScrollOperation, SetZoomRatioOperation, SheetSkeletonManagerService } from '@univerjs/sheets-ui';
+import { ISheetSelectionRenderService, SetScrollOperation, SetZoomRatioOperation, SheetSkeletonManagerService } from '@univerjs/sheets-ui';
import type { IFloatDomLayout } from '@univerjs/ui';
import { CanvasFloatDomService } from '@univerjs/ui';
import type { IDisposable } from '@wendellhu/redi';
@@ -167,7 +167,7 @@ export class SheetCanvasFloatDomManagerService extends Disposable {
@IUniverInstanceService private _univerInstanceService: IUniverInstanceService,
@Inject(ICommandService) private _commandService: ICommandService,
@IDrawingManagerService private _drawingManagerService: IDrawingManagerService,
- @ISelectionRenderService private readonly _selectionRenderService: ISelectionRenderService,
+ @ISheetSelectionRenderService private readonly _selectionRenderService: ISheetSelectionRenderService,
@Inject(CanvasFloatDomService) private readonly _canvasFloatDomService: CanvasFloatDomService,
@ISheetDrawingService private readonly _sheetDrawingService: ISheetDrawingService
) {
@@ -223,7 +223,7 @@ export class SheetCanvasFloatDomManagerService extends Disposable {
const { unitId, subUnitId, drawingId } = param;
const target = getSheetCommandTarget(this._univerInstanceService, { unitId, subUnitId });
const floatDomParam = this._drawingManagerService.getDrawingByParam(param) as IFloatDomData;
- const skeleton = this._renderManagerService.getRenderById(unitId)?.with(SheetSkeletonManagerService).getUnitSkeleton(unitId, subUnitId);
+ const skeleton = this._renderManagerService.getRenderById(unitId)?.with(SheetSkeletonManagerService).getWorksheetSkeleton(subUnitId);
if (floatDomParam == null || target == null || skeleton == null) {
return;
}
@@ -322,7 +322,7 @@ export class SheetCanvasFloatDomManagerService extends Disposable {
const map = this._ensureMap(unitId, subUnitId);
const ids = Array.from(map.keys());
const target = getSheetCommandTarget(this._univerInstanceService, { unitId, subUnitId });
- const skeleton = this._renderManagerService.getRenderById(unitId)?.with(SheetSkeletonManagerService).getUnitSkeleton(unitId, subUnitId);
+ const skeleton = this._renderManagerService.getRenderById(unitId)?.with(SheetSkeletonManagerService).getWorksheetSkeleton(subUnitId);
if (!renderObject || !target || !skeleton) {
return;
}
diff --git a/packages/sheets-filter-ui/src/commands/commands/__tests__/sheets-filter.command.spec.ts b/packages/sheets-filter-ui/src/commands/commands/__tests__/sheets-filter.command.spec.ts
index 185eede690..d9a06ca872 100644
--- a/packages/sheets-filter-ui/src/commands/commands/__tests__/sheets-filter.command.spec.ts
+++ b/packages/sheets-filter-ui/src/commands/commands/__tests__/sheets-filter.command.spec.ts
@@ -17,7 +17,7 @@
import type { IRange, IWorkbookData } from '@univerjs/core';
import { AuthzIoLocalService, IAuthzIoService, ICommandService, IUniverInstanceService, LocaleType, Plugin, RANGE_TYPE, RedoCommand, UndoCommand, Univer, UniverInstanceType } from '@univerjs/core';
import type { ISetRangeValuesCommandParams } from '@univerjs/sheets';
-import { NORMAL_SELECTION_PLUGIN_NAME, RangeProtectionRuleModel, RefRangeService, SelectionManagerService, SetRangeValuesCommand, SetRangeValuesMutation, SheetInterceptorService, WorkbookPermissionService, WorksheetPermissionService, WorksheetProtectionPointModel, WorksheetProtectionRuleModel } from '@univerjs/sheets';
+import { RangeProtectionRuleModel, RefRangeService, SetRangeValuesCommand, SetRangeValuesMutation, SheetInterceptorService, SheetsSelectionsService, WorkbookPermissionService, WorksheetPermissionService, WorksheetProtectionPointModel, WorksheetProtectionRuleModel } from '@univerjs/sheets';
import type { FilterModel, ISetSheetsFilterRangeMutationParams } from '@univerjs/sheets-filter';
import { SetSheetsFilterRangeMutation, SheetsFilterService, UniverSheetsFilterPlugin } from '@univerjs/sheets-filter';
import type { Dependency } from '@wendellhu/redi';
@@ -93,7 +93,7 @@ function createFilterCommandTestBed() {
([
[RefRangeService],
[SheetInterceptorService],
- [SelectionManagerService],
+ [SheetsSelectionsService],
[WorksheetPermissionService],
[WorksheetProtectionPointModel],
[WorkbookPermissionService],
@@ -131,7 +131,7 @@ describe('test sheets filter commands', () => {
let get: Injector['get'];
let commandService: ICommandService;
let sheetsFilterService: SheetsFilterService;
- let selectionManagerService: SelectionManagerService;
+ let selectionManagerService: SheetsSelectionsService;
beforeEach(() => {
const testBed = createFilterCommandTestBed();
@@ -140,7 +140,7 @@ describe('test sheets filter commands', () => {
commandService = get(ICommandService);
sheetsFilterService = get(SheetsFilterService);
- selectionManagerService = get(SelectionManagerService);
+ selectionManagerService = get(SheetsSelectionsService);
});
afterEach(() => {
@@ -148,14 +148,8 @@ describe('test sheets filter commands', () => {
});
function select(range: IRange) {
- selectionManagerService.setCurrentSelection({
- pluginName: NORMAL_SELECTION_PLUGIN_NAME,
- unitId: 'test',
- sheetId: 'sheet1',
- });
-
const { startColumn, startRow, endColumn, endRow } = range;
- selectionManagerService.add([
+ selectionManagerService.addSelections([
{
range: { startRow, startColumn, endColumn, endRow, rangeType: RANGE_TYPE.NORMAL },
primary: {
diff --git a/packages/sheets-filter-ui/src/commands/commands/sheets-filter.command.ts b/packages/sheets-filter-ui/src/commands/commands/sheets-filter.command.ts
index 167c184cdb..6c1cdafc67 100644
--- a/packages/sheets-filter-ui/src/commands/commands/sheets-filter.command.ts
+++ b/packages/sheets-filter-ui/src/commands/commands/sheets-filter.command.ts
@@ -18,7 +18,7 @@ import type { ICommand, IMutationInfo, Nullable, Workbook } from '@univerjs/core
import { CommandType, ICommandService, IUndoRedoService, IUniverInstanceService, LocaleService, sequenceExecute, UniverInstanceType } from '@univerjs/core';
import { MessageType } from '@univerjs/design';
import type { ISheetCommandSharedParams } from '@univerjs/sheets';
-import { isSingleCellSelection, SelectionManagerService } from '@univerjs/sheets';
+import { isSingleCellSelection, SheetsSelectionsService } from '@univerjs/sheets';
import type { FilterColumn, IAutoFilter, IFilterColumn, IReCalcSheetsFilterMutationParams, ISetSheetsFilterCriteriaMutationParams, ISetSheetsFilterRangeMutationParams } from '@univerjs/sheets-filter';
import { ReCalcSheetsFilterMutation, RemoveSheetsFilterMutation, SetSheetsFilterCriteriaMutation, SetSheetsFilterRangeMutation, SheetsFilterService } from '@univerjs/sheets-filter';
import { expandToContinuousRange } from '@univerjs/sheets-ui';
@@ -61,8 +61,8 @@ export const SmartToggleSheetsFilterCommand: ICommand = {
return result;
}
- const selectionManager = accessor.get(SelectionManagerService);
- const lastSelection = selectionManager.getLast();
+ const selectionManager = accessor.get(SheetsSelectionsService);
+ const lastSelection = selectionManager.getCurrentLastSelection();
if (!lastSelection) return false;
const startRange = lastSelection.range;
diff --git a/packages/sheets-filter-ui/src/commands/operations/__tests__/sheets-filter.operation.spec.ts b/packages/sheets-filter-ui/src/commands/operations/__tests__/sheets-filter.operation.spec.ts
index faad42bffa..0dbb416595 100644
--- a/packages/sheets-filter-ui/src/commands/operations/__tests__/sheets-filter.operation.spec.ts
+++ b/packages/sheets-filter-ui/src/commands/operations/__tests__/sheets-filter.operation.spec.ts
@@ -21,7 +21,7 @@ import { SetSheetsFilterRangeMutation, UniverSheetsFilterPlugin } from '@univerj
import type { Dependency } from '@wendellhu/redi';
import { Inject, Injector } from '@wendellhu/redi';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
-import { RefRangeService, SelectionManagerService, SheetInterceptorService } from '@univerjs/sheets';
+import { RefRangeService, SheetInterceptorService, SheetsSelectionsService } from '@univerjs/sheets';
import type { IEditorBridgeServiceVisibleParam } from '@univerjs/sheets-ui';
import { CloseFilterPanelOperation, FILTER_PANEL_OPENED_KEY, OpenFilterPanelOperation } from '../sheets-filter.operation';
import { SheetsFilterPanelService } from '../../../services/sheets-filter-panel.service';
@@ -79,7 +79,7 @@ function createFilterOperationTestBed() {
[SheetInterceptorService],
[SheetsFilterPanelService],
[RefRangeService],
- [SelectionManagerService],
+ [SheetsSelectionsService],
] as Dependency[]).forEach((d) => injector.add(d));
}
}
diff --git a/packages/sheets-filter-ui/src/controllers/__tests__/sheets-filter.menu.spec.ts b/packages/sheets-filter-ui/src/controllers/__tests__/sheets-filter.menu.spec.ts
index 87e31e94f0..ac7802254c 100644
--- a/packages/sheets-filter-ui/src/controllers/__tests__/sheets-filter.menu.spec.ts
+++ b/packages/sheets-filter-ui/src/controllers/__tests__/sheets-filter.menu.spec.ts
@@ -14,9 +14,9 @@
* limitations under the License.
*/
-import type { IRange, IWorkbookData } from '@univerjs/core';
-import { AuthzIoLocalService, DisposableCollection, IAuthzIoService, ICommandService, LocaleType, Plugin, RANGE_TYPE, Univer, UniverInstanceType } from '@univerjs/core';
-import { NORMAL_SELECTION_PLUGIN_NAME, RangeProtectionRuleModel, RefRangeService, SelectionManagerService, SetWorksheetActiveOperation, SheetInterceptorService, WorkbookPermissionService, WorksheetPermissionService, WorksheetProtectionPointModel, WorksheetProtectionRuleModel } from '@univerjs/sheets';
+import type { IWorkbookData } from '@univerjs/core';
+import { AuthzIoLocalService, DisposableCollection, IAuthzIoService, ICommandService, LocaleType, Plugin, Univer, UniverInstanceType } from '@univerjs/core';
+import { RangeProtectionRuleModel, RefRangeService, SetWorksheetActiveOperation, SheetInterceptorService, SheetsSelectionsService, WorkbookPermissionService, WorksheetPermissionService, WorksheetProtectionPointModel, WorksheetProtectionRuleModel } from '@univerjs/sheets';
import type { ISetSheetsFilterCriteriaMutationParams, ISetSheetsFilterRangeMutationParams } from '@univerjs/sheets-filter';
import { RemoveSheetsFilterMutation, SetSheetsFilterCriteriaMutation, SetSheetsFilterRangeMutation, UniverSheetsFilterPlugin } from '@univerjs/sheets-filter';
import { IMenuService, IPlatformService, IShortcutService, MenuService, PlatformService, ShortcutService } from '@univerjs/ui';
@@ -63,7 +63,7 @@ function createSheetsFilterMenuTestBed() {
override onStarting(injector: Injector): void {
injector.add([IPlatformService, { useClass: PlatformService }]);
injector.add([RefRangeService]);
- injector.add([SelectionManagerService]);
+ injector.add([SheetsSelectionsService]);
injector.add([IShortcutService, { useClass: ShortcutService }]);
injector.add([IMenuService, { useClass: MenuService }]);
injector.add([WorksheetPermissionService]);
@@ -122,33 +122,6 @@ describe('test sheet filter menu items', () => {
disposableCollection.dispose();
});
- function select(range: IRange) {
- const selectionManager = get(SelectionManagerService);
- selectionManager.setCurrentSelection({
- pluginName: NORMAL_SELECTION_PLUGIN_NAME,
- unitId: 'test',
- sheetId: 'sheet1',
- });
-
- const { startColumn, startRow, endColumn, endRow } = range;
- selectionManager.add([
- {
- range: { startRow, startColumn, endColumn, endRow, rangeType: RANGE_TYPE.NORMAL },
- primary: {
- startRow,
- startColumn,
- endColumn,
- endRow,
- actualRow: startRow,
- actualColumn: startColumn,
- isMerged: false,
- isMergedMainCell: false,
- },
- style: null,
- },
- ]);
- }
-
it('should "SmartToggleSheetsFilterMenu" change status correctly', () => {
let activated = false;
diff --git a/packages/sheets-filter-ui/src/controllers/sheets-filter-mobile-ui.controller.ts b/packages/sheets-filter-ui/src/controllers/sheets-filter-mobile-ui.controller.ts
index f538d85b74..d99b116778 100644
--- a/packages/sheets-filter-ui/src/controllers/sheets-filter-mobile-ui.controller.ts
+++ b/packages/sheets-filter-ui/src/controllers/sheets-filter-mobile-ui.controller.ts
@@ -16,6 +16,7 @@
import { LifecycleStages, runOnLifecycle, RxDisposable, UniverInstanceType } from '@univerjs/core';
import { IRenderManagerService } from '@univerjs/engine-render';
+import type { Dependency } from '@wendellhu/redi';
import { SheetsFilterRenderController } from './sheets-filter-render.controller';
export class SheetsFilterMobileUIController extends RxDisposable {
@@ -28,7 +29,7 @@ export class SheetsFilterMobileUIController extends RxDisposable {
}
private _initRenderControllers(): void {
- this.disposeWithMe(this._renderManagerService.registerRenderModule(UniverInstanceType.UNIVER_SHEET, SheetsFilterRenderController));
+ this.disposeWithMe(this._renderManagerService.registerRenderModule(UniverInstanceType.UNIVER_SHEET, [SheetsFilterRenderController] as Dependency));
}
}
diff --git a/packages/sheets-filter-ui/src/controllers/sheets-filter-render.controller.ts b/packages/sheets-filter-ui/src/controllers/sheets-filter-render.controller.ts
index 77af222924..f0582d597b 100644
--- a/packages/sheets-filter-ui/src/controllers/sheets-filter-render.controller.ts
+++ b/packages/sheets-filter-ui/src/controllers/sheets-filter-render.controller.ts
@@ -22,11 +22,11 @@ import type { ISelectionStyle, ISheetCommandSharedParams } from '@univerjs/sheet
import { INTERCEPTOR_POINT, SheetInterceptorService } from '@univerjs/sheets';
import type { FilterModel } from '@univerjs/sheets-filter';
import { FILTER_MUTATIONS, ReCalcSheetsFilterMutation, RemoveSheetsFilterMutation, SetSheetsFilterCriteriaMutation, SetSheetsFilterRangeMutation, SheetsFilterService } from '@univerjs/sheets-filter';
-import { getCoordByCell, ISelectionRenderService, SelectionShape, SheetSkeletonManagerService, SheetsRenderService } from '@univerjs/sheets-ui';
+import { getCoordByCell, ISheetSelectionRenderService, SelectionShape, SheetSkeletonManagerService, SheetsRenderService } from '@univerjs/sheets-ui';
import type { IDisposable } from '@wendellhu/redi';
import { Inject, Injector } from '@wendellhu/redi';
-import { combineLatest, filter, map, of, startWith, switchMap, takeUntil, throttleTime } from 'rxjs';
+import { filter, map, of, startWith, switchMap, takeUntil, throttleTime } from 'rxjs';
import type { ISheetsFilterButtonShapeProps } from '../views/widgets/filter-button.shape';
import { FILTER_ICON_PADDING, FILTER_ICON_SIZE, SheetsFilterButtonShape } from '../views/widgets/filter-button.shape';
@@ -57,7 +57,7 @@ export class SheetsFilterRenderController extends RxDisposable implements IRende
@Inject(SheetsRenderService) private _sheetsRenderService: SheetsRenderService,
@ICommandService private readonly _commandService: ICommandService,
@IRenderManagerService private readonly _renderManagerService: IRenderManagerService,
- @ISelectionRenderService private readonly _selectionRenderService: ISelectionRenderService
+ @ISheetSelectionRenderService private readonly _selectionRenderService: ISheetSelectionRenderService
) {
super();
@@ -73,50 +73,44 @@ export class SheetsFilterRenderController extends RxDisposable implements IRende
private _initRenderer(): void {
// Subscribe to skeleton change and filter model change.
- combineLatest([
- this._selectionRenderService.usable$,
- this._sheetSkeletonManagerService.currentSkeleton$,
- ])
- .pipe(
- filter(([usable]) => usable),
- switchMap(([_, skeletonParams]) => {
- if (!skeletonParams) return of(null);
-
- const { unit: workbook, unitId } = this._context;
- const worksheetId = workbook.getActiveSheet()?.getSheetId() || '';
- const filterModel = this._sheetsFilterService.getFilterModel(unitId, worksheetId) ?? undefined;
- const getParams = (): ISheetsFilterRenderParams => ({
- unitId,
- worksheetId,
- filterModel,
- range: filterModel?.getRange(),
- skeleton: skeletonParams.skeleton,
- });
-
- return fromCallback(this._commandService.onCommandExecuted.bind(this._commandService)).pipe(
- filter(([command]) =>
- command.type === CommandType.MUTATION
- && (command.params as ISheetCommandSharedParams).unitId === workbook.getUnitId()
- && FILTER_MUTATIONS.has(command.id)
- ),
- throttleTime(20, undefined, { leading: false, trailing: true }),
- map(getParams),
- startWith(getParams()) // must trigger once
- );
- }),
- takeUntil(this.dispose$)
- )
- .subscribe((renderParams) => {
- this._disposeRendering();
-
- // If there's no filter range, we don't need to render anything.
- if (!renderParams || !renderParams.range) {
- return;
- }
+ this._sheetSkeletonManagerService.currentSkeleton$.pipe(
+ switchMap((skeletonParams) => {
+ if (!skeletonParams) return of(null);
+
+ const { unit: workbook, unitId } = this._context;
+ const worksheetId = workbook.getActiveSheet()?.getSheetId() || '';
+ const filterModel = this._sheetsFilterService.getFilterModel(unitId, worksheetId) ?? undefined;
+ const getParams = (): ISheetsFilterRenderParams => ({
+ unitId,
+ worksheetId,
+ filterModel,
+ range: filterModel?.getRange(),
+ skeleton: skeletonParams.skeleton,
+ });
- this._renderRange(renderParams.unitId, renderParams.range, renderParams.skeleton);
- this._renderButtons(renderParams as Required<ISheetsFilterRenderParams>);
- });
+ return fromCallback(this._commandService.onCommandExecuted.bind(this._commandService)).pipe(
+ filter(([command]) =>
+ command.type === CommandType.MUTATION
+ && (command.params as ISheetCommandSharedParams).unitId === workbook.getUnitId()
+ && FILTER_MUTATIONS.has(command.id)
+ ),
+ throttleTime(20, undefined, { leading: false, trailing: true }),
+ map(getParams),
+ startWith(getParams()) // must trigger once
+ );
+ }),
+ takeUntil(this.dispose$)
+ ).subscribe((renderParams) => {
+ this._disposeRendering();
+
+ // If there's no filter range, we don't need to render anything.
+ if (!renderParams || !renderParams.range) {
+ return;
+ }
+
+ this._renderRange(renderParams.unitId, renderParams.range, renderParams.skeleton);
+ this._renderButtons(renderParams as Required<ISheetsFilterRenderParams>);
+ });
}
private _renderRange(unitId: string, range: IRange, skeleton: SpreadsheetSkeleton): void {
diff --git a/packages/sheets-filter-ui/src/controllers/sheets-filter-ui.controller.ts b/packages/sheets-filter-ui/src/controllers/sheets-filter-ui.controller.ts
index b1b24329bd..0b53933e4e 100644
--- a/packages/sheets-filter-ui/src/controllers/sheets-filter-ui.controller.ts
+++ b/packages/sheets-filter-ui/src/controllers/sheets-filter-ui.controller.ts
@@ -47,7 +47,7 @@ export const FILTER_PANEL_POPUP_KEY = 'FILTER_PANEL_POPUP';
/**
* This controller controls the UI of "filter" features. Menus, commands and filter panel etc. Except for the rendering.
*/
-@OnLifecycle(LifecycleStages.Ready, SheetsFilterUIController)
+@OnLifecycle(LifecycleStages.Rendered, SheetsFilterUIController)
export class SheetsFilterUIController extends SheetsFilterMobileUIController {
constructor(
private readonly _config: Partial<IUniverSheetsFilterUIConfig>,
diff --git a/packages/sheets-filter-ui/src/services/__tests__/sheets-filter-panel.service.spec.ts b/packages/sheets-filter-ui/src/services/__tests__/sheets-filter-panel.service.spec.ts
index 9c37beb71a..62cae92c5b 100644
--- a/packages/sheets-filter-ui/src/services/__tests__/sheets-filter-panel.service.spec.ts
+++ b/packages/sheets-filter-ui/src/services/__tests__/sheets-filter-panel.service.spec.ts
@@ -16,7 +16,7 @@
import type { IOperation, IWorkbookData } from '@univerjs/core';
import { CommandType, ICommandService, LocaleService, Plugin, Univer, UniverInstanceType } from '@univerjs/core';
-import { RefRangeService, SelectionManagerService, SheetInterceptorService } from '@univerjs/sheets';
+import { RefRangeService, SheetInterceptorService, SheetsSelectionsService } from '@univerjs/sheets';
import type { Dependency } from '@wendellhu/redi';
import { Inject, Injector } from '@wendellhu/redi';
import { afterEach, beforeEach, describe, expect, it, vitest } from 'vitest';
@@ -55,7 +55,7 @@ function createSheetsFilterPanelServiceTestBed(workbookData: IWorkbookData) {
override onStarting(injector: Injector): void {
([
[RefRangeService],
- [SelectionManagerService],
+ [SheetsSelectionsService],
[SheetInterceptorService],
[SheetsFilterPanelService],
] as Dependency[]).forEach((d) => injector.add(d));
diff --git a/packages/sheets-filter-ui/src/views/components/SheetsFilterPanel.stories.tsx b/packages/sheets-filter-ui/src/views/components/SheetsFilterPanel.stories.tsx
index d46a6b682c..4a9f99ef28 100644
--- a/packages/sheets-filter-ui/src/views/components/SheetsFilterPanel.stories.tsx
+++ b/packages/sheets-filter-ui/src/views/components/SheetsFilterPanel.stories.tsx
@@ -21,7 +21,7 @@ import type { Injector } from '@wendellhu/redi';
import { UniverSheetsFilterPlugin } from '@univerjs/sheets-filter';
import type { IWorkbookData } from '@univerjs/core';
import { CommandType, ICommandService, ILogService, LocaleService, LocaleType, LogLevel, Plugin, Univer, UniverInstanceType } from '@univerjs/core';
-import { RefRangeService, SelectionManagerService, SheetInterceptorService, WorksheetProtectionPointModel } from '@univerjs/sheets';
+import { RefRangeService, SheetInterceptorService, SheetsSelectionsService, WorksheetProtectionPointModel } from '@univerjs/sheets';
import { IMenuService, IShortcutService, MenuService, ShortcutService } from '@univerjs/ui';
import { SetCellEditVisibleOperation } from '@univerjs/sheets-ui';
import { SheetsFilterPanelService } from '../../services/sheets-filter-panel.service';
@@ -61,7 +61,7 @@ function createFilterStorybookBed(workbookData: IWorkbookData, locale: LocaleTyp
}
override onStarting(injector: Injector): void {
- injector.add([SelectionManagerService]);
+ injector.add([SheetsSelectionsService]);
injector.add([IShortcutService, { useClass: ShortcutService }]);
injector.add([IMenuService, { useClass: MenuService }]);
injector.add([WorksheetProtectionPointModel]);
diff --git a/packages/sheets-filter/src/models/__tests__/filter-interceptor.spec.ts b/packages/sheets-filter/src/models/__tests__/filter-interceptor.spec.ts
index 1a9a255c5f..93d99c79ed 100644
--- a/packages/sheets-filter/src/models/__tests__/filter-interceptor.spec.ts
+++ b/packages/sheets-filter/src/models/__tests__/filter-interceptor.spec.ts
@@ -21,20 +21,18 @@ import type { Dependency } from '@wendellhu/redi';
import { Inject, Injector } from '@wendellhu/redi';
import type { IInsertColCommandParams, IInsertRowCommandParams, IMoveColsCommandParams, IMoveRowsCommandParams, IRemoveRowColCommandParams, IRemoveSheetCommandParams, ISetSelectionsOperationParams } from '@univerjs/sheets';
-import { InsertColCommand, InsertColMutation, InsertRowCommand, InsertRowMutation, MoveColsCommand, MoveColsMutation, MoveRowsCommand, MoveRowsMutation, NORMAL_SELECTION_PLUGIN_NAME, RefRangeService, RemoveColCommand, RemoveColMutation, RemoveRowCommand, RemoveRowMutation, RemoveSheetCommand, RemoveSheetMutation, SelectionManagerService, SetSelectionsOperation, SheetInterceptorService } from '@univerjs/sheets';
+import { InsertColCommand, InsertColMutation, InsertRowCommand, InsertRowMutation, MoveColsCommand, MoveColsMutation, MoveRowsCommand, MoveRowsMutation, RefRangeService, RemoveColCommand, RemoveColMutation, RemoveRowCommand, RemoveRowMutation, RemoveSheetCommand, RemoveSheetMutation, SetSelectionsOperation, SheetInterceptorService, SheetsSelectionsService } from '@univerjs/sheets';
import { SHEET_FILTER_SNAPSHOT_ID, SheetsFilterService } from '../../services/sheet-filter.service';
import { SheetsFilterController } from '../../controllers/sheets-filter.controller';
describe('Test "Filter Interceptor"', () => {
let univer: Univer;
- let get: Injector['get'];
let sheetsFilterService: SheetsFilterService;
let commandService: ICommandService;
beforeEach(() => {
const testBed = createFilterTestUniver();
univer = testBed.univer;
- get = testBed.get;
sheetsFilterService = testBed.sheetsFilterService;
commandService = testBed.commandService;
univer.__getInjector();
@@ -46,32 +44,44 @@ describe('Test "Filter Interceptor"', () => {
describe('Test "insert Command"', () => {
it('insert col command, in filter range', async () => {
- const insertColCommandParams = { unitId: 'workbookId', subUnitId: 'worksheetId', range: { startColumn: 2, endColumn: 2, startRow: 0, endRow: 4, type: RANGE_TYPE.COLUMN,
- }, direction: Direction.RIGHT } as IInsertColCommandParams;
+ const insertColCommandParams = {
+ unitId: 'workbookId', subUnitId: 'worksheetId', range: {
+ startColumn: 2, endColumn: 2, startRow: 0, endRow: 4, type: RANGE_TYPE.COLUMN,
+ }, direction: Direction.RIGHT,
+ } as IInsertColCommandParams;
await commandService.executeCommand(InsertColCommand.id, insertColCommandParams);
expect(sheetsFilterService.getFilterModel('workbookId', 'worksheetId')!.getRange()).toStrictEqual({ startColumn: 1, endColumn: 3, startRow: 1, endRow: 2 });
expect(sheetsFilterService.getFilterModel('workbookId', 'worksheetId')!.getAllFilterColumns().map((x) => x[0])).toStrictEqual([3]);
});
it('insert col command, before filter range', async () => {
- const insertColCommandParams = { unitId: 'workbookId', subUnitId: 'worksheetId', range: { startColumn: 0, endColumn: 0, startRow: 0, endRow: 4, type: RANGE_TYPE.COLUMN,
- }, direction: Direction.RIGHT } as IInsertColCommandParams;
+ const insertColCommandParams = {
+ unitId: 'workbookId', subUnitId: 'worksheetId', range: {
+ startColumn: 0, endColumn: 0, startRow: 0, endRow: 4, type: RANGE_TYPE.COLUMN,
+ }, direction: Direction.RIGHT,
+ } as IInsertColCommandParams;
await commandService.executeCommand(InsertColCommand.id, insertColCommandParams);
expect(sheetsFilterService.getFilterModel('workbookId', 'worksheetId')!.getRange()).toStrictEqual({ startColumn: 2, endColumn: 3, startRow: 1, endRow: 2 });
expect(sheetsFilterService.getFilterModel('workbookId', 'worksheetId')!.getAllFilterColumns().map((x) => x[0])).toStrictEqual([3]);
});
it('insert row command, in filter range', async () => {
- const insertRowCommandParams = { unitId: 'workbookId', subUnitId: 'worksheetId', range: { startColumn: 0, endColumn: 3, startRow: 2, endRow: 2, type: RANGE_TYPE.ROW,
- }, direction: Direction.DOWN } as IInsertRowCommandParams;
+ const insertRowCommandParams = {
+ unitId: 'workbookId', subUnitId: 'worksheetId', range: {
+ startColumn: 0, endColumn: 3, startRow: 2, endRow: 2, type: RANGE_TYPE.ROW,
+ }, direction: Direction.DOWN,
+ } as IInsertRowCommandParams;
await commandService.executeCommand(InsertRowCommand.id, insertRowCommandParams);
expect(sheetsFilterService.getFilterModel('workbookId', 'worksheetId')!.getRange()).toStrictEqual({ startColumn: 1, endColumn: 2, startRow: 1, endRow: 3 });
expect(sheetsFilterService.getFilterModel('workbookId', 'worksheetId')!.getAllFilterColumns().map((x) => x[0])).toStrictEqual([2]);
});
it('insert row command, before filter range', async () => {
- const insertRowCommandParams = { unitId: 'workbookId', subUnitId: 'worksheetId', range: { startColumn: 0, endColumn: 3, startRow: 0, endRow: 0, type: RANGE_TYPE.ROW,
- }, direction: Direction.DOWN } as IInsertRowCommandParams;
+ const insertRowCommandParams = {
+ unitId: 'workbookId', subUnitId: 'worksheetId', range: {
+ startColumn: 0, endColumn: 3, startRow: 0, endRow: 0, type: RANGE_TYPE.ROW,
+ }, direction: Direction.DOWN,
+ } as IInsertRowCommandParams;
await commandService.executeCommand(InsertRowCommand.id, insertRowCommandParams);
expect(sheetsFilterService.getFilterModel('workbookId', 'worksheetId')!.getRange()).toStrictEqual({ startColumn: 1, endColumn: 2, startRow: 2, endRow: 3 });
expect(sheetsFilterService.getFilterModel('workbookId', 'worksheetId')!.getAllFilterColumns().map((x) => x[0])).toStrictEqual([2]);
@@ -80,30 +90,42 @@ describe('Test "Filter Interceptor"', () => {
describe('Test "remove Command"', () => {
it('remove col command, in filter range', async () => {
- const removeColCommandParams = { unitId: 'workbookId', subUnitId: 'worksheetId', range: { startColumn: 1, endColumn: 1, startRow: 0, endRow: 4, type: RANGE_TYPE.COLUMN,
- }, direction: Direction.RIGHT } as IRemoveRowColCommandParams;
+ const removeColCommandParams = {
+ unitId: 'workbookId', subUnitId: 'worksheetId', range: {
+ startColumn: 1, endColumn: 1, startRow: 0, endRow: 4, type: RANGE_TYPE.COLUMN,
+ }, direction: Direction.RIGHT,
+ } as IRemoveRowColCommandParams;
await commandService.executeCommand(RemoveColCommand.id, removeColCommandParams);
expect(sheetsFilterService.getFilterModel('workbookId', 'worksheetId')!.getRange()).toStrictEqual({ startColumn: 1, endColumn: 1, startRow: 1, endRow: 2 });
expect(sheetsFilterService.getFilterModel('workbookId', 'worksheetId')!.getAllFilterColumns().map((x) => x[0])).toStrictEqual([1]);
});
it('remove col command, before filter range', async () => {
- const removeColCommandParams = { unitId: 'workbookId', subUnitId: 'worksheetId', range: { startColumn: 0, endColumn: 0, startRow: 0, endRow: 4, type: RANGE_TYPE.COLUMN,
- }, direction: Direction.RIGHT } as IRemoveRowColCommandParams;
+ const removeColCommandParams = {
+ unitId: 'workbookId', subUnitId: 'worksheetId', range: {
+ startColumn: 0, endColumn: 0, startRow: 0, endRow: 4, type: RANGE_TYPE.COLUMN,
+ }, direction: Direction.RIGHT,
+ } as IRemoveRowColCommandParams;
await commandService.executeCommand(RemoveColCommand.id, removeColCommandParams);
expect(sheetsFilterService.getFilterModel('workbookId', 'worksheetId')!.getRange()).toStrictEqual({ startColumn: 0, endColumn: 1, startRow: 1, endRow: 2 });
expect(sheetsFilterService.getFilterModel('workbookId', 'worksheetId')!.getAllFilterColumns().map((x) => x[0])).toStrictEqual([1]);
});
it('remove row command, in filter range', async () => {
- const removeRowCommandParams = { unitId: 'workbookId', subUnitId: 'worksheetId', range: { startColumn: 0, endColumn: 3, startRow: 1, endRow: 1, type: RANGE_TYPE.ROW,
- }, direction: Direction.DOWN } as IRemoveRowColCommandParams;
+ const removeRowCommandParams = {
+ unitId: 'workbookId', subUnitId: 'worksheetId', range: {
+ startColumn: 0, endColumn: 3, startRow: 1, endRow: 1, type: RANGE_TYPE.ROW,
+ }, direction: Direction.DOWN,
+ } as IRemoveRowColCommandParams;
await commandService.executeCommand(RemoveRowCommand.id, removeRowCommandParams);
expect(sheetsFilterService.getFilterModel('workbookId', 'worksheetId')).toBe(null);
});
it('remove row command, before filter range', async () => {
- const removeRowCommandParams = { unitId: 'workbookId', subUnitId: 'worksheetId', range: { startColumn: 0, endColumn: 3, startRow: 0, endRow: 0, type: RANGE_TYPE.ROW,
- }, direction: Direction.DOWN } as IRemoveRowColCommandParams;
+ const removeRowCommandParams = {
+ unitId: 'workbookId', subUnitId: 'worksheetId', range: {
+ startColumn: 0, endColumn: 3, startRow: 0, endRow: 0, type: RANGE_TYPE.ROW,
+ }, direction: Direction.DOWN,
+ } as IRemoveRowColCommandParams;
await commandService.executeCommand(RemoveRowCommand.id, removeRowCommandParams);
expect(sheetsFilterService.getFilterModel('workbookId', 'worksheetId')!.getRange()).toStrictEqual({ startColumn: 1, endColumn: 2, startRow: 0, endRow: 1 });
expect(sheetsFilterService.getFilterModel('workbookId', 'worksheetId')!.getAllFilterColumns().map((x) => x[0])).toStrictEqual([2]);
@@ -112,32 +134,35 @@ describe('Test "Filter Interceptor"', () => {
describe('Test "move Command"', () => {
it('move col command, filter column move to left', async () => {
- const moveColCommandParams = { unitId: 'workbookId', subUnitId: 'worksheetId', fromRange: { startColumn: 1, endColumn: 1, startRow: 0, endRow: 4, type: RANGE_TYPE.COLUMN,
- }, toRange: { startColumn: 3, endColumn: 3, startRow: 0, endRow: 4, type: RANGE_TYPE.COLUMN }, direction: Direction.RIGHT } as IMoveColsCommandParams;
- const selectionManagerService = get(SelectionManagerService);
- selectionManagerService.setCurrentSelection({ unitId: 'workbookId', sheetId: 'worksheetId', pluginName: NORMAL_SELECTION_PLUGIN_NAME });
- await commandService.executeCommand(SetSelectionsOperation.id, { unitId: 'workbookId', subUnitId: 'worksheetId', pluginName: NORMAL_SELECTION_PLUGIN_NAME, selections: [{ style: null, range: { startColumn: 1, endColumn: 1, startRow: 0, endRow: 4, rangeType: RANGE_TYPE.COLUMN }, primary: {} }] } as ISetSelectionsOperationParams);
+ const moveColCommandParams = {
+ unitId: 'workbookId', subUnitId: 'worksheetId', fromRange: {
+ startColumn: 1, endColumn: 1, startRow: 0, endRow: 4, type: RANGE_TYPE.COLUMN,
+ }, toRange: { startColumn: 3, endColumn: 3, startRow: 0, endRow: 4, type: RANGE_TYPE.COLUMN }, direction: Direction.RIGHT,
+ } as IMoveColsCommandParams;
+ await commandService.executeCommand(SetSelectionsOperation.id, { unitId: 'workbookId', subUnitId: 'worksheetId', selections: [{ style: null, range: { startColumn: 1, endColumn: 1, startRow: 0, endRow: 4, rangeType: RANGE_TYPE.COLUMN }, primary: {} }] } as ISetSelectionsOperationParams);
await commandService.executeCommand(MoveColsCommand.id, moveColCommandParams);
expect(sheetsFilterService.getFilterModel('workbookId', 'worksheetId')!.getRange()).toStrictEqual({ startColumn: 1, endColumn: 1, startRow: 1, endRow: 2 });
expect(sheetsFilterService.getFilterModel('workbookId', 'worksheetId')!.getAllFilterColumns().map((x) => x[0])).toStrictEqual([1]);
});
it('move col command, filter column move to right', async () => {
- const moveColCommandParams = { unitId: 'workbookId', subUnitId: 'worksheetId', fromRange: { startColumn: 2, endColumn: 2, startRow: 0, endRow: 4, type: RANGE_TYPE.COLUMN,
- }, toRange: { startColumn: 4, endColumn: 4, startRow: 0, endRow: 4, type: RANGE_TYPE.COLUMN }, direction: Direction.RIGHT } as IMoveColsCommandParams;
- const selectionManagerService = get(SelectionManagerService);
- selectionManagerService.setCurrentSelection({ unitId: 'workbookId', sheetId: 'worksheetId', pluginName: NORMAL_SELECTION_PLUGIN_NAME });
- await commandService.executeCommand(SetSelectionsOperation.id, { unitId: 'workbookId', subUnitId: 'worksheetId', pluginName: NORMAL_SELECTION_PLUGIN_NAME, selections: [{ style: null, range: { startColumn: 2, endColumn: 2, startRow: 0, endRow: 4, rangeType: RANGE_TYPE.COLUMN }, primary: {} }] } as ISetSelectionsOperationParams);
+ const moveColCommandParams = {
+ unitId: 'workbookId', subUnitId: 'worksheetId', fromRange: {
+ startColumn: 2, endColumn: 2, startRow: 0, endRow: 4, type: RANGE_TYPE.COLUMN,
+ }, toRange: { startColumn: 4, endColumn: 4, startRow: 0, endRow: 4, type: RANGE_TYPE.COLUMN }, direction: Direction.RIGHT,
+ } as IMoveColsCommandParams;
+ await commandService.executeCommand(SetSelectionsOperation.id, { unitId: 'workbookId', subUnitId: 'worksheetId', selections: [{ style: null, range: { startColumn: 2, endColumn: 2, startRow: 0, endRow: 4, rangeType: RANGE_TYPE.COLUMN }, primary: {} }] } as ISetSelectionsOperationParams);
await commandService.executeCommand(MoveColsCommand.id, moveColCommandParams);
expect(sheetsFilterService.getFilterModel('workbookId', 'worksheetId')!.getRange()).toStrictEqual({ startColumn: 1, endColumn: 3, startRow: 1, endRow: 2 });
expect(sheetsFilterService.getFilterModel('workbookId', 'worksheetId')!.getAllFilterColumns().map((x) => x[0])).toStrictEqual([3]);
});
it('move row command', async () => {
- const moveRowCommandParams = { unitId: 'workbookId', subUnitId: 'worksheetId', fromRange: { startColumn: 0, endColumn: 3, startRow: 2, endRow: 2, type: RANGE_TYPE.ROW,
- }, toRange: { startColumn: 0, endColumn: 3, startRow: 4, endRow: 4, type: RANGE_TYPE.ROW }, direction: Direction.RIGHT } as IMoveRowsCommandParams;
- const selectionManagerService = get(SelectionManagerService);
- selectionManagerService.setCurrentSelection({ unitId: 'workbookId', sheetId: 'worksheetId', pluginName: NORMAL_SELECTION_PLUGIN_NAME });
- await commandService.executeCommand(SetSelectionsOperation.id, { unitId: 'workbookId', subUnitId: 'worksheetId', pluginName: NORMAL_SELECTION_PLUGIN_NAME, selections: [{ style: null, range: { startColumn: 0, endColumn: 3, startRow: 2, endRow: 2, rangeType: RANGE_TYPE.ROW }, primary: {} }] } as ISetSelectionsOperationParams);
+ const moveRowCommandParams = {
+ unitId: 'workbookId', subUnitId: 'worksheetId', fromRange: {
+ startColumn: 0, endColumn: 3, startRow: 2, endRow: 2, type: RANGE_TYPE.ROW,
+ }, toRange: { startColumn: 0, endColumn: 3, startRow: 4, endRow: 4, type: RANGE_TYPE.ROW }, direction: Direction.RIGHT,
+ } as IMoveRowsCommandParams;
+ await commandService.executeCommand(SetSelectionsOperation.id, { unitId: 'workbookId', subUnitId: 'worksheetId', selections: [{ style: null, range: { startColumn: 0, endColumn: 3, startRow: 2, endRow: 2, rangeType: RANGE_TYPE.ROW }, primary: {} }] } as ISetSelectionsOperationParams);
await commandService.executeCommand(MoveRowsCommand.id, moveRowCommandParams);
expect(sheetsFilterService.getFilterModel('workbookId', 'worksheetId')!.getRange()).toStrictEqual({ startColumn: 1, endColumn: 2, startRow: 1, endRow: 3 });
expect(sheetsFilterService.getFilterModel('workbookId', 'worksheetId')!.getAllFilterColumns().map((x) => x[0])).toStrictEqual([2]);
@@ -147,8 +172,8 @@ describe('Test "Filter Interceptor"', () => {
describe('Test "remove sheet Command"', () => {
it('remove sheet command', async () => {
const removeSheetCommandParams = { unitId: 'workbookId', subUnitId: 'worksheetId' } as IRemoveSheetCommandParams;
- await commandService.executeCommand(RemoveSheetCommand.id, removeSheetCommandParams);
- expect(sheetsFilterService.getFilterModel('workbookId', 'worksheetId')).toBe(null);
+ expect(await commandService.executeCommand(RemoveSheetCommand.id, removeSheetCommandParams)).toBeTruthy();
+ expect(sheetsFilterService.getFilterModel('workbookId', 'worksheetId') === null).toBeTruthy();
});
});
});
@@ -178,7 +203,7 @@ function createFilterTestUniver(dependencies?: Dependency[], workbookData?: IWor
injector.add([SheetInterceptorService]);
injector.add([SheetsFilterService]);
- injector.add([SelectionManagerService]);
+ injector.add([SheetsSelectionsService]);
injector.add([RefRangeService]);
injector.add([SheetsFilterController]);
}
diff --git a/packages/sheets-filter/src/models/__tests__/filter-model.spec.ts b/packages/sheets-filter/src/models/__tests__/filter-model.spec.ts
index c0a9648c45..7e299e97f6 100644
--- a/packages/sheets-filter/src/models/__tests__/filter-model.spec.ts
+++ b/packages/sheets-filter/src/models/__tests__/filter-model.spec.ts
@@ -216,49 +216,6 @@ describe('Test filter model and related utils', () => {
expect(filterColumn.filteredOutRows!.size).toBe(1);
});
});
-
- describe('Test "FilterModel"', () => {
- let univer: Univer;
- let filterColumn: FilterColumn;
- let get: Injector['get'];
-
- beforeEach(() => {
- const testBed = createFilterModelTestBed({
- id: 'test',
- appVersion: '3.0.0-alpha',
- sheets: {
- sheet1: {
- id: 'sheet1',
- name: 'sheet1',
- cellData: {
- 0: {
- 1: { v: 'header' },
- },
- 1: {
- 1: { v: 123 },
- },
- 2: {
- 1: { v: 345 },
- },
- },
- },
- },
- locale: LocaleType.ZH_CN,
- name: '',
- sheetOrder: [],
- styles: {},
- });
-
- univer = testBed.univer;
- get = testBed.get;
- });
-
- // TODO@wzhudev: not implemented yet
- // describe('Test serialization and deserialization', () => {
- // it('should serialize return a correct object', () => { });
- // it('should deserialize return a correct instance', () => { });
- // });
- });
});
function createFilterModelTestBed(workbookData: IWorkbookData) {
diff --git a/packages/sheets-filter/src/services/sheet-filter.service.ts b/packages/sheets-filter/src/services/sheet-filter.service.ts
index ebe9071701..044ef07e3c 100644
--- a/packages/sheets-filter/src/services/sheet-filter.service.ts
+++ b/packages/sheets-filter/src/services/sheet-filter.service.ts
@@ -15,7 +15,8 @@
*/
import type { Nullable, Workbook } from '@univerjs/core';
-import { CommandType, Disposable,
+import {
+ CommandType, Disposable,
fromCallback,
ICommandService,
IResourceManagerService,
@@ -71,7 +72,8 @@ export class SheetsFilterService extends Disposable {
constructor(
@IResourceManagerService private readonly _resourcesManagerService: IResourceManagerService,
@IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService,
- @ICommandService private readonly _commandService: ICommandService) {
+ @ICommandService private readonly _commandService: ICommandService
+ ) {
super();
this._initModel();
@@ -136,7 +138,7 @@ export class SheetsFilterService extends Disposable {
}
// Use getActiveSheet to avoid automatically activating the next sheet when deleting the sheet, causing the sheet switching in ActiveWorksheetController to be invalid.
- const activeSheet = workbook.getActiveSheet();
+ const activeSheet = workbook.getActiveSheet(true);
if (!activeSheet) {
this._activeFilterModel$.next(null);
return;
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
index 851e99380c..61b8022895 100644
--- a/packages/sheets-find-replace/src/controllers/sheet-find-replace.controller.ts
+++ b/packages/sheets-find-replace/src/controllers/sheet-find-replace.controller.ts
@@ -20,7 +20,7 @@ import { IRenderManagerService, RENDER_RAW_FORMULA_KEY } from '@univerjs/engine-
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 { SetRangeValuesCommand, SetSelectionsOperation, SetWorksheetActivateCommand, SetWorksheetActiveOperation, SheetsSelectionsService } 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';
@@ -126,7 +126,7 @@ export class SheetFindModel extends FindModel {
@ICommandService private readonly _commandService: ICommandService,
@IContextService private readonly _contextService: IContextService,
@Inject(ThemeService) private readonly _themeService: ThemeService,
- @Inject(SelectionManagerService) private readonly _selectionManagerService: SelectionManagerService
+ @Inject(SheetsSelectionsService) private readonly _selectionManagerService: SheetsSelectionsService
) {
super();
}
@@ -256,7 +256,7 @@ export class SheetFindModel extends FindModel {
let globalIndex = 0;
const matchesByWorksheet = this._matchesByWorksheet.get(activeSheet.getSheetId())!;
- const selections = this._selectionManagerService.getSelections();
+ const selections = this._selectionManagerService.getCurrentSelections();
if (!selections?.length) {
match = matchesByWorksheet[0];
index = 0;
@@ -285,7 +285,7 @@ export class SheetFindModel extends FindModel {
const checkShouldFindInSelections = (): boolean => {
const currentWorksheet = this._workbook.getActiveSheet();
if (!currentWorksheet) return false;
- const currentSelections = this._selectionManagerService.getSelections();
+ const currentSelections = this._selectionManagerService.getCurrentSelections();
const shouldFindInSelections = currentSelections?.some((selection) => !isSelectionSingleCell(selection, currentWorksheet)) ?? false;
return shouldFindInSelections;
};
@@ -301,7 +301,7 @@ export class SheetFindModel extends FindModel {
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 currentSelections = this._selectionManagerService.getCurrentSelections();
const newComplete = findBySelections
? this._findInSelections(currentWorksheet, currentSelections as ISelectionWithStyle[], query, unitId)
: this._findInWorksheet(currentWorksheet, query, unitId);
@@ -662,7 +662,7 @@ export class SheetFindModel extends FindModel {
// 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();
+ const selections = this._selectionManagerService.getCurrentSelections();
if (!selections?.length) {
return [this._matches[0], 0];
}
@@ -705,7 +705,7 @@ export class SheetFindModel extends FindModel {
// 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();
+ const selections = this._selectionManagerService.getCurrentSelections();
if (!selections?.length) {
return [this._matches[0], 0];
}
diff --git a/packages/sheets-formula/src/commands/operations/__tests__/create-command-test-bed.ts b/packages/sheets-formula/src/commands/operations/__tests__/create-command-test-bed.ts
index 0d989b19df..3712830397 100644
--- a/packages/sheets-formula/src/commands/operations/__tests__/create-command-test-bed.ts
+++ b/packages/sheets-formula/src/commands/operations/__tests__/create-command-test-bed.ts
@@ -17,12 +17,12 @@
import type { IWorkbookData } from '@univerjs/core';
import { AuthzIoLocalService, IAuthzIoService, ILogService, IUniverInstanceService, LocaleType, LogLevel, Plugin, Univer, UniverInstanceType } from '@univerjs/core';
import { LexerTreeBuilder } from '@univerjs/engine-formula';
-import { RangeProtectionRuleModel, SelectionManagerService, SheetInterceptorService, WorkbookPermissionService, WorksheetPermissionService, WorksheetProtectionPointModel, WorksheetProtectionRuleModel } from '@univerjs/sheets';
+import { RangeProtectionRuleModel, SheetInterceptorService, SheetsSelectionsService, WorkbookPermissionService, WorksheetPermissionService, WorksheetProtectionPointModel, WorksheetProtectionRuleModel } from '@univerjs/sheets';
import type { Dependency } from '@wendellhu/redi';
import { Inject, Injector } from '@wendellhu/redi';
import { EditorService, IEditorService } from '@univerjs/ui';
import { IRenderManagerService, RenderManagerService } from '@univerjs/engine-render';
-import { EditorBridgeService, IEditorBridgeService, ISelectionRenderService, SelectionRenderService, SheetSkeletonManagerService } from '@univerjs/sheets-ui';
+import { EditorBridgeService, IEditorBridgeService, ISheetSelectionRenderService, SheetSelectionRenderService, SheetSkeletonManagerService } from '@univerjs/sheets-ui';
import { FormulaPromptService, IFormulaPromptService } from '../../../services/prompt.service';
const TEST_WORKBOOK_DATA_DEMO = (): IWorkbookData => ({
@@ -68,8 +68,8 @@ export function createCommandTestBed(workbookData?: IWorkbookData, dependencies?
}
override onStarting(injector: Injector): void {
- injector.add([ISelectionRenderService, { useClass: SelectionRenderService }]);
- injector.add([SelectionManagerService]);
+ injector.add([ISheetSelectionRenderService, { useClass: SheetSelectionRenderService }]);
+ injector.add([SheetsSelectionsService]);
injector.add([LexerTreeBuilder]);
injector.add([IFormulaPromptService, { useClass: FormulaPromptService }]);
injector.add([IEditorBridgeService, { useClass: EditorBridgeService }]);
diff --git a/packages/sheets-formula/src/commands/operations/__tests__/insert-function.operation.spec.ts b/packages/sheets-formula/src/commands/operations/__tests__/insert-function.operation.spec.ts
index a24b3575e6..99923df681 100644
--- a/packages/sheets-formula/src/commands/operations/__tests__/insert-function.operation.spec.ts
+++ b/packages/sheets-formula/src/commands/operations/__tests__/insert-function.operation.spec.ts
@@ -17,11 +17,10 @@
import type { Univer } from '@univerjs/core';
import { ICommandService, IUniverInstanceService, RANGE_TYPE, RedoCommand, UndoCommand } from '@univerjs/core';
import {
- NORMAL_SELECTION_PLUGIN_NAME,
- SelectionManagerService,
SetRangeValuesCommand,
SetRangeValuesMutation,
SetSelectionsOperation,
+ SheetsSelectionsService,
} from '@univerjs/sheets';
import type { Injector } from '@wendellhu/redi';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
@@ -61,14 +60,10 @@ describe('Test insert function operation', () => {
describe('insert function', () => {
describe('correct situations', () => {
it('insert function, match the data range above, directly set values', async () => {
- const selectionManager = get(SelectionManagerService);
- selectionManager.setCurrentSelection({
- pluginName: NORMAL_SELECTION_PLUGIN_NAME,
- unitId: 'test',
- sheetId: 'sheet1',
- });
+ const selectionManager = get(SheetsSelectionsService);
+
// B3:B4
- selectionManager.add([
+ selectionManager.addSelections([
{
range: { startRow: 2, startColumn: 1, endRow: 3, endColumn: 1, rangeType: RANGE_TYPE.NORMAL },
primary: null,
@@ -102,14 +97,10 @@ describe('Test insert function operation', () => {
});
it('insert function, match the data range left, directly set values', async () => {
- const selectionManager = get(SelectionManagerService);
- selectionManager.setCurrentSelection({
- pluginName: NORMAL_SELECTION_PLUGIN_NAME,
- unitId: 'test',
- sheetId: 'sheet1',
- });
+ const selectionManager = get(SheetsSelectionsService);
+
// C2:D2
- selectionManager.add([
+ selectionManager.addSelections([
{
range: { startRow: 1, startColumn: 2, endRow: 1, endColumn: 3, rangeType: RANGE_TYPE.NORMAL },
primary: null,
diff --git a/packages/sheets-formula/src/commands/operations/insert-function.operation.ts b/packages/sheets-formula/src/commands/operations/insert-function.operation.ts
index 1e2d945dc1..0eab450974 100644
--- a/packages/sheets-formula/src/commands/operations/insert-function.operation.ts
+++ b/packages/sheets-formula/src/commands/operations/insert-function.operation.ts
@@ -29,9 +29,8 @@ import { serializeRange } from '@univerjs/engine-formula';
import {
getCellAtRowCol,
getSheetCommandTarget,
- NORMAL_SELECTION_PLUGIN_NAME,
- SelectionManagerService,
SetSelectionsOperation,
+ SheetsSelectionsService,
} from '@univerjs/sheets';
import type { IAccessor } from '@wendellhu/redi';
@@ -50,9 +49,9 @@ export const InsertFunctionOperation: ICommand = {
id: 'formula-ui.operation.insert-function',
type: CommandType.OPERATION,
handler: async (accessor: IAccessor, params: IInsertFunctionOperationParams) => {
- const selectionManagerService = accessor.get(SelectionManagerService);
+ const selectionManagerService = accessor.get(SheetsSelectionsService);
const editorService = accessor.get(IEditorService);
- const currentSelections = selectionManagerService.getSelections();
+ const currentSelections = selectionManagerService.getCurrentSelections();
if (!currentSelections || !currentSelections.length) {
return false;
}
@@ -147,7 +146,7 @@ export const InsertFunctionOperation: ICommand = {
const setSelectionParams = {
unitId,
subUnitId,
- pluginName: NORMAL_SELECTION_PLUGIN_NAME,
+
selections: [resultRange],
};
await commandService.executeCommand(SetSelectionsOperation.id, setSelectionParams);
diff --git a/packages/sheets-formula/src/common/selection.ts b/packages/sheets-formula/src/common/selection.ts
index e1d27a154b..e7adb25f31 100644
--- a/packages/sheets-formula/src/common/selection.ts
+++ b/packages/sheets-formula/src/common/selection.ts
@@ -26,18 +26,13 @@ export function getFormulaRefSelectionStyle(themeService: ThemeService, refColor
id,
strokeWidth: 1,
stroke: refColor,
- // strokeDash: 10,
fill,
-
widgets: { tl: true, tc: true, tr: true, ml: true, mr: true, bl: true, bc: true, br: true },
widgetSize: 6,
widgetStrokeWidth: 1,
widgetStroke: style.colorWhite,
-
hasAutoFill: false,
-
hasRowHeader: false,
-
hasColumnHeader: false,
};
}
diff --git a/packages/sheets-formula/src/controllers/__tests__/create-command-test-bed.ts b/packages/sheets-formula/src/controllers/__tests__/create-command-test-bed.ts
index 479c47d784..c71c79d68f 100644
--- a/packages/sheets-formula/src/controllers/__tests__/create-command-test-bed.ts
+++ b/packages/sheets-formula/src/controllers/__tests__/create-command-test-bed.ts
@@ -18,7 +18,7 @@ import type { IWorkbookData, Workbook } from '@univerjs/core';
import { ILogService, IUniverInstanceService, LocaleType, LogLevel, Plugin, Univer, UniverInstanceType } from '@univerjs/core';
import { CalculateFormulaService, DefinedNamesService, FormulaCurrentConfigService, FormulaDataModel, FormulaRuntimeService, IDefinedNamesService, IFormulaCurrentConfigService, IFormulaRuntimeService, LexerTreeBuilder } from '@univerjs/engine-formula';
import { IRenderManagerService, RenderManagerService } from '@univerjs/engine-render';
-import { SelectionManagerService, SheetInterceptorService } from '@univerjs/sheets';
+import { SheetInterceptorService, SheetsSelectionsService } from '@univerjs/sheets';
import { EditorBridgeService, IEditorBridgeService, SheetSkeletonManagerService } from '@univerjs/sheets-ui';
import { EditorService, IEditorService } from '@univerjs/ui';
import type { Dependency } from '@wendellhu/redi';
@@ -78,7 +78,7 @@ export function createCommandTestBed(workbookData?: IWorkbookData, dependencies?
}
override onStarting(injector: Injector): void {
- injector.add([SelectionManagerService]);
+ injector.add([SheetsSelectionsService]);
injector.add([SheetInterceptorService]);
injector.add([CalculateFormulaService]);
injector.add([FormulaDataModel]);
diff --git a/packages/sheets-formula/src/controllers/__tests__/formula-auto-fill.controller.spec.ts b/packages/sheets-formula/src/controllers/__tests__/formula-auto-fill.controller.spec.ts
index 128c82a386..63fdb0f42f 100644
--- a/packages/sheets-formula/src/controllers/__tests__/formula-auto-fill.controller.spec.ts
+++ b/packages/sheets-formula/src/controllers/__tests__/formula-auto-fill.controller.spec.ts
@@ -25,22 +25,21 @@ import {
} from '@univerjs/core';
import {
AddWorksheetMergeMutation,
- NORMAL_SELECTION_PLUGIN_NAME,
RangeProtectionRenderModel,
RangeProtectionRuleModel,
RangeProtectionService,
RemoveWorksheetMergeMutation,
- SelectionManagerService,
SetRangeValuesMutation,
SetSelectionsOperation,
+ SheetsSelectionsService,
} from '@univerjs/sheets';
import {
AutoFillCommand,
AutoFillController,
AutoFillService,
IAutoFillService,
- ISelectionRenderService,
- SelectionRenderService,
+ ISheetSelectionRenderService,
+ SheetSelectionRenderService,
SheetsRenderService,
} from '@univerjs/sheets-ui';
import { IPlatformService, IShortcutService, PlatformService, ShortcutService } from '@univerjs/ui';
@@ -74,7 +73,7 @@ describe('Test auto fill with formula', () => {
beforeEach(() => {
const testBed = createCommandTestBed(undefined, [
- [ISelectionRenderService, { useClass: SelectionRenderService }],
+ [ISheetSelectionRenderService, { useClass: SheetSelectionRenderService }],
[AutoFillController],
[IAutoFillService, { useClass: AutoFillService }],
[IShortcutService, { useClass: ShortcutService }],
@@ -116,13 +115,9 @@ describe('Test auto fill with formula', () => {
describe('correct situations', () => {
it('one cell with formula', async () => {
- const selectionManager = get(SelectionManagerService);
- selectionManager.setCurrentSelection({
- pluginName: NORMAL_SELECTION_PLUGIN_NAME,
- unitId: 'test',
- sheetId: 'sheet1',
- });
- selectionManager.add([
+ const selectionManager = get(SheetsSelectionsService);
+
+ selectionManager.addSelections([
{
range: { startRow: 0, startColumn: 1, endRow: 0, endColumn: 1, rangeType: RANGE_TYPE.NORMAL },
primary: null,
diff --git a/packages/sheets-formula/src/controllers/__tests__/formula-clipboard.controller.spec.ts b/packages/sheets-formula/src/controllers/__tests__/formula-clipboard.controller.spec.ts
index 87e93801e7..f082126f6b 100644
--- a/packages/sheets-formula/src/controllers/__tests__/formula-clipboard.controller.spec.ts
+++ b/packages/sheets-formula/src/controllers/__tests__/formula-clipboard.controller.spec.ts
@@ -19,7 +19,7 @@ import { ICommandService, IUniverInstanceService, ObjectMatrix } from '@univerjs
import { FormulaDataModel, LexerTreeBuilder } from '@univerjs/engine-formula';
import { type ISetRangeValuesMutationParams, SetRangeValuesMutation } from '@univerjs/sheets';
import type { ICellDataWithSpanInfo } from '@univerjs/sheets-ui';
-import { COPY_TYPE, ISelectionRenderService, PREDEFINED_HOOK_NAME, SelectionRenderService } from '@univerjs/sheets-ui';
+import { COPY_TYPE, ISheetSelectionRenderService, PREDEFINED_HOOK_NAME, SheetSelectionRenderService } from '@univerjs/sheets-ui';
import type { Injector } from '@wendellhu/redi';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
@@ -41,7 +41,7 @@ describe('Test paste with formula', () => {
beforeEach(() => {
const testBed = createCommandTestBed(undefined, [
- [ISelectionRenderService, { useClass: SelectionRenderService }],
+ [ISheetSelectionRenderService, { useClass: SheetSelectionRenderService }],
]);
univer = testBed.univer;
get = testBed.get;
diff --git a/packages/sheets-formula/src/controllers/__tests__/update-formula.controller.spec.ts b/packages/sheets-formula/src/controllers/__tests__/update-formula.controller.spec.ts
index 6dc499669b..22a89b5c52 100644
--- a/packages/sheets-formula/src/controllers/__tests__/update-formula.controller.spec.ts
+++ b/packages/sheets-formula/src/controllers/__tests__/update-formula.controller.spec.ts
@@ -17,7 +17,7 @@
import type { ICellData, IObjectMatrixPrimitiveType, IWorkbookData, Nullable, Univer } from '@univerjs/core';
import { CellValueType, Direction, ICommandService, IUniverInstanceService, LocaleType, RANGE_TYPE, RedoCommand, UndoCommand } from '@univerjs/core';
import type { IDeleteRangeMoveLeftCommandParams, IDeleteRangeMoveUpCommandParams, IInsertColCommandParams, IInsertRowCommandParams, IMoveColsCommandParams, IMoveRangeCommandParams, IMoveRowsCommandParams, InsertRangeMoveDownCommandParams, InsertRangeMoveRightCommandParams, IRemoveRowColCommandParams, IRemoveSheetCommandParams, ISetWorksheetNameCommandParams } from '@univerjs/sheets';
-import { DeleteRangeMoveLeftCommand, DeleteRangeMoveUpCommand, InsertColCommand, InsertColMutation, InsertRangeMoveDownCommand, InsertRangeMoveRightCommand, InsertRowCommand, InsertRowMutation, MoveColsCommand, MoveColsMutation, MoveRangeCommand, MoveRangeMutation, MoveRowsCommand, MoveRowsMutation, NORMAL_SELECTION_PLUGIN_NAME, RemoveColCommand, RemoveColMutation, RemoveRowCommand, RemoveRowMutation, RemoveSheetCommand, RemoveSheetMutation, SelectionManagerService, SetRangeValuesMutation, SetSelectionsOperation, SetWorksheetNameCommand, SetWorksheetNameMutation } from '@univerjs/sheets';
+import { DeleteRangeMoveLeftCommand, DeleteRangeMoveUpCommand, InsertColCommand, InsertColMutation, InsertRangeMoveDownCommand, InsertRangeMoveRightCommand, InsertRowCommand, InsertRowMutation, MoveColsCommand, MoveColsMutation, MoveRangeCommand, MoveRangeMutation, MoveRowsCommand, MoveRowsMutation, RemoveColCommand, RemoveColMutation, RemoveRowCommand, RemoveRowMutation, RemoveSheetCommand, RemoveSheetMutation, SetRangeValuesMutation, SetSelectionsOperation, SetWorksheetNameCommand, SetWorksheetNameMutation, SheetsSelectionsService } from '@univerjs/sheets';
import type { Injector } from '@wendellhu/redi';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
@@ -364,15 +364,10 @@ describe('Test insert function operation', () => {
});
it('Move rows, update reference', async () => {
- const selectionManager = get(SelectionManagerService);
- selectionManager.setCurrentSelection({
- pluginName: NORMAL_SELECTION_PLUGIN_NAME,
- unitId: 'test',
- sheetId: 'sheet1',
- });
+ const selectionManager = get(SheetsSelectionsService);
// A1
- selectionManager.add([
+ selectionManager.addSelections([
{
range: { startRow: 1, startColumn: 0, endRow: 1, endColumn: 0, rangeType: RANGE_TYPE.ROW },
primary: null,
@@ -411,15 +406,9 @@ describe('Test insert function operation', () => {
});
it('Move rows, update reference and position', async () => {
- const selectionManager = get(SelectionManagerService);
- selectionManager.setCurrentSelection({
- pluginName: NORMAL_SELECTION_PLUGIN_NAME,
- unitId: 'test',
- sheetId: 'sheet1',
- });
-
+ const selectionManager = get(SheetsSelectionsService);
// A1
- selectionManager.add([
+ selectionManager.addSelections([
{
range: { startRow: 1, startColumn: 0, endRow: 1, endColumn: 0, rangeType: RANGE_TYPE.ROW },
primary: null,
@@ -464,15 +453,10 @@ describe('Test insert function operation', () => {
});
it('Move columns, update reference', async () => {
- const selectionManager = get(SelectionManagerService);
- selectionManager.setCurrentSelection({
- pluginName: NORMAL_SELECTION_PLUGIN_NAME,
- unitId: 'test',
- sheetId: 'sheet1',
- });
+ const selectionManager = get(SheetsSelectionsService);
// A1
- selectionManager.add([
+ selectionManager.addSelections([
{
range: { startRow: 0, startColumn: 0, endRow: 0, endColumn: 0, rangeType: RANGE_TYPE.COLUMN },
primary: null,
@@ -511,15 +495,10 @@ describe('Test insert function operation', () => {
});
it('Move columns, update reference and position', async () => {
- const selectionManager = get(SelectionManagerService);
- selectionManager.setCurrentSelection({
- pluginName: NORMAL_SELECTION_PLUGIN_NAME,
- unitId: 'test',
- sheetId: 'sheet1',
- });
+ const selectionManager = get(SheetsSelectionsService);
// A1
- selectionManager.add([
+ selectionManager.addSelections([
{
range: { startRow: 0, startColumn: 1, endRow: 0, endColumn: 1, rangeType: RANGE_TYPE.COLUMN },
primary: null,
diff --git a/packages/sheets-formula/src/controllers/formula-editor-show.controller.ts b/packages/sheets-formula/src/controllers/formula-editor-show.controller.ts
index b11db534ee..4f048e6fcc 100644
--- a/packages/sheets-formula/src/controllers/formula-editor-show.controller.ts
+++ b/packages/sheets-formula/src/controllers/formula-editor-show.controller.ts
@@ -33,7 +33,7 @@ import type { IRenderContext, IRenderModule } from '@univerjs/engine-render';
import { IRenderManagerService } from '@univerjs/engine-render';
import {
IEditorBridgeService,
- ISelectionRenderService,
+ ISheetSelectionRenderService,
SelectionShape,
SheetSkeletonManagerService,
} from '@univerjs/sheets-ui';
@@ -48,7 +48,6 @@ export class FormulaEditorShowController extends Disposable implements IRenderMo
@Inject(FormulaDataModel) private readonly _formulaDataModel: FormulaDataModel,
@Inject(ThemeService) private readonly _themeService: ThemeService,
@IRenderManagerService private readonly _renderManagerService: IRenderManagerService,
- @ISelectionRenderService private readonly _selectionRenderService: ISelectionRenderService,
@Inject(SheetSkeletonManagerService) private readonly _sheetSkeletonManagerService: SheetSkeletonManagerService,
@ICommandService private readonly _commandService: ICommandService
) {
@@ -183,8 +182,11 @@ export class FormulaEditorShowController extends Disposable implements IRenderMo
hasColumnHeader: false,
};
- const { scene } = this._renderManagerService.getRenderById(unitId) || {};
- const { rangeWithCoord, primaryWithCoord } = this._selectionRenderService.attachSelectionWithCoord({
+ const renderUnit = this._renderManagerService.getRenderById(unitId);
+ if (!renderUnit) return;
+
+ const { scene } = renderUnit;
+ const { rangeWithCoord, primaryWithCoord } = renderUnit.with(ISheetSelectionRenderService).attachSelectionWithCoord({
range: arrayRange,
primary: null,
style,
diff --git a/packages/sheets-formula/src/controllers/formula-ui.controller.ts b/packages/sheets-formula/src/controllers/formula-ui.controller.ts
index 1fa03f0313..ecde1a1cae 100644
--- a/packages/sheets-formula/src/controllers/formula-ui.controller.ts
+++ b/packages/sheets-formula/src/controllers/formula-ui.controller.ts
@@ -17,7 +17,7 @@
import { Disposable, ICommandService, LifecycleStages, OnLifecycle, UniverInstanceType } from '@univerjs/core';
import type { MenuConfig } from '@univerjs/ui';
import { BuiltInUIPart, ComponentManager, IMenuService, IShortcutService, IUIPartsService } from '@univerjs/ui';
-import type { Ctor } from '@wendellhu/redi';
+import type { Ctor, Dependency } from '@wendellhu/redi';
import { Inject, Injector } from '@wendellhu/redi';
import { connectInjector } from '@wendellhu/redi/react-bindings';
@@ -125,6 +125,6 @@ export class FormulaUIController extends Disposable {
}
private _registerRenderModules(): void {
- this.disposeWithMe(this._renderManagerService.registerRenderModule(UniverInstanceType.UNIVER_SHEET, FormulaEditorShowController));
+ this.disposeWithMe(this._renderManagerService.registerRenderModule(UniverInstanceType.UNIVER_SHEET, [FormulaEditorShowController] as Dependency));
}
}
diff --git a/packages/sheets-formula/src/controllers/prompt.controller.ts b/packages/sheets-formula/src/controllers/prompt.controller.ts
index baf38a6d1f..696aa7b5f3 100644
--- a/packages/sheets-formula/src/controllers/prompt.controller.ts
+++ b/packages/sheets-formula/src/controllers/prompt.controller.ts
@@ -70,26 +70,29 @@ import {
IRenderManagerService,
ITextSelectionRenderManager,
} from '@univerjs/engine-render';
-import type { ISelectionWithStyle } from '@univerjs/sheets';
+import type {
+ ISelectionWithStyle,
+} from '@univerjs/sheets';
import {
convertSelectionDataToRange,
- getNormalSelectionStyle,
+
+ DISABLE_NORMAL_SELECTIONS,
getPrimaryForRange,
- NORMAL_SELECTION_PLUGIN_NAME,
- SelectionManagerService,
+ IRefSelectionsService,
setEndForRange,
+ SheetsSelectionsService,
} from '@univerjs/sheets';
import type { EditorBridgeService, SelectionShape } from '@univerjs/sheets-ui';
import {
ExpandSelectionCommand,
getEditorObject,
IEditorBridgeService,
- ISelectionRenderService,
JumpOver,
MoveSelectionCommand,
SheetSkeletonManagerService,
} from '@univerjs/sheets-ui';
import { IContextMenuService, IEditorService, KeyCode, MetaKeys, SetEditorResizeOperation } from '@univerjs/ui';
+import type { IDisposable } from '@wendellhu/redi';
import { Inject } from '@wendellhu/redi';
import type { ISelectEditorFormulaOperationParam } from '../commands/operations/editor-formula.operation';
@@ -97,10 +100,11 @@ import { SelectEditorFormulaOperation } from '../commands/operations/editor-form
import { HelpFunctionOperation } from '../commands/operations/help-function.operation';
import { SearchFunctionOperation } from '../commands/operations/search-function.operation';
import { META_KEY_CTRL_AND_SHIFT } from '../common/prompt';
-import { FORMULA_REF_SELECTION_PLUGIN_NAME, getFormulaRefSelectionStyle } from '../common/selection';
+import { getFormulaRefSelectionStyle } from '../common/selection';
import { IDescriptionService } from '../services/description.service';
import { IFormulaPromptService } from '../services/prompt.service';
import { ReferenceAbsoluteOperation } from '../commands/operations/reference-absolute.operation';
+import { RefSelectionsRenderService } from '../services/render-services/ref-selections.render-service';
interface IRefSelection {
refIndex: number;
@@ -125,7 +129,7 @@ enum InputPanelState {
const sheetEditorUnitIds = [DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY, DOCS_NORMAL_EDITOR_UNIT_ID_KEY];
-@OnLifecycle(LifecycleStages.Rendered, PromptController)
+@OnLifecycle(LifecycleStages.Steady, PromptController)
export class PromptController extends Disposable {
private _formulaRefColors: string[] = [];
@@ -134,7 +138,6 @@ export class PromptController extends Disposable {
private _previousRangesCount: number = 0;
private _previousInsertRefStringIndex: Nullable<number>;
-
private _currentInsertRefStringIndex: number = -1;
private _arrowMoveActionState: ArrowMoveAction = ArrowMoveAction.InitialState;
@@ -155,6 +158,14 @@ export class PromptController extends Disposable {
private _existsSequenceNode = false;
+ // TODO@wzhudev: selection render service would be a render unit, we we cannot
+ // easily access it here.
+ private get _selectionRenderService(): RefSelectionsRenderService {
+ return this._renderManagerService.getRenderById(
+ this._univerInstanceService.getCurrentUnitForType(UniverInstanceType.UNIVER_SHEET)!.getUnitId()
+ )!.with(RefSelectionsRenderService);
+ }
+
constructor(
@ICommandService private readonly _commandService: ICommandService,
@IContextService private readonly _contextService: IContextService,
@@ -164,9 +175,9 @@ export class PromptController extends Disposable {
@Inject(LexerTreeBuilder) private readonly _lexerTreeBuilder: LexerTreeBuilder,
@IRenderManagerService private readonly _renderManagerService: IRenderManagerService,
@Inject(ThemeService) private readonly _themeService: ThemeService,
- @Inject(SelectionManagerService) private readonly _selectionManagerService: SelectionManagerService,
+ @Inject(SheetsSelectionsService) private readonly _sheetsSelectionsService: SheetsSelectionsService,
+ @IRefSelectionsService private readonly _refSelectionsService: SheetsSelectionsService,
@IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService,
- @Inject(ISelectionRenderService) private readonly _selectionRenderService: ISelectionRenderService,
@Inject(IDescriptionService) private readonly _descriptionService: IDescriptionService,
@Inject(TextSelectionManagerService) private readonly _textSelectionManagerService: TextSelectionManagerService,
@IContextMenuService private readonly _contextMenuService: IContextMenuService,
@@ -201,9 +212,7 @@ export class PromptController extends Disposable {
this._initialFormulaTheme();
- this._initialRefSelectionUpdateEvent();
-
- this._initialRefSelectionInsertEvent();
+ this._initSelectionsEndListener();
this._initialExitEditor();
@@ -252,23 +261,24 @@ export class PromptController extends Disposable {
}
const editor = this._editorService.getEditor(params.unitId);
-
- if (!editor || editor.onlyInputContent()) {
+ if (!editor
+ || editor.onlyInputContent()
+ || (editor.isSheetEditor() && this._editorBridgeService.isVisible().visible === false)
+ ) {
return;
}
- if (
- (editor.isSheetEditor() && this._editorBridgeService.isVisible().visible === false) ||
- this._formulaPromptService.isSelectionMoving()
- ) {
+ const onlyInputRange = editor.onlyInputRange();
+
+ // @ts-ignore
+ if (params?.options?.fromSelection) {
return;
+ } else {
+ this._quitSelectingMode();
}
this._contextSwitch();
-
- this._changeKeepVisibleHideState();
-
- this._switchSelectionPlugin();
+ this._checkShouldEnterSelectingMode(onlyInputRange);
if (this._formulaPromptService.isLockedSelectionChange()) {
return;
@@ -276,11 +286,7 @@ export class PromptController extends Disposable {
this._highlightFormula();
- // if (this._isLockedOnSelectionInsertRefString) {
- // return;
- // }
-
- if (editor.onlyInputRange()) {
+ if (onlyInputRange) {
return;
}
@@ -292,24 +298,19 @@ export class PromptController extends Disposable {
}
private _initialEditorInputChange() {
+ const arrows = [KeyCode.ARROW_DOWN, KeyCode.ARROW_UP, KeyCode.ARROW_LEFT, KeyCode.ARROW_RIGHT, KeyCode.CTRL, KeyCode.SHIFT];
+
this.disposeWithMe(
this._textSelectionRenderManager.onInputBefore$.subscribe((param) => {
this._previousSequenceNodes = null;
this._previousInsertRefStringIndex = null;
- this._selectionRenderService.enableSkipRemainLast();
+ this._selectionRenderService.setSkipLastEnabled(true);
- const e = param?.event as KeyboardEvent;
-
- if (e == null) {
- return;
- }
+ const event = param?.event as KeyboardEvent;
+ if (!event) return;
- if (
- ![KeyCode.ARROW_DOWN, KeyCode.ARROW_UP, KeyCode.ARROW_LEFT, KeyCode.ARROW_RIGHT].includes(
- e.which
- )
- ) {
+ if (!arrows.includes(event.which)) {
if (this._arrowMoveActionState !== ArrowMoveAction.moveCursor) {
this._arrowMoveActionState = ArrowMoveAction.moveRefReady;
}
@@ -319,7 +320,7 @@ export class PromptController extends Disposable {
this._inputPanelState = InputPanelState.keyArrow;
}
- if (e.which !== KeyCode.F4) {
+ if (event.which !== KeyCode.F4) {
this._userCursorMove = false;
}
})
@@ -362,158 +363,128 @@ export class PromptController extends Disposable {
this._editorService.closeRangePrompt$.subscribe(() => {
if (!this._editorService.getSpreadsheetFocusState() || !this._formulaPromptService.isLockedSelectionInsert()) {
this._closeRangePrompt();
- this._selectionManagerService.changePlugin(NORMAL_SELECTION_PLUGIN_NAME);
}
})
);
}
private _closeRangePrompt(editorId: Nullable<string>) {
- /**
- * Switching the selection of PluginName causes a refresh.
- * Here, a delay is added to prevent the loss of content when pressing enter.
- */
- const current = this._selectionManagerService.getCurrent();
-
this._insertSelections = [];
-
- if (current?.pluginName === NORMAL_SELECTION_PLUGIN_NAME) {
- this._disableForceKeepVisible();
- return;
- }
-
- this._selectionManagerService.clear();
+ this._refSelectionsService.clear();
if (editorId && this._editorService.isSheetEditor(editorId)) {
- this._selectionManagerService.changePlugin(NORMAL_SELECTION_PLUGIN_NAME);
this._updateEditorModel('\r\n', []);
- } else {
- this._selectionManagerService.changePluginNoRefresh(NORMAL_SELECTION_PLUGIN_NAME);
}
this._contextService.setContextValue(FOCUSING_EDITOR_INPUT_FORMULA, false);
+ this._contextService.setContextValue(DISABLE_NORMAL_SELECTIONS, false);
- this._disableForceKeepVisible();
-
- this._selectionRenderService.resetStyle();
+ this._quitSelectingMode();
this._resetTemp();
this._hideFunctionPanel();
}
- private _initialRefSelectionUpdateEvent() {
- const disposableCollection = new DisposableCollection();
+ private _initSelectionsEndListener() {
+ const d = new DisposableCollection();
- this.disposeWithMe(
- toDisposable(
- this._selectionManagerService.selectionMoveEnd$.subscribe(() => {
- // Each range change requires re-listening
- disposableCollection.dispose();
+ this.disposeWithMe(this._refSelectionsService.selectionMoveEnd$.subscribe((selections) => {
+ d.dispose();
- const current = this._selectionManagerService.getCurrent();
+ if (selections.length === 0) return;
- this._formulaPromptService.disableSelectionMoving();
+ // Rebuild selections when the selection is changed from cache refs in the formula string (not current selections)!
+ this._updateRefSelectionStyle(this._isSelectionMovingRefSelections);
- if (current?.pluginName !== FORMULA_REF_SELECTION_PLUGIN_NAME) {
- return;
- }
+ const selectionControls = this._selectionRenderService.getSelectionControls();
+ selectionControls.forEach((c) => {
+ c.disableHelperSelection();
- this._updateRefSelectionStyle(this._isSelectionMovingRefSelections);
-
- const selectionControls = this._selectionRenderService.getSelectionControls();
- selectionControls.forEach((controlSelection) => {
- controlSelection.disableHelperSelection();
-
- disposableCollection.add(
- toDisposable(
- controlSelection.selectionMoving$.subscribe((toRange) => {
- this._changeControlSelection(toRange, controlSelection);
- })
- )
- );
-
- disposableCollection.add(
- toDisposable(
- controlSelection.selectionScaling$.subscribe((toRange) => {
- this._changeControlSelection(toRange, controlSelection);
- })
- )
- );
-
- disposableCollection.add(
- toDisposable(
- controlSelection.selectionMoved$.subscribe(() => {
- this._formulaPromptService.disableLockedSelectionChange();
- })
- )
- );
-
- disposableCollection.add(
- toDisposable(
- controlSelection.selectionScaled$.subscribe(() => {
- this._formulaPromptService.disableLockedSelectionChange();
- })
- )
- );
- });
- })
- )
- );
+ d.add(c.selectionMoving$.subscribe((toRange) => this._onSelectionControlChange(toRange, c)));
+ d.add(c.selectionScaling$.subscribe((toRange) => this._onSelectionControlChange(toRange, c)));
+
+ d.add(c.selectionMoved$.subscribe(() => this._formulaPromptService.disableLockedSelectionChange()));
+ d.add(c.selectionScaled$.subscribe(() => this._formulaPromptService.disableLockedSelectionChange()));
+ });
+ }));
}
- private _selectionChanging(selectionWithStyles: ISelectionWithStyle[], isSync: boolean = false) {
- if (selectionWithStyles.length === 0) {
- return;
- }
+ // #region - selecting mode - user can use cursor to select a range on the canvas and move the selection
+ // with keyboard shortcuts
- /**
- * selectionChangingState
- * If the selection range in the editor is not restricted by being locked,
- * it is considered a user experience optimization.
- */
- if (this._editorService.selectionChangingState() && !this._formulaPromptService.isLockedSelectionInsert()) {
- return;
+ private _updateSelecting(selectionsWithStyles: ISelectionWithStyle[], performInsertion: boolean = false) {
+ if (selectionsWithStyles.length === 0) return;
+ if (this._editorService.selectionChangingState() && !this._formulaPromptService.isLockedSelectionInsert()) return;
+
+ this._insertControlSelections(selectionsWithStyles);
+
+ if (performInsertion) {
+ const currentSelection = selectionsWithStyles[selectionsWithStyles.length - 1];
+ this._insertControlSelectionReplace(currentSelection);
}
+ }
- this._formulaPromptService.enableSelectionMoving();
+ private _selectionsChangeDisposables: Nullable<IDisposable>;
+ private _enableRefSelectionsRenderService() {
+ const d = this._selectionsChangeDisposables = new DisposableCollection();
- this._inertControlSelection(selectionWithStyles);
+ d.add(this._selectionRenderService.enableSelectionChanging());
- if (isSync === false) {
- return;
- }
- const currentSelection = selectionWithStyles[selectionWithStyles.length - 1];
- this._inertControlSelectionReplace(currentSelection);
+ // When the current selections change, the ref string is updated without touch `IRefSelectionsService`.
+
+ d.add(this._selectionRenderService.selectionMoving$.subscribe((selections) => {
+ this._updateSelecting(selections.map((s) => convertSelectionDataToRange(s)));
+ }));
+
+ d.add(this._selectionRenderService.selectionMoveStart$.subscribe((selections) => {
+ this._updateSelecting(selections.map((s) => convertSelectionDataToRange(s)), true);
+ }));
}
- private _initialRefSelectionInsertEvent() {
- this.disposeWithMe(
- toDisposable(
- this._selectionRenderService.selectionMoving$.subscribe((selectionWithCoordAndStyles) => {
- this._selectionChanging(
- selectionWithCoordAndStyles.map((selectionDataWithStyle) =>
- convertSelectionDataToRange(selectionDataWithStyle)
- )
- );
- })
- )
- );
+ private _disposeSelectionsChangeListeners(): void {
+ this._selectionsChangeDisposables?.dispose();
+ this._selectionsChangeDisposables = null;
+ }
- this.disposeWithMe(
- toDisposable(
- this._selectionRenderService.selectionMoveStart$.subscribe((selectionWithCoordAndStyles) => {
- this._selectionChanging(
- selectionWithCoordAndStyles.map((selectionDataWithStyle) =>
- convertSelectionDataToRange(selectionDataWithStyle)
- ),
- true
- );
- })
- )
- );
+ private _insertControlSelections(selections: ISelectionWithStyle[]) {
+ const currentSelection = selections[selections.length - 1];
+
+ this._resetSequenceNodes(selections.length);
+
+ if (
+ (selections.length === this._previousRangesCount || this._previousRangesCount === 0) &&
+ this._previousSequenceNodes != null
+ ) {
+ this._insertControlSelectionReplace(currentSelection);
+ } else {
+ // Holding down ctrl causes an addition, requiring the ref string to be increased.
+ let insertNodes = this._formulaPromptService.getSequenceNodes()!;
+ const char = this._getCurrentChar()!;
+
+ this._previousInsertRefStringIndex = this._currentInsertRefStringIndex;
+
+ if (!matchRefDrawToken(char) && this._focusIsOnlyRange(selections.length)) {
+ this._formulaPromptService.insertSequenceString(this._currentInsertRefStringIndex, matchToken.COMMA);
+ insertNodes = this._formulaPromptService.getSequenceNodes();
+ this._previousInsertRefStringIndex += 1;
+ }
+
+ this._previousSequenceNodes = Tools.deepClone(insertNodes);
+ this._formulaPromptService.setSequenceNodes(insertNodes);
+
+ const refString = this._getRefString(currentSelection);
+ this._formulaPromptService.insertSequenceRef(this._previousInsertRefStringIndex, refString);
+
+ this._selectionRenderService.setSkipLastEnabled(false);
+ }
+
+ this._arrowMoveActionState = ArrowMoveAction.moveRefReady;
+ this._previousRangesCount = selections.length;
}
+ // #endregion
+
private _initAcceptFormula() {
this.disposeWithMe(
toDisposable(
@@ -539,11 +510,6 @@ export class PromptController extends Disposable {
}
const difference = formulaString.length - node.token.length;
-
- // node.token = formulaString;
-
- // node.endIndex += difference;
-
const newNode = { ...node };
newNode.token = formulaString;
@@ -570,9 +536,6 @@ export class PromptController extends Disposable {
continue;
}
- // node.startIndex += formulaStringCount;
- // node.endIndex += formulaStringCount;
-
const newNode = { ...node };
newNode.startIndex += formulaStringCount;
@@ -586,7 +549,7 @@ export class PromptController extends Disposable {
selectionIndex += 1;
}
- this._syncToEditor(lastSequenceNodes, selectionIndex);
+ this._syncToEditor(lastSequenceNodes, selectionIndex, undefined, false, false);
})
)
);
@@ -632,15 +595,11 @@ export class PromptController extends Disposable {
return;
}
- // const currentBody = this._getCurrentBody();
-
- // const dataStream = currentBody?.dataStream || '';
-
const config = this._getCurrentBodyDataStreamAndOffset();
const functionAndParameter = this._lexerTreeBuilder.getFunctionAndParameter(config?.dataStream || '', startOffset - 1 + (config?.offset || 0));
- if (functionAndParameter == null) {
+ if (!functionAndParameter) {
this._hideFunctionPanel();
return;
}
@@ -676,38 +635,17 @@ export class PromptController extends Disposable {
});
}
- /**
- * If the cursor is located at a formula token,
- * it is necessary to prohibit the behavior of closing the editor by clicking on the canvas,
- * in order to generate reference text for the formula.
- */
- private _changeKeepVisibleHideState() {
- if (this._getContextState() === false) {
- this._disableForceKeepVisible();
+ private _checkShouldEnterSelectingMode(isOnlyInputRangeEditor = false): void {
+ if (isOnlyInputRangeEditor) {
+ this._enterSelectingMode();
return;
}
const char = this._getCurrentChar();
-
- if (char == null) {
- this._disableForceKeepVisible();
- return;
- }
-
- if (matchRefDrawToken(char)) {
- this._editorBridgeService.enableForceKeepVisible();
-
- this._contextMenuService.disable();
-
- this._formulaPromptService.enableLockedSelectionInsert();
-
- this._selectionRenderService.enableRemainLast();
-
- if (this._arrowMoveActionState !== ArrowMoveAction.moveCursor) {
- this._arrowMoveActionState = ArrowMoveAction.moveRefReady;
- }
+ if (char && matchRefDrawToken(char)) {
+ this._enterSelectingMode();
} else {
- this._disableForceKeepVisible();
+ this._quitSelectingMode();
}
}
@@ -735,29 +673,50 @@ export class PromptController extends Disposable {
return dataStream[startOffset - 1 + config.offset];
}
+ private _isSelectingMode = false;
+ private _enterSelectingMode() {
+ if (this._isSelectingMode) {
+ return;
+ }
+
+ this._editorBridgeService.enableForceKeepVisible();
+ this._contextMenuService.disable();
+ this._formulaPromptService.enableLockedSelectionInsert();
+ this._selectionRenderService.setRemainLastEnabled(true);
+
+ // Maybe `enterSelectingMode` should be merged with `_enableRefSelectionsRenderService`.
+ this._enableRefSelectionsRenderService();
+
+ // TODO: remain last
+ if (this._arrowMoveActionState !== ArrowMoveAction.moveCursor) {
+ this._arrowMoveActionState = ArrowMoveAction.moveRefReady;
+ }
+
+ this._isSelectingMode = true;
+ }
+
/**
* Disable the ref string generation mode. In the ref string generation mode,
* users can select a certain area using the mouse and arrow keys, and convert the area into a ref string.
*/
- private _disableForceKeepVisible() {
- this._editorBridgeService.disableForceKeepVisible();
+ private _quitSelectingMode() {
+ if (!this._isSelectingMode) {
+ return;
+ }
+ this._editorBridgeService.disableForceKeepVisible();
this._contextMenuService.enable();
-
this._formulaPromptService.disableLockedSelectionInsert();
-
this._currentInsertRefStringIndex = -1;
- this._selectionRenderService.disableRemainLast();
+
+ this._disposeSelectionsChangeListeners();
if (this._arrowMoveActionState === ArrowMoveAction.moveRefReady) {
this._arrowMoveActionState = ArrowMoveAction.exitInput;
}
- }
- // private _getCurrentBody() {
- // const documentModel = this._univerInstanceService.getCurrentUniverDocInstance();
- // return documentModel?.snapshot?.body;
- // }
+ this._isSelectingMode = false;
+ }
private _getCurrentBodyDataStreamAndOffset() {
const documentModel = this._univerInstanceService.getCurrentUniverDocInstance();
@@ -809,6 +768,7 @@ export class PromptController extends Disposable {
if (config && isFormulaString(config.dataStream)) {
this._contextService.setContextValue(FOCUSING_EDITOR_INPUT_FORMULA, true);
+ this._contextService.setContextValue(DISABLE_NORMAL_SELECTIONS, true);
const lastSequenceNodes =
this._lexerTreeBuilder.sequenceNodesBuilder(config.dataStream.replace(/\r/g, '').replace(/\n/g, '')) ||
@@ -830,6 +790,7 @@ export class PromptController extends Disposable {
}
this._contextService.setContextValue(FOCUSING_EDITOR_INPUT_FORMULA, false);
+ this._contextService.setContextValue(DISABLE_NORMAL_SELECTIONS, false);
this._formulaPromptService.disableLockedSelectionChange();
@@ -846,32 +807,6 @@ export class PromptController extends Disposable {
return this._contextService.getContextValue(FOCUSING_EDITOR_INPUT_FORMULA);
}
- /**
- * Switch from formula selection state to regular selection state.
- */
- private _switchSelectionPlugin() {
- if (this._getContextState() === true) {
- this._selectionManagerService.changePluginNoRefresh(FORMULA_REF_SELECTION_PLUGIN_NAME);
- // const selections = this._selectionManagerService.getSelections();
- // if (selections == null || selections.length === 0) {
- // const selectionData = this._selectionManagerService.getLastByPlugin(NORMAL_SELECTION_PLUGIN_NAME);
- // if (selectionData != null) {
- // this._selectionManagerService.add([Tools.deepClone(selectionData)]);
- // }
- // }
-
- const style = getNormalSelectionStyle(this._themeService);
- style.strokeDash = 8;
- style.hasAutoFill = false;
- style.hasRowHeader = false;
- style.hasColumnHeader = false;
- this._selectionRenderService.setStyle(style);
- } else {
- this._selectionManagerService.changePluginNoRefresh(NORMAL_SELECTION_PLUGIN_NAME);
- this._selectionRenderService.resetStyle();
- }
- }
-
/**
* Highlight cell editor and formula bar editor.
*/
@@ -880,19 +815,13 @@ export class PromptController extends Disposable {
return;
}
- // const dataStream = body.dataStream;
-
- // const sequenceNodes = this._lexerTreeBuilder.buildSequenceNodes(
- // dataStream.replace(/\r/g, '').replace(/\n/g, '')
- // );
-
const sequenceNodes = this._formulaPromptService.getSequenceNodes();
const unitIds = this._editorModelUnitIds();
const bodyList = this._getFormulaAndCellEditorBody(unitIds).filter((b) => !!b);
- this._selectionManagerService.clear();
+ this._refSelectionsService.clear();
if (sequenceNodes == null || sequenceNodes.length === 0) {
this._existsSequenceNode = false;
@@ -966,8 +895,6 @@ export class PromptController extends Disposable {
}
}
- // console.log('sequenceNodes', sequenceNodes, textRuns);
-
return { textRuns, refSelections };
}
@@ -1064,7 +991,7 @@ export class PromptController extends Disposable {
return;
}
- this._selectionManagerService.add(selectionWithStyle);
+ this._refSelectionsService.addSelections(selectionWithStyle);
}
private _getPrimary(range: IRange, themeColor: string, refIndex: number) {
@@ -1242,7 +1169,8 @@ export class PromptController extends Disposable {
sequenceNodes: Array<string | ISequenceNode>,
textSelectionOffset: number,
editorUnitId?: string,
- canUndo: boolean = true
+ canUndo: boolean = true,
+ fromSelection = true
) {
let dataStream = generateStringWithSequence(sequenceNodes);
@@ -1296,6 +1224,7 @@ export class PromptController extends Disposable {
},
],
segmentId: null,
+ options: { fromSelection },
});
} else {
this._updateEditorModel(`${formulaString}\r\n`, textRuns);
@@ -1305,7 +1234,7 @@ export class PromptController extends Disposable {
endOffset: textSelectionOffset + 1 - offset,
style,
},
- ]);
+ ], true, { fromSelection });
}
/**
@@ -1365,7 +1294,7 @@ export class PromptController extends Disposable {
docViewModel.reset(documentDataModel);
}
- private _inertControlSelectionReplace(currentSelection: ISelectionWithStyle) {
+ private _insertControlSelectionReplace(currentSelection: ISelectionWithStyle) {
if (this._previousSequenceNodes == null) {
this._previousSequenceNodes = this._formulaPromptService.getSequenceNodes();
}
@@ -1396,12 +1325,6 @@ export class PromptController extends Disposable {
const range = convertSelectionDataToRange(currentSelection);
this._insertSelections.push(range);
});
-
- // const currentSelection = selectionDatas[selectionDatas.length - 1];
-
- // if (currentSelection.primaryWithCoord != null) {
- // this._lastPrimaryCell = ;
- // }
}
/**
@@ -1458,70 +1381,14 @@ export class PromptController extends Disposable {
}
}
- private _inertControlSelection(selectionWithStyles: ISelectionWithStyle[]) {
- const currentSelection = selectionWithStyles[selectionWithStyles.length - 1];
-
- this._resetSequenceNodes(selectionWithStyles.length);
-
- if (
- (selectionWithStyles.length === this._previousRangesCount || this._previousRangesCount === 0) &&
- this._previousSequenceNodes != null
- ) {
- this._inertControlSelectionReplace(currentSelection);
- } else {
- // Holding down ctrl causes an addition, requiring the ref string to be increased.
- let insertNodes = this._formulaPromptService.getSequenceNodes();
-
- if (insertNodes == null) {
- return;
- }
-
- const char = this._getCurrentChar();
-
- if (char == null) {
- return;
- }
-
- this._previousInsertRefStringIndex = this._currentInsertRefStringIndex;
-
- if (!matchRefDrawToken(char) && this._focusIsOnlyRange(selectionWithStyles.length)) {
- this._formulaPromptService.insertSequenceString(this._currentInsertRefStringIndex, matchToken.COMMA);
-
- insertNodes = this._formulaPromptService.getSequenceNodes();
-
- this._previousInsertRefStringIndex += 1;
- }
-
- this._previousSequenceNodes = Tools.deepClone(insertNodes);
-
- const refString = this._getRefString(currentSelection);
-
- this._formulaPromptService.setSequenceNodes(insertNodes);
-
- this._formulaPromptService.insertSequenceRef(this._previousInsertRefStringIndex, refString);
-
- // this._lastSequenceNodes = insertNodes;
-
- this._selectionRenderService.disableSkipRemainLast();
- }
-
- this._arrowMoveActionState = ArrowMoveAction.moveRefReady;
-
- this._previousRangesCount = selectionWithStyles.length;
- }
-
private _updateRefSelectionStyle(refSelections: IRefSelection[]) {
const controls = this._selectionRenderService.getSelectionControls();
-
const { unitId, sheetId } = this._getCurrentUnitIdAndSheetId();
for (let i = 0, len = refSelections.length; i < len; i++) {
const refSelection = refSelections[i];
-
const { refIndex, themeColor, token } = refSelection;
-
const rangeWithSheet = deserializeRangeWithSheet(token);
-
const { unitId: refUnitId, sheetName, range } = rangeWithSheet;
if (refUnitId != null && refUnitId.length > 0 && unitId !== refUnitId) {
@@ -1529,7 +1396,6 @@ export class PromptController extends Disposable {
}
const refSheetId = this._getSheetIdByName(unitId, sheetName.trim());
-
if (refSheetId != null && refSheetId !== sheetId) {
continue;
}
@@ -1568,25 +1434,21 @@ export class PromptController extends Disposable {
return false;
});
- if (control == null) {
+ if (!control) {
continue;
}
const style = getFormulaRefSelectionStyle(this._themeService, themeColor, refIndex.toString());
-
control.updateStyle(style);
}
}
- private _changeControlSelection(toRange: Nullable<IRangeWithCoord>, controlSelection: SelectionShape) {
- if (!toRange) {
- return;
- }
-
+ private _onSelectionControlChange(toRange: IRangeWithCoord, selectionControl: SelectionShape) {
const { skeleton } = this._getCurrentUnitIdAndSheetId();
this._formulaPromptService.enableLockedSelectionChange();
- const id = controlSelection.selectionStyle?.id;
- if (id == null || !Tools.isStringNumber(id)) {
+
+ const id = selectionControl.selectionStyle?.id;
+ if (!id || !Tools.isStringNumber(id)) {
return;
}
@@ -1646,8 +1508,7 @@ export class PromptController extends Disposable {
}
this._syncToEditor(sequenceNodes, node.endIndex + 1);
-
- controlSelection.update(toRange, undefined, undefined, undefined, this._selectionRenderService.attachPrimaryWithCoord(primary));
+ selectionControl.update(toRange, undefined, undefined, undefined, this._selectionRenderService.attachPrimaryWithCoord(primary));
}
private _refreshFormulaAndCellEditor(unitIds: string[]) {
@@ -1692,7 +1553,6 @@ export class PromptController extends Disposable {
if (documentComponent) {
this.disposeWithMe(documentComponent.onPointerDown$.subscribeEvent(() => {
this._arrowMoveActionState = ArrowMoveAction.moveCursor;
-
this._inputPanelState = InputPanelState.mouse;
}));
}
@@ -1715,7 +1575,6 @@ export class PromptController extends Disposable {
eventType: DeviceInputEventType.Keyboard,
keycode,
});
- // Don't move the selection here, because changeVisible will update the selection.
}
private _pressTab(params: ISelectEditorFormulaOperationParam) {
@@ -1734,7 +1593,6 @@ export class PromptController extends Disposable {
eventType: DeviceInputEventType.Keyboard,
keycode,
});
- // Don't move the selection here, because changeVisible will update the selection.
}
private _pressEsc(params: ISelectEditorFormulaOperationParam) {
@@ -1746,7 +1604,6 @@ export class PromptController extends Disposable {
eventType: DeviceInputEventType.Keyboard,
keycode,
});
- this._selectionManagerService.refreshSelection();
}
}
@@ -1800,6 +1657,7 @@ export class PromptController extends Disposable {
this._pressEnter(params);
return;
}
+
if (keycode === KeyCode.TAB) {
this._pressTab(params);
return;
@@ -1842,24 +1700,24 @@ export class PromptController extends Disposable {
this._arrowMoveActionState = ArrowMoveAction.movingRef;
}
- const previousRanges = this._selectionManagerService.getSelectionRanges() || [];
-
+ // If there's no current selections in the ref selections service, we should copy for
+ // normal selection.
+ const previousRanges = this._refSelectionsService.getCurrentSelections();
if (previousRanges.length === 0) {
- const selectionData =
- this._selectionManagerService.getLastByPlugin(NORMAL_SELECTION_PLUGIN_NAME);
+ const selectionData = this._sheetsSelectionsService.getCurrentLastSelection();
if (selectionData != null) {
const selectionDataNew = Tools.deepClone(selectionData);
- this._selectionManagerService.add([selectionDataNew]);
+ this._refSelectionsService.addSelections([selectionDataNew]);
}
}
this._pressArrowKey(params);
- const selectionWithStyles = this._selectionManagerService.getSelections() || [];
-
+ const selectionWithStyles = this._refSelectionsService.getCurrentSelections();
const currentSelection = selectionWithStyles[selectionWithStyles.length - 1];
- this._inertControlSelectionReplace(currentSelection);
+ this._insertControlSelectionReplace(currentSelection);
+ this._highlightFormula();
}
})
);
@@ -1926,11 +1784,12 @@ export class PromptController extends Disposable {
);
this.disposeWithMe(
+ // TODO: unfinished
this._editorService.singleSelection$.subscribe((state) => {
if (state === true) {
- this._selectionRenderService.enableSingleSelection();
+ // this._selectionRenderService.enableSingleSelection();
} else {
- this._selectionRenderService.disableSingleSelection();
+ // this._selectionRenderService.disableSingleSelection();
}
})
);
@@ -2038,6 +1897,5 @@ export class PromptController extends Disposable {
const editorUnitId = this._univerInstanceService.getCurrentUniverDocInstance()!.getUnitId();
const editor = this._editorService.getEditor(editorUnitId);
return editor?.render;
- // return getEditorObject(this._editorBridgeService.getCurrentEditorId(), this._renderManagerService);
}
}
diff --git a/packages/sheets-formula/src/controllers/update-formula.controller.ts b/packages/sheets-formula/src/controllers/update-formula.controller.ts
index 7380905f86..ab621b404d 100644
--- a/packages/sheets-formula/src/controllers/update-formula.controller.ts
+++ b/packages/sheets-formula/src/controllers/update-formula.controller.ts
@@ -97,12 +97,12 @@ import {
RemoveSheetCommand,
RemoveSheetMutation,
runRefRangeMutations,
- SelectionManagerService,
SetBorderCommand,
SetRangeValuesMutation,
SetStyleCommand,
SetWorksheetNameCommand,
SheetInterceptorService,
+ SheetsSelectionsService,
} from '@univerjs/sheets';
import { Inject, Injector } from '@wendellhu/redi';
@@ -171,7 +171,7 @@ export class UpdateFormulaController extends Disposable {
@Inject(LexerTreeBuilder) private readonly _lexerTreeBuilder: LexerTreeBuilder,
@Inject(FormulaDataModel) private readonly _formulaDataModel: FormulaDataModel,
@Inject(SheetInterceptorService) private _sheetInterceptorService: SheetInterceptorService,
- @Inject(SelectionManagerService) private _selectionManagerService: SelectionManagerService,
+ @Inject(SheetsSelectionsService) private _selectionManagerService: SheetsSelectionsService,
@IEditorService private readonly _editorService: IEditorService,
@Inject(Injector) readonly _injector: Injector
) {
diff --git a/packages/sheets-formula/src/formula-ui-plugin.ts b/packages/sheets-formula/src/formula-ui-plugin.ts
index 24e63f9e40..f264871920 100644
--- a/packages/sheets-formula/src/formula-ui-plugin.ts
+++ b/packages/sheets-formula/src/formula-ui-plugin.ts
@@ -20,6 +20,7 @@ import { Inject, Injector } from '@wendellhu/redi';
import { UniverFormulaEnginePlugin } from '@univerjs/engine-formula';
import { IRenderManagerService } from '@univerjs/engine-render';
+import { IRefSelectionsService, SheetsSelectionsService } from '@univerjs/sheets';
import { FORMULA_UI_PLUGIN_NAME } from './common/plugin-name';
import { ActiveDirtyController } from './controllers/active-dirty.controller';
import { ArrayFormulaDisplayController } from './controllers/array-formula-display.controller';
@@ -28,7 +29,6 @@ import { FormulaClipboardController } from './controllers/formula-clipboard.cont
import { FormulaEditorShowController } from './controllers/formula-editor-show.controller';
import type { IUniverSheetsFormulaConfig } from './controllers/formula-ui.controller';
import { DefaultSheetFormulaConfig, FormulaUIController } from './controllers/formula-ui.controller';
-import { PromptController } from './controllers/prompt.controller';
import { TriggerCalculationController } from './controllers/trigger-calculation.controller';
import { UpdateFormulaController } from './controllers/update-formula.controller';
@@ -44,6 +44,8 @@ import { FormulaRefRangeService } from './services/formula-ref-range.service';
import { RegisterOtherFormulaService } from './services/register-other-formula.service';
import { FormulaAlertRenderController } from './controllers/formula-alert-render.controller';
import { FormulaRenderManagerController } from './controllers/formula-render.controller';
+import { RefSelectionsRenderService } from './services/render-services/ref-selections.render-service';
+import { PromptController } from './controllers/prompt.controller';
/**
* The configuration of the formula UI plugin.
@@ -64,7 +66,7 @@ export class UniverSheetsFormulaPlugin extends Plugin {
}
override onStarting(): void {
- this._init();
+ this._registerDependencies();
}
override onRendered(): void {
@@ -73,37 +75,24 @@ export class UniverSheetsFormulaPlugin extends Plugin {
private _registerRenderModules(): void {
([
-
- FormulaAlertRenderController,
- ]).forEach((controller) => {
- this.disposeWithMe(this._renderManagerService.registerRenderModule(UniverInstanceType.UNIVER_SHEET, controller));
+ [RefSelectionsRenderService],
+ [FormulaAlertRenderController],
+ ] as Dependency[]).forEach((dep) => {
+ this.disposeWithMe(this._renderManagerService.registerRenderModule(UniverInstanceType.UNIVER_SHEET, dep));
});
}
- _init(): void {
+ private _registerDependencies(): void {
+ const j = this._injector;
const dependencies: Dependency[] = [
- // services
[IFormulaPromptService, { useClass: FormulaPromptService }],
- [
- IDescriptionService,
- {
- useFactory: () => this._injector.createInstance(DescriptionService, this._config?.description),
- },
- ],
+ [IRefSelectionsService, { useClass: SheetsSelectionsService }],
+ [IDescriptionService, { useFactory: () => j.createInstance(DescriptionService, this._config?.description) }],
[IFormulaCustomFunctionService, { useClass: FormulaCustomFunctionService }],
-
[IRegisterFunctionService, { useClass: RegisterFunctionService }],
[FormulaRefRangeService],
[RegisterOtherFormulaService],
-
- // controllers
- [
- FormulaUIController,
- {
- useFactory: () => this._injector.createInstance(FormulaUIController, this._config),
- },
- ],
- [PromptController],
+ [FormulaUIController, { useFactory: () => j.createInstance(FormulaUIController, this._config) }],
[FormulaAutoFillController],
[FormulaClipboardController],
[ArrayFormulaDisplayController],
@@ -113,9 +102,10 @@ export class UniverSheetsFormulaPlugin extends Plugin {
[ActiveDirtyController],
[DefinedNameController],
[FormulaRenderManagerController],
+ [PromptController],
];
- dependencies.forEach((dependency) => this._injector.add(dependency));
+ dependencies.forEach((dependency) => j.add(dependency));
}
}
diff --git a/packages/sheets-formula/src/services/prompt.service.ts b/packages/sheets-formula/src/services/prompt.service.ts
index 76a51bd7f5..08164cedac 100644
--- a/packages/sheets-formula/src/services/prompt.service.ts
+++ b/packages/sheets-formula/src/services/prompt.service.ts
@@ -137,12 +137,6 @@ export interface IFormulaPromptService {
insertSequenceString(index: number, content: string): void;
- enableSelectionMoving(): void;
-
- disableSelectionMoving(): void;
-
- isSelectionMoving(): boolean;
-
enableLockedSelectionChange(): void;
disableLockedSelectionChange(): void;
@@ -383,18 +377,6 @@ export class FormulaPromptService implements IFormulaPromptService, IDisposable
}
}
- enableSelectionMoving() {
- this._isSelectionMoving = true;
- }
-
- disableSelectionMoving() {
- this._isSelectionMoving = false;
- }
-
- isSelectionMoving() {
- return this._isSelectionMoving;
- }
-
enableLockedSelectionChange() {
this._isLockedOnSelectionChangeRefString = true;
}
diff --git a/packages/sheets-formula/src/services/render-services/ref-selections.render-service.ts b/packages/sheets-formula/src/services/render-services/ref-selections.render-service.ts
new file mode 100644
index 0000000000..40ffe9a5da
--- /dev/null
+++ b/packages/sheets-formula/src/services/render-services/ref-selections.render-service.ts
@@ -0,0 +1,212 @@
+/**
+ * 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 } from '@univerjs/core';
+import { DisposableCollection, RANGE_TYPE, ThemeService, toDisposable } from '@univerjs/core';
+import type { IMouseEvent, IPointerEvent, IRenderContext, IRenderModule } from '@univerjs/engine-render';
+import { IRenderManagerService, ScrollTimerType, SHEET_VIEWPORT_KEY, Vector2 } from '@univerjs/engine-render';
+import { convertSelectionDataToRange, getNormalSelectionStyle, IRefSelectionsService, type ISelectionWithCoordAndStyle, type SheetsSelectionsService, type WorkbookSelections } from '@univerjs/sheets';
+import { BaseSelectionRenderService, checkInHeaderRanges, getAllSelection, getCoordByOffset, getSheetObject, SheetSkeletonManagerService } from '@univerjs/sheets-ui';
+import { IShortcutService } from '@univerjs/ui';
+import type { IDisposable } from '@wendellhu/redi';
+import { Inject, Injector } from '@wendellhu/redi';
+
+/**
+ * This service extends the existing `SelectionRenderService` to provide the rendering of prompt selections
+ * when user is editing ref ranges in formulas.
+ *
+ * Not that this service works with Uni-mode, which means it should be able to deal with multi render unit
+ * and handle selections on them, though each at a time.
+ */
+export class RefSelectionsRenderService extends BaseSelectionRenderService implements IRenderModule {
+ private readonly _workbookSelections: WorkbookSelections;
+
+ private _eventDisposables: Nullable<IDisposable>;
+
+ constructor(
+ private readonly _context: IRenderContext<Workbook>,
+ @Inject(Injector) injector: Injector,
+ @Inject(ThemeService) themeService: ThemeService,
+ @IShortcutService shortcutService: IShortcutService,
+ @IRenderManagerService renderManagerService: IRenderManagerService,
+ @IRefSelectionsService refSelectionsService: SheetsSelectionsService,
+ @Inject(SheetSkeletonManagerService) private readonly _sheetSkeletonManagerService: SheetSkeletonManagerService
+ ) {
+ super(
+ injector,
+ themeService,
+ shortcutService,
+ renderManagerService
+ );
+
+ this._workbookSelections = refSelectionsService.getWorkbookSelections(this._context.unitId);
+
+ this._initSelectionChangeListener();
+ this._initSkeletonChangeListener();
+ this._initUserActionSyncListener();
+
+ this._setStyle(getRefSelectionStyle(this._themeService));
+ this._remainLastEnabled = true; // For ref range selections, we should always remain others.
+ }
+
+ setRemainLastEnabled(enabled: boolean): void {
+ this._remainLastEnabled = enabled;
+ }
+
+ setSkipLastEnabled(enabled: boolean): void {
+ this._skipLastEnabled = enabled;
+ }
+
+ /**
+ * Call this method and user will be able to select on the canvas to update selections.
+ */
+ enableSelectionChanging(): IDisposable {
+ this._disableSelectionChanging();
+ this._eventDisposables = this._initCanvasEventListeners();
+ return toDisposable(() => this._disableSelectionChanging());
+ }
+
+ private _disableSelectionChanging(): void {
+ this._eventDisposables?.dispose();
+ this._eventDisposables = null;
+ }
+
+ private _initCanvasEventListeners(): IDisposable {
+ const sheetObject = this._getSheetObject();
+ const { spreadsheetRowHeader, spreadsheetColumnHeader, spreadsheet, spreadsheetLeftTopPlaceholder } = sheetObject;
+ const { scene } = this._context;
+
+ const listenerDisposables = new DisposableCollection();
+
+ listenerDisposables.add(spreadsheet?.onPointerDown$.subscribeEvent((evt: IPointerEvent | IMouseEvent, state) => {
+ this._onPointerDown(evt, spreadsheet.zIndex + 1, RANGE_TYPE.NORMAL, this._getActiveViewport(evt));
+ if (evt.button !== 2) {
+ state.stopPropagation();
+ }
+ }));
+
+ listenerDisposables.add(
+ spreadsheetRowHeader?.onPointerDown$.subscribeEvent((evt: IPointerEvent | IMouseEvent, state) => {
+ const skeleton = this._sheetSkeletonManagerService.getCurrent()!.skeleton;
+ const { row } = getCoordByOffset(evt.offsetX, evt.offsetY, scene, skeleton);
+ const matchSelectionData = checkInHeaderRanges(this._workbookSelections.getCurrentSelections(), row, RANGE_TYPE.ROW);
+ if (matchSelectionData) return;
+
+ this._onPointerDown(evt, (spreadsheet.zIndex || 1) + 1, RANGE_TYPE.ROW, this._getActiveViewport(evt), ScrollTimerType.Y);
+ if (evt.button !== 2) {
+ state.stopPropagation();
+ }
+ })
+ );
+
+ listenerDisposables.add(spreadsheetColumnHeader?.onPointerDown$.subscribeEvent((evt: IPointerEvent | IMouseEvent, state) => {
+ const skeleton = this._sheetSkeletonManagerService.getCurrent()!.skeleton;
+ const { column } = getCoordByOffset(evt.offsetX, evt.offsetY, scene, skeleton);
+ const matchSelectionData = checkInHeaderRanges(this._workbookSelections.getCurrentSelections(), column, RANGE_TYPE.COLUMN);
+ if (matchSelectionData) return;
+
+ this._onPointerDown(evt, (spreadsheet.zIndex || 1) + 1, RANGE_TYPE.COLUMN, this._getActiveViewport(evt), ScrollTimerType.X);
+
+ if (evt.button !== 2) {
+ state.stopPropagation();
+ }
+ }));
+
+ listenerDisposables.add(spreadsheetLeftTopPlaceholder?.onPointerDown$.subscribeEvent((evt: IPointerEvent | IMouseEvent, state) => {
+ this._reset(); // remove all other selections
+
+ const skeleton = this._sheetSkeletonManagerService.getCurrent()!.skeleton;
+ const selectionWithStyle = getAllSelection(skeleton);
+ const selectionData = this.attachSelectionWithCoord(selectionWithStyle);
+ this._addSelectionControlBySelectionData(selectionData);
+ this.refreshSelectionMoveStart();
+
+ if (evt.button !== 2) {
+ state.stopPropagation();
+ }
+ }));
+
+ return listenerDisposables;
+ }
+
+ private _initUserActionSyncListener() {
+ // When user completes range selection, we should update the range into the `IRefSelectionService`,
+ // and later the selections would be updated to the `SelectionManagerService`.
+ // Note that it would also trigger the callback in `_initSelectionChangeListener`.
+ this.disposeWithMe(this.selectionMoveEnd$.subscribe((params) => this._updateSelections(params)));
+ }
+
+ private _updateSelections(selectionDataWithStyleList: ISelectionWithCoordAndStyle[]) {
+ const workbook = this._context.unit;
+ const sheetId = workbook.getActiveSheet()!.getSheetId();
+
+ if (selectionDataWithStyleList.length === 0) return;
+
+ this._workbookSelections.setSelections(
+ sheetId,
+ selectionDataWithStyleList.map((selectionDataWithStyle) => convertSelectionDataToRange(selectionDataWithStyle))
+ );
+ }
+
+ private _initSelectionChangeListener(): void {
+ // When selection completes, we need to update the selections' rendering and clear event handlers.
+ this.disposeWithMe(this._workbookSelections.beforeSelectionMoveEnd$.subscribe((selectionsWithStyles) => {
+ // Clear already existed selections.
+ this._reset();
+
+ for (const selectionWithStyle of selectionsWithStyles) {
+ const selectionData = this.attachSelectionWithCoord(selectionWithStyle);
+ this._addSelectionControlBySelectionData(selectionData);
+ }
+ }));
+ }
+
+ private _initSkeletonChangeListener(): void {
+ this.disposeWithMe(this._sheetSkeletonManagerService.currentSkeleton$.subscribe((param) => {
+ if (!param) {
+ return;
+ }
+
+ const { skeleton } = param;
+ const { scene } = this._context;
+ const viewportMain = scene.getViewport(SHEET_VIEWPORT_KEY.VIEW_MAIN);
+ this._changeRuntime(skeleton, scene, viewportMain);
+ }));
+ }
+
+ private _getActiveViewport(evt: IPointerEvent | IMouseEvent) {
+ const sheetObject = this._getSheetObject();
+ return sheetObject?.scene.getActiveViewportByCoord(Vector2.FromArray([evt.offsetX, evt.offsetY]));
+ }
+
+ private _getSheetObject() {
+ return getSheetObject(this._context.unit, this._context)!;
+ }
+}
+
+/**
+ * Return the selections style while adding a range into the formula string (blue dashed).
+ * @param themeService
+ * @returns The selection's style.
+ */
+function getRefSelectionStyle(themeService: ThemeService) {
+ const style = getNormalSelectionStyle(themeService);
+ style.strokeDash = 8;
+ style.hasAutoFill = false;
+ style.hasRowHeader = false;
+ style.hasColumnHeader = false;
+ return style;
+}
diff --git a/packages/sheets-formula/tsconfig.json b/packages/sheets-formula/tsconfig.json
index d676ad2a20..805edbd666 100644
--- a/packages/sheets-formula/tsconfig.json
+++ b/packages/sheets-formula/tsconfig.json
@@ -5,5 +5,5 @@
"outDir": "lib/types"
},
"references": [{ "path": "./tsconfig.node.json" }],
- "include": ["src"]
+ "include": ["src", "../sheets/src/services/ref-selections.service.ts"]
}
diff --git a/packages/sheets-hyper-link-ui/src/commands/operations/sidebar.operations.ts b/packages/sheets-hyper-link-ui/src/commands/operations/sidebar.operations.ts
index 1056edd362..4b6773265c 100644
--- a/packages/sheets-hyper-link-ui/src/commands/operations/sidebar.operations.ts
+++ b/packages/sheets-hyper-link-ui/src/commands/operations/sidebar.operations.ts
@@ -15,7 +15,7 @@
*/
import { CommandType, type ICommand, ICommandService, IUniverInstanceService } from '@univerjs/core';
-import { getSheetCommandTarget, type ISheetCommandSharedParams, SelectionManagerService } from '@univerjs/sheets';
+import { getSheetCommandTarget, type ISheetCommandSharedParams, SheetsSelectionsService } from '@univerjs/sheets';
import { HyperLinkModel } from '@univerjs/sheets-hyper-link';
import { ISidebarService } from '@univerjs/ui';
import { CellLinkEdit } from '../../views/CellLinkEdit';
@@ -77,11 +77,12 @@ export const InsertHyperLinkOperation: ICommand = {
return false;
}
const commandService = accessor.get(ICommandService);
- const selectionManagerService = accessor.get(SelectionManagerService);
- const selection = selectionManagerService.getFirst();
- if (!selection?.primary) {
+ const selectionManagerService = accessor.get(SheetsSelectionsService);
+ const selection = selectionManagerService.getCurrentLastSelection();
+ if (!selection) {
return false;
}
+
const row = selection.primary.startRow;
const column = selection.primary.startColumn;
return commandService.executeCommand(OpenHyperLinkSidebarOperation.id, {
diff --git a/packages/sheets-hyper-link-ui/src/controllers/popup.controller.ts b/packages/sheets-hyper-link-ui/src/controllers/popup.controller.ts
index 43a4d73940..1e2b21a7c5 100644
--- a/packages/sheets-hyper-link-ui/src/controllers/popup.controller.ts
+++ b/packages/sheets-hyper-link-ui/src/controllers/popup.controller.ts
@@ -46,7 +46,7 @@ export class SheetsHyperLinkPopupController extends Disposable {
const skeleton = this._renderManagerService.getRenderById(currentCell.location.unitId)
?.with(SheetSkeletonManagerService)
- .getUnitSkeleton(currentCell.location.unitId, currentCell.location.subUnitId)
+ .getWorksheetSkeleton(currentCell.location.subUnitId)
?.skeleton;
const currentCol = currentCell.location.col;
diff --git a/packages/sheets-hyper-link-ui/src/controllers/set-range.controller.ts b/packages/sheets-hyper-link-ui/src/controllers/set-range.controller.ts
index c51eceb7b6..68eef74c7c 100644
--- a/packages/sheets-hyper-link-ui/src/controllers/set-range.controller.ts
+++ b/packages/sheets-hyper-link-ui/src/controllers/set-range.controller.ts
@@ -18,7 +18,7 @@ import type { IMutationInfo, Workbook } from '@univerjs/core';
import { CellValueType, Disposable, IUniverInstanceService, LifecycleStages, ObjectMatrix, OnLifecycle, Range, Tools, UniverInstanceType } from '@univerjs/core';
import { Inject, Injector } from '@wendellhu/redi';
import type { ISetRangeValuesMutationParams } from '@univerjs/sheets';
-import { ClearSelectionAllCommand, ClearSelectionContentCommand, ClearSelectionFormatCommand, getSheetCommandTarget, SelectionManagerService, SetRangeValuesCommand, SetRangeValuesMutation, SetRangeValuesUndoMutationFactory, SheetInterceptorService } from '@univerjs/sheets';
+import { ClearSelectionAllCommand, ClearSelectionContentCommand, ClearSelectionFormatCommand, getSheetCommandTarget, SetRangeValuesCommand, SetRangeValuesMutation, SetRangeValuesUndoMutationFactory, SheetInterceptorService, SheetsSelectionsService } from '@univerjs/sheets';
import type { IAddHyperLinkCommandParams, IUpdateHyperLinkCommandParams } from '@univerjs/sheets-hyper-link';
import { AddHyperLinkCommand, AddHyperLinkMutation, HyperLinkModel, RemoveHyperLinkMutation, UpdateHyperLinkCommand } from '@univerjs/sheets-hyper-link';
import { isLegalLink, serializeUrl } from '../common/util';
@@ -29,7 +29,7 @@ export class SheetHyperLinkSetRangeController extends Disposable {
@Inject(SheetInterceptorService) private readonly _sheetInterceptorService: SheetInterceptorService,
@Inject(Injector) private readonly _injector: Injector,
@Inject(HyperLinkModel) private readonly _hyperLinkModel: HyperLinkModel,
- @Inject(SelectionManagerService) private readonly _selectionManagerService: SelectionManagerService,
+ @Inject(SheetsSelectionsService) private readonly _selectionManagerService: SheetsSelectionsService,
@IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService
) {
super();
@@ -220,7 +220,7 @@ export class SheetHyperLinkSetRangeController extends Disposable {
) {
const redos: IMutationInfo[] = [];
const undos: IMutationInfo[] = [];
- const selection = this._selectionManagerService.getFirst();
+ const selection = this._selectionManagerService.getCurrentLastSelection();
const target = getSheetCommandTarget(this._univerInstanceService);
if (selection && target) {
const { unitId, subUnitId } = target;
diff --git a/packages/sheets-hyper-link-ui/src/plugin.ts b/packages/sheets-hyper-link-ui/src/plugin.ts
index e735806307..fd97e01cee 100644
--- a/packages/sheets-hyper-link-ui/src/plugin.ts
+++ b/packages/sheets-hyper-link-ui/src/plugin.ts
@@ -68,7 +68,13 @@ export class UniverSheetsHyperLinkUIPlugin extends Plugin {
];
dependencies.forEach((dep) => injector.add(dep));
+ }
+
+ override onReady(): void {
+ const renderDependencies: Dependency[] = [
+ [SheetsHyperLinkRenderController],
+ ];
- this._renderManagerService.registerRenderModule(UniverInstanceType.UNIVER_SHEET, SheetsHyperLinkRenderController);
+ renderDependencies.forEach((d) => this._renderManagerService.registerRenderModule(UniverInstanceType.UNIVER_SHEET, d));
}
}
diff --git a/packages/sheets-hyper-link-ui/src/services/resolver.service.ts b/packages/sheets-hyper-link-ui/src/services/resolver.service.ts
index 84c15fd1ad..18a0b49a5b 100644
--- a/packages/sheets-hyper-link-ui/src/services/resolver.service.ts
+++ b/packages/sheets-hyper-link-ui/src/services/resolver.service.ts
@@ -19,7 +19,7 @@ import { ICommandService, isValidRange, IUniverInstanceService, LocaleService, R
import { MessageType } from '@univerjs/design';
import { deserializeRangeWithSheet, IDefinedNamesService, serializeRangeWithSheet } from '@univerjs/engine-formula';
import type { ISetSelectionsOperationParams } from '@univerjs/sheets';
-import { NORMAL_SELECTION_PLUGIN_NAME, SetSelectionsOperation, SetWorksheetActiveOperation } from '@univerjs/sheets';
+import { SetSelectionsOperation, SetWorksheetActiveOperation } from '@univerjs/sheets';
import { ERROR_RANGE } from '@univerjs/sheets-hyper-link';
import { ScrollToRangeOperation } from '@univerjs/sheets-ui';
import { IMessageService } from '@univerjs/ui';
@@ -190,7 +190,7 @@ export class SheetsHyperLinkResolverService {
{
unitId,
subUnitId,
- pluginName: NORMAL_SELECTION_PLUGIN_NAME,
+
selections: [{
range: realRange,
}],
diff --git a/packages/sheets-hyper-link/src/controllers/ref-range.controller.ts b/packages/sheets-hyper-link/src/controllers/ref-range.controller.ts
index f2f9cf25be..b7927cea67 100644
--- a/packages/sheets-hyper-link/src/controllers/ref-range.controller.ts
+++ b/packages/sheets-hyper-link/src/controllers/ref-range.controller.ts
@@ -17,7 +17,7 @@
import type { IRange, Nullable } from '@univerjs/core';
import { Disposable, ICommandService, isValidRange, LifecycleStages, OnLifecycle, sequenceExecuteAsync, toDisposable } from '@univerjs/core';
import type { EffectRefRangeParams } from '@univerjs/sheets';
-import { handleDefaultRangeChangeWithEffectRefCommandsSkipNoInterests, RefRangeService, SelectionManagerService } from '@univerjs/sheets';
+import { handleDefaultRangeChangeWithEffectRefCommandsSkipNoInterests, RefRangeService, SheetsSelectionsService } from '@univerjs/sheets';
import type { IAddHyperLinkMutationParams, ICellHyperLink, IRemoveHyperLinkMutationParams, IUpdateHyperLinkMutationParams, IUpdateHyperLinkRefMutationParams } from '@univerjs/sheets-hyper-link';
import { AddHyperLinkMutation, HyperLinkModel, RemoveHyperLinkMutation, UpdateHyperLinkMutation, UpdateHyperLinkRefMutation } from '@univerjs/sheets-hyper-link';
import type { IDisposable } from '@wendellhu/redi';
@@ -35,7 +35,7 @@ export class SheetsHyperLinkRefRangeController extends Disposable {
constructor(
@Inject(RefRangeService) private readonly _refRangeService: RefRangeService,
@Inject(HyperLinkModel) private readonly _hyperLinkModel: HyperLinkModel,
- @Inject(SelectionManagerService) private readonly _selectionManagerService: SelectionManagerService,
+ @Inject(SheetsSelectionsService) private readonly _selectionManagerService: SheetsSelectionsService,
@ICommandService private readonly _commandService: ICommandService
) {
super();
diff --git a/packages/sheets-numfmt/src/commands/commands/add-decimal.command.ts b/packages/sheets-numfmt/src/commands/commands/add-decimal.command.ts
index fcdb9f777b..11bf6e73b1 100644
--- a/packages/sheets-numfmt/src/commands/commands/add-decimal.command.ts
+++ b/packages/sheets-numfmt/src/commands/commands/add-decimal.command.ts
@@ -16,7 +16,7 @@
import type { ICommand } from '@univerjs/core';
import { CommandType, ICommandService, IUniverInstanceService, Range } from '@univerjs/core';
-import { getSheetCommandTarget, INumfmtService, SelectionManagerService } from '@univerjs/sheets';
+import { getSheetCommandTarget, INumfmtService, SheetsSelectionsService } from '@univerjs/sheets';
import type { IAccessor } from '@wendellhu/redi';
import { getDecimalFromPattern, setPatternDecimal } from '../../utils/decimal';
@@ -28,11 +28,11 @@ export const AddDecimalCommand: ICommand = {
type: CommandType.COMMAND,
handler: async (accessor: IAccessor) => {
const commandService = accessor.get(ICommandService);
- const selectionManagerService = accessor.get(SelectionManagerService);
+ const selectionManagerService = accessor.get(SheetsSelectionsService);
const numfmtService = accessor.get(INumfmtService);
const univerInstanceService = accessor.get(IUniverInstanceService);
- const selections = selectionManagerService.getSelections();
+ const selections = selectionManagerService.getCurrentSelections();
if (!selections || !selections.length) {
return false;
}
diff --git a/packages/sheets-numfmt/src/commands/commands/set-currency.command.ts b/packages/sheets-numfmt/src/commands/commands/set-currency.command.ts
index 37c22cbbb2..25d68662d1 100644
--- a/packages/sheets-numfmt/src/commands/commands/set-currency.command.ts
+++ b/packages/sheets-numfmt/src/commands/commands/set-currency.command.ts
@@ -16,7 +16,7 @@
import type { ICommand } from '@univerjs/core';
import { CommandType, ICommandService, Range } from '@univerjs/core';
-import { SelectionManagerService } from '@univerjs/sheets';
+import { SheetsSelectionsService } from '@univerjs/sheets';
import type { IAccessor } from '@wendellhu/redi';
import { CURRENCYFORMAT } from '../../base/const/FORMATDETAIL';
@@ -28,9 +28,9 @@ export const SetCurrencyCommand: ICommand = {
type: CommandType.COMMAND,
handler: async (accessor: IAccessor) => {
const commandService = accessor.get(ICommandService);
- const selectionManagerService = accessor.get(SelectionManagerService);
+ const selectionManagerService = accessor.get(SheetsSelectionsService);
- const selections = selectionManagerService.getSelections();
+ const selections = selectionManagerService.getCurrentSelections();
if (!selections || !selections.length) {
return false;
}
diff --git a/packages/sheets-numfmt/src/commands/commands/set-percent.command.ts b/packages/sheets-numfmt/src/commands/commands/set-percent.command.ts
index d389ca8df0..814f4dae83 100644
--- a/packages/sheets-numfmt/src/commands/commands/set-percent.command.ts
+++ b/packages/sheets-numfmt/src/commands/commands/set-percent.command.ts
@@ -16,7 +16,7 @@
import type { ICommand } from '@univerjs/core';
import { CommandType, ICommandService, Range } from '@univerjs/core';
-import { SelectionManagerService } from '@univerjs/sheets';
+import { SheetsSelectionsService } from '@univerjs/sheets';
import type { IAccessor } from '@wendellhu/redi';
import type { ISetNumfmtCommandParams } from './set-numfmt.command';
@@ -27,9 +27,9 @@ export const SetPercentCommand: ICommand = {
type: CommandType.COMMAND,
handler: async (accessor: IAccessor) => {
const commandService = accessor.get(ICommandService);
- const selectionManagerService = accessor.get(SelectionManagerService);
+ const selectionManagerService = accessor.get(SheetsSelectionsService);
- const selections = selectionManagerService.getSelections();
+ const selections = selectionManagerService.getCurrentSelections();
if (!selections || !selections.length) {
return false;
}
diff --git a/packages/sheets-numfmt/src/commands/commands/subtract-decimal.command.ts b/packages/sheets-numfmt/src/commands/commands/subtract-decimal.command.ts
index 81fbd77a8a..f0ab3b4352 100644
--- a/packages/sheets-numfmt/src/commands/commands/subtract-decimal.command.ts
+++ b/packages/sheets-numfmt/src/commands/commands/subtract-decimal.command.ts
@@ -16,7 +16,7 @@
import type { ICommand } from '@univerjs/core';
import { CommandType, ICommandService, IUniverInstanceService, Range } from '@univerjs/core';
-import { getSheetCommandTarget, INumfmtService, SelectionManagerService } from '@univerjs/sheets';
+import { getSheetCommandTarget, INumfmtService, SheetsSelectionsService } from '@univerjs/sheets';
import type { IAccessor } from '@wendellhu/redi';
import { getDecimalFromPattern, setPatternDecimal } from '../../utils/decimal';
@@ -28,11 +28,11 @@ export const SubtractDecimalCommand: ICommand = {
type: CommandType.COMMAND,
handler: async (accessor: IAccessor) => {
const commandService = accessor.get(ICommandService);
- const selectionManagerService = accessor.get(SelectionManagerService);
+ const selectionManagerService = accessor.get(SheetsSelectionsService);
const numfmtService = accessor.get(INumfmtService);
const univerInstanceService = accessor.get(IUniverInstanceService);
- const selections = selectionManagerService.getSelections();
+ const selections = selectionManagerService.getCurrentSelections();
if (!selections || !selections.length) {
return false;
}
diff --git a/packages/sheets-numfmt/src/components/more-numfmt-type/MoreNumfmtType.tsx b/packages/sheets-numfmt/src/components/more-numfmt-type/MoreNumfmtType.tsx
index 05cc3ba8b9..8c492158b6 100644
--- a/packages/sheets-numfmt/src/components/more-numfmt-type/MoreNumfmtType.tsx
+++ b/packages/sheets-numfmt/src/components/more-numfmt-type/MoreNumfmtType.tsx
@@ -20,7 +20,7 @@ import './index.less';
import { ICommandService, LocaleService, Range } from '@univerjs/core';
import { ITextSelectionRenderManager } from '@univerjs/engine-render';
import type { FormatType } from '@univerjs/sheets';
-import { SelectionManagerService } from '@univerjs/sheets';
+import { SheetsSelectionsService } from '@univerjs/sheets';
import { useDependency, useInjector } from '@wendellhu/redi/react-bindings';
import React from 'react';
@@ -43,9 +43,9 @@ export const Options = () => {
const localeService = useDependency(LocaleService);
const injector = useInjector();
- const selectionManagerService = useDependency(SelectionManagerService);
+ const selectionManagerService = useDependency(SheetsSelectionsService);
const setNumfmt = (pattern: string | null) => {
- const selection = selectionManagerService.getLast();
+ const selection = selectionManagerService.getCurrentLastSelection();
if (!selection) {
return;
}
diff --git a/packages/sheets-numfmt/src/controllers/numfmt.controller.ts b/packages/sheets-numfmt/src/controllers/numfmt.controller.ts
index 617c1fad6e..9a95035049 100644
--- a/packages/sheets-numfmt/src/controllers/numfmt.controller.ts
+++ b/packages/sheets-numfmt/src/controllers/numfmt.controller.ts
@@ -35,9 +35,9 @@ import {
INTERCEPTOR_POINT,
INumfmtService,
RemoveNumfmtMutation,
- SelectionManagerService,
SetNumfmtMutation,
SheetInterceptorService,
+ SheetsSelectionsService,
} from '@univerjs/sheets';
import { ComponentManager, ISidebarService } from '@univerjs/ui';
import type { IDisposable } from '@wendellhu/redi';
@@ -74,7 +74,7 @@ export class NumfmtController extends Disposable implements INumfmtController {
@Inject(ThemeService) private _themeService: ThemeService,
@IUniverInstanceService private _univerInstanceService: IUniverInstanceService,
@ICommandService private _commandService: ICommandService,
- @Inject(SelectionManagerService) private _selectionManagerService: SelectionManagerService,
+ @Inject(SheetsSelectionsService) private _selectionManagerService: SheetsSelectionsService,
@IRenderManagerService private _renderManagerService: IRenderManagerService,
@INumfmtService private _numfmtService: INumfmtService,
@Inject(ComponentManager) private _componentManager: ComponentManager,
@@ -98,7 +98,7 @@ export class NumfmtController extends Disposable implements INumfmtController {
const numfmtService = this._numfmtService;
const localeService = this._localeService;
- const selections = selectionManagerService.getSelectionRanges() || [];
+ const selections = selectionManagerService.getCurrentSelections()?.map((s) => s.range) || [];
const range = selections[0];
if (!range) {
@@ -131,7 +131,7 @@ export class NumfmtController extends Disposable implements INumfmtController {
this._previewPattern = config.value;
this._forceUpdate();
} else if (config.type === 'confirm') {
- const selections = selectionManagerService.getSelectionRanges() || [];
+ const selections = selectionManagerService.getCurrentSelections()?.map((s) => s.range) || [];
const params: ISetNumfmtCommandParams = { values: [] };
const patternType = getPatternType(config.value);
selections.forEach((rangeInfo) => {
diff --git a/packages/sheets-numfmt/src/menu/menu.ts b/packages/sheets-numfmt/src/menu/menu.ts
index c1b44aa2c2..6446c3f23b 100644
--- a/packages/sheets-numfmt/src/menu/menu.ts
+++ b/packages/sheets-numfmt/src/menu/menu.ts
@@ -19,8 +19,8 @@ import {
INumfmtService,
RangeProtectionPermissionEditPoint,
RemoveNumfmtMutation,
- SelectionManagerService,
SetNumfmtMutation,
+ SheetsSelectionsService,
WorkbookEditablePermission,
WorksheetEditPermission,
WorksheetSetCellStylePermission,
@@ -104,7 +104,7 @@ export const FactoryOtherMenuItem = (accessor: IAccessor): IMenuSelectorItem =>
const commandService = accessor.get(ICommandService);
const localeService = accessor.get(LocaleService);
- const selectionManagerService = accessor.get(SelectionManagerService);
+ const selectionManagerService = accessor.get(SheetsSelectionsService);
const value$ = deriveStateFromActiveSheet$(univerInstanceService, '', ({ workbook, worksheet }) => new Observable((subscribe) =>
merge(
selectionManagerService.selectionMoveEnd$,
@@ -118,7 +118,7 @@ export const FactoryOtherMenuItem = (accessor: IAccessor): IMenuSelectorItem =>
return () => disposable.dispose();
})
).subscribe(() => {
- const selections = selectionManagerService.getSelections();
+ const selections = selectionManagerService.getCurrentSelections();
if (selections && selections[0]) {
const range = selections[0].range;
const row = range.startRow;
diff --git a/packages/sheets-sort-ui/src/services/sheets-sort-ui.service.tsx b/packages/sheets-sort-ui/src/services/sheets-sort-ui.service.tsx
index d66d719bed..95559cda9d 100644
--- a/packages/sheets-sort-ui/src/services/sheets-sort-ui.service.tsx
+++ b/packages/sheets-sort-ui/src/services/sheets-sort-ui.service.tsx
@@ -26,8 +26,8 @@ import { Disposable, ICommandService,
UniverInstanceType,
} from '@univerjs/core';
+import { getPrimaryForRange, SetSelectionsOperation, SheetsSelectionsService } from '@univerjs/sheets';
import type { ISheetRangeLocation } from '@univerjs/sheets';
-import { getPrimaryForRange, NORMAL_SELECTION_PLUGIN_NAME, SelectionManagerService, SetSelectionsOperation } from '@univerjs/sheets';
import { Inject } from '@wendellhu/redi';
import { expandToContinuousRange } from '@univerjs/sheets-ui';
@@ -68,7 +68,7 @@ export class SheetsSortUIService extends Disposable {
@IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService,
@IConfirmService private readonly _confirmService: IConfirmService,
@ILogService private readonly _logService: ILogService,
- @Inject(SelectionManagerService) private readonly _selectionManagerService: SelectionManagerService,
+ @Inject(SheetsSelectionsService) private readonly _selectionManagerService: SheetsSelectionsService,
@Inject(SheetsSortService) private readonly _sheetsSortService: SheetsSortService,
@Inject(LocaleService) private readonly _localeService: LocaleService,
@ICommandService private readonly _commandService: ICommandService) {
@@ -151,7 +151,7 @@ export class SheetsSortUIService extends Disposable {
const setSelectionsOperationParams = {
unitId,
subUnitId,
- pluginName: NORMAL_SELECTION_PLUGIN_NAME,
+
selections: [{ range, primary: getPrimaryForRange(range, worksheet), style: null }],
};
@@ -235,7 +235,7 @@ export class SheetsSortUIService extends Disposable {
const worksheet = workbook.getActiveSheet() as Worksheet;
const unitId = workbook.getUnitId();
const subUnitId = worksheet.getSheetId();
- const selection = this._selectionManagerService.getLast();
+ const selection = this._selectionManagerService.getCurrentLastSelection();
if (!selection) {
return null;
}
@@ -257,7 +257,7 @@ export class SheetsSortUIService extends Disposable {
this.setSelection(unitId, subUnitId, range);
}
}
- const primary = this._selectionManagerService.getLast()?.primary;
+ const primary = this._selectionManagerService.getCurrentLastSelection()?.primary;
if (!primary) {
return null;
}
diff --git a/packages/sheets-sort/src/commands/commands/__tests__/create-command-test-bed.ts b/packages/sheets-sort/src/commands/commands/__tests__/create-command-test-bed.ts
index d645bb18b5..950d9cfbd7 100644
--- a/packages/sheets-sort/src/commands/commands/__tests__/create-command-test-bed.ts
+++ b/packages/sheets-sort/src/commands/commands/__tests__/create-command-test-bed.ts
@@ -17,7 +17,7 @@
import { BooleanNumber, ILogService, IUniverInstanceService, type IWorkbookData, LocaleService, LocaleType, LogLevel, Plugin, Tools, Univer, UniverInstanceType, type Workbook } from '@univerjs/core';
import type { Dependency } from '@wendellhu/redi';
import { Inject, Injector } from '@wendellhu/redi';
-import { SelectionManagerService, SheetInterceptorService } from '@univerjs/sheets';
+import { SheetInterceptorService, SheetsSelectionsService } from '@univerjs/sheets';
import { FormulaDataModel } from '@univerjs/engine-formula';
import enUS from '../../../locale/en-US';
import { SheetsSortService } from '../../../services/sheets-sort.service';
@@ -143,7 +143,7 @@ export function createCommandTestBed(workbookData?: IWorkbookData, dependencies?
override onStarting(injector: Injector): void {
injector.add([SheetsSortService]);
injector.add([SheetsSortController]);
- injector.add([SelectionManagerService, { useClass: mockSelectionManagerService as any }]);
+ injector.add([SheetsSelectionsService, { useClass: mockSelectionManagerService as any }]);
injector.add([SheetInterceptorService]);
injector.add([FormulaDataModel, { useClass: mockFormulaDataModel }]);
diff --git a/packages/sheets-thread-comment-base/src/controllers/sheets-thread-comment-ref-range.controller.ts b/packages/sheets-thread-comment-base/src/controllers/sheets-thread-comment-ref-range.controller.ts
index d7f179c22b..387bd8fa94 100644
--- a/packages/sheets-thread-comment-base/src/controllers/sheets-thread-comment-ref-range.controller.ts
+++ b/packages/sheets-thread-comment-base/src/controllers/sheets-thread-comment-ref-range.controller.ts
@@ -19,7 +19,7 @@ import { Disposable, ICommandService, LifecycleStages, OnLifecycle, sequenceExec
import type { IDisposable } from '@wendellhu/redi';
import { Inject } from '@wendellhu/redi';
import type { EffectRefRangeParams } from '@univerjs/sheets';
-import { handleDefaultRangeChangeWithEffectRefCommandsSkipNoInterests, RefRangeService, SelectionManagerService } from '@univerjs/sheets';
+import { handleDefaultRangeChangeWithEffectRefCommandsSkipNoInterests, RefRangeService, SheetsSelectionsService } from '@univerjs/sheets';
import type { IAddCommentMutationParams, IUpdateCommentRefMutationParams } from '@univerjs/thread-comment';
import { AddCommentMutation, DeleteCommentMutation, ThreadCommentModel, UpdateCommentRefMutation } from '@univerjs/thread-comment';
import { serializeRange, singleReferenceToGrid } from '@univerjs/engine-formula';
@@ -35,7 +35,7 @@ export class SheetsThreadCommentRefRangeController extends Disposable {
@Inject(RefRangeService) private readonly _refRangeService: RefRangeService,
@Inject(SheetsThreadCommentModel) private readonly _sheetsThreadCommentModel: SheetsThreadCommentModel,
@Inject(ThreadCommentModel) private readonly _threadCommentModel: ThreadCommentModel,
- @Inject(SelectionManagerService) private readonly _selectionManagerService: SelectionManagerService,
+ @Inject(SheetsSelectionsService) private readonly _selectionManagerService: SheetsSelectionsService,
@ICommandService private readonly _commandService: ICommandService
) {
super();
diff --git a/packages/sheets-thread-comment/src/commands/operations/comment.operation.ts b/packages/sheets-thread-comment/src/commands/operations/comment.operation.ts
index a538336a7b..7e932e2c08 100644
--- a/packages/sheets-thread-comment/src/commands/operations/comment.operation.ts
+++ b/packages/sheets-thread-comment/src/commands/operations/comment.operation.ts
@@ -17,7 +17,7 @@
import type { ICommand } from '@univerjs/core';
import { CommandType, IUniverInstanceService } from '@univerjs/core';
import type { ISheetLocation } from '@univerjs/sheets';
-import { getSheetCommandTarget, SelectionManagerService } from '@univerjs/sheets';
+import { getSheetCommandTarget, SheetsSelectionsService } from '@univerjs/sheets';
import { ThreadCommentPanelService } from '@univerjs/thread-comment-ui';
import { SheetsThreadCommentModel } from '@univerjs/sheets-thread-comment-base';
import { SheetsThreadCommentPopupService } from '../../services/sheets-thread-comment-popup.service';
@@ -26,40 +26,39 @@ export const ShowAddSheetCommentModalOperation: ICommand = {
type: CommandType.OPERATION,
id: 'sheets.operation.show-comment-modal',
handler(accessor) {
- const selectionManagerService = accessor.get(SelectionManagerService);
+ const selectionManagerService = accessor.get(SheetsSelectionsService);
const univerInstanceService = accessor.get(IUniverInstanceService);
const sheetsThreadCommentPopupService = accessor.get(SheetsThreadCommentPopupService);
const threadCommentPanelService = accessor.get(ThreadCommentPanelService);
- const activeCell = selectionManagerService.getFirst()?.primary;
- const current = selectionManagerService.getCurrent();
+ const activeCell = selectionManagerService.getCurrentLastSelection()?.primary;
const model = accessor.get(SheetsThreadCommentModel);
- if (!current || !activeCell) {
+ if (!activeCell) {
return false;
}
- const { unitId, sheetId } = current;
- const result = getSheetCommandTarget(univerInstanceService, { unitId, subUnitId: sheetId });
+ const result = getSheetCommandTarget(univerInstanceService);
if (!result) {
return false;
}
- const { workbook, worksheet } = result;
+
+ const { workbook, worksheet, unitId, subUnitId } = result;
const location: ISheetLocation = {
workbook,
worksheet,
unitId,
- subUnitId: sheetId,
+ subUnitId,
row: activeCell.startRow,
col: activeCell.startColumn,
};
sheetsThreadCommentPopupService.showPopup(location);
- const rootId = model.getByLocation(unitId, sheetId, activeCell.startRow, activeCell.startColumn);
+ const rootId = model.getByLocation(unitId, subUnitId, activeCell.startRow, activeCell.startColumn);
if (rootId) {
threadCommentPanelService.setActiveComment({
unitId,
- subUnitId: sheetId,
+ subUnitId,
commentId: rootId,
trigger: 'context-menu',
});
diff --git a/packages/sheets-ui/src/commands/commands/__tests__/add-worksheet-merge.command.spec.ts b/packages/sheets-ui/src/commands/commands/__tests__/add-worksheet-merge.command.spec.ts
index 575caf337d..1d7a06a722 100644
--- a/packages/sheets-ui/src/commands/commands/__tests__/add-worksheet-merge.command.spec.ts
+++ b/packages/sheets-ui/src/commands/commands/__tests__/add-worksheet-merge.command.spec.ts
@@ -38,7 +38,6 @@ import {
MoveColsCommand,
MoveColsMutation,
MoveRangeMutation,
- NORMAL_SELECTION_PLUGIN_NAME,
RefRangeService,
RemoveColCommand,
RemoveColMutation,
@@ -46,9 +45,9 @@ import {
RemoveRowMutation,
RemoveWorksheetMergeCommand,
RemoveWorksheetMergeMutation,
- SelectionManagerService,
SetRangeValuesMutation,
SetSelectionsOperation,
+ SheetsSelectionsService,
} from '@univerjs/sheets';
import { type IConfirmPartMethodOptions, IConfirmService } from '@univerjs/ui';
import type { IDisposable, Injector } from '@wendellhu/redi';
@@ -67,7 +66,7 @@ describe('Test add worksheet merge commands', () => {
let univer: Univer;
let get: Injector['get'];
let commandService: ICommandService;
- let selectionManager: SelectionManagerService;
+ let selectionManager: SheetsSelectionsService;
beforeEach(() => {
const testBed = createCommandTestBed(undefined, [
@@ -132,12 +131,7 @@ describe('Test add worksheet merge commands', () => {
get(LocaleService).load({});
get(MergeCellController);
- selectionManager = get(SelectionManagerService);
- selectionManager.setCurrentSelection({
- pluginName: NORMAL_SELECTION_PLUGIN_NAME,
- unitId: 'test',
- sheetId: 'sheet1',
- });
+ selectionManager = get(SheetsSelectionsService);
});
afterEach(() => {
@@ -147,13 +141,8 @@ describe('Test add worksheet merge commands', () => {
describe('add merge all', () => {
describe('correct situations', () => {
it('will merge all cells of the selected range when there is a selected range', async () => {
- const selectionManager = get(SelectionManagerService);
- selectionManager.setCurrentSelection({
- pluginName: NORMAL_SELECTION_PLUGIN_NAME,
- unitId: 'test',
- sheetId: 'sheet1',
- });
- selectionManager.add([
+ const selectionManager = get(SheetsSelectionsService);
+ selectionManager.addSelections([
{
range: { startRow: 0, startColumn: 0, endColumn: 5, endRow: 5, rangeType: RANGE_TYPE.NORMAL },
primary: null,
@@ -198,13 +187,8 @@ describe('Test add worksheet merge commands', () => {
describe('add merge vertical', () => {
describe('correct situations', () => {
it('will merge all vertical cells of the selected range when there is a selected range', async () => {
- const selectionManager = get(SelectionManagerService);
- selectionManager.setCurrentSelection({
- pluginName: NORMAL_SELECTION_PLUGIN_NAME,
- unitId: 'test',
- sheetId: 'sheet1',
- });
- selectionManager.add([
+ const selectionManager = get(SheetsSelectionsService);
+ selectionManager.addSelections([
{
range: { startRow: 0, startColumn: 0, endColumn: 5, endRow: 5, rangeType: RANGE_TYPE.NORMAL },
primary: null,
@@ -247,13 +231,8 @@ describe('Test add worksheet merge commands', () => {
describe('add merge horizontal', () => {
describe('correct situations', () => {
it('will merge all horizontal cells of the selected range when there is a selected range', async () => {
- const selectionManager = get(SelectionManagerService);
- selectionManager.setCurrentSelection({
- pluginName: NORMAL_SELECTION_PLUGIN_NAME,
- unitId: 'test',
- sheetId: 'sheet1',
- });
- selectionManager.add([
+ const selectionManager = get(SheetsSelectionsService);
+ selectionManager.addSelections([
{
range: { startRow: 0, startColumn: 0, endColumn: 5, endRow: 5, rangeType: RANGE_TYPE.NORMAL },
primary: null,
@@ -291,13 +270,8 @@ describe('Test add worksheet merge commands', () => {
describe('cancel merge', () => {
describe('correct situations', () => {
it('will cancel the merge of the selected range when there is a selected range', async () => {
- const selectionManager = get(SelectionManagerService);
- selectionManager.setCurrentSelection({
- pluginName: NORMAL_SELECTION_PLUGIN_NAME,
- unitId: 'test',
- sheetId: 'sheet1',
- });
- selectionManager.add([
+ const selectionManager = get(SheetsSelectionsService);
+ selectionManager.addSelections([
{
range: { startRow: 0, startColumn: 0, endColumn: 5, endRow: 5, rangeType: RANGE_TYPE.NORMAL },
primary: null,
@@ -335,8 +309,8 @@ describe('Test add worksheet merge commands', () => {
describe('with insert or remove col', () => {
it('will adjust the merge data when insert col and remove col', async () => {
- selectionManager.clear();
- selectionManager.add([
+ selectionManager.clearCurrentSelections();
+ selectionManager.addSelections([
{
range: { startRow: 0, startColumn: 0, endColumn: 5, endRow: 5, rangeType: RANGE_TYPE.NORMAL },
primary: null,
@@ -357,8 +331,8 @@ describe('Test add worksheet merge commands', () => {
expect(mergeData.length).toBe(0);
expect(await commandService.executeCommand(AddWorksheetMergeAllCommand.id)).toBeTruthy();
expect(mergeData.length).toBe(2);
- selectionManager.clear();
- selectionManager.add([
+ selectionManager.clearCurrentSelections();
+ selectionManager.addSelections([
{
range: {
startRow: 0,
@@ -374,8 +348,8 @@ describe('Test add worksheet merge commands', () => {
expect(await commandService.executeCommand(InsertColAfterCommand.id)).toBeTruthy();
expect(worksheet.getMergeData().length).toBe(2);
expect(worksheet.getMergeData()[1]).toStrictEqual({ startRow: 10, startColumn: 11, endColumn: 16, endRow: 15, rangeType: 0 });
- selectionManager.clear();
- selectionManager.add([
+ selectionManager.clearCurrentSelections();
+ selectionManager.addSelections([
{
range: {
startRow: 0,
@@ -392,8 +366,8 @@ describe('Test add worksheet merge commands', () => {
expect(worksheet.getMergeData().length).toBe(2);
expect(worksheet.getMergeData()[1]).toStrictEqual({ startRow: 10, startColumn: 11, endColumn: 18, endRow: 15, rangeType: 0 });
- selectionManager.clear();
- selectionManager.add([
+ selectionManager.clearCurrentSelections();
+ selectionManager.addSelections([
{
range: {
startRow: 0,
@@ -409,8 +383,8 @@ describe('Test add worksheet merge commands', () => {
expect(await commandService.executeCommand(RemoveColCommand.id)).toBeTruthy();
expect(worksheet.getMergeData().length).toBe(2);
expect(worksheet.getMergeData()[1]).toStrictEqual({ startRow: 10, startColumn: 10, endColumn: 17, endRow: 15, rangeType: 0 });
- selectionManager.clear();
- selectionManager.add([
+ selectionManager.clearCurrentSelections();
+ selectionManager.addSelections([
{
range: {
startRow: 0,
@@ -431,8 +405,8 @@ describe('Test add worksheet merge commands', () => {
describe('with move col', () => {
it('will adjust the merge data when move col', async () => {
- selectionManager.clear();
- selectionManager.add([
+ selectionManager.clearCurrentSelections();
+ selectionManager.addSelections([
{
range: { startRow: 0, startColumn: 0, endColumn: 5, endRow: 5, rangeType: RANGE_TYPE.NORMAL },
primary: null,
@@ -453,8 +427,8 @@ describe('Test add worksheet merge commands', () => {
expect(mergeData.length).toBe(0);
expect(await commandService.executeCommand(AddWorksheetMergeAllCommand.id)).toBeTruthy();
expect(mergeData.length).toBe(2);
- selectionManager.clear();
- selectionManager.add([{
+ selectionManager.clearCurrentSelections();
+ selectionManager.addSelections([{
primary: null,
style: null,
range: {
@@ -484,8 +458,8 @@ describe('Test add worksheet merge commands', () => {
expect(worksheet.getMergeData().length).toBe(2);
expect(worksheet.getMergeData()[1]).toStrictEqual({ startRow: 10, startColumn: 11, endColumn: 16, endRow: 15, rangeType: 0 });
- selectionManager.clear();
- selectionManager.add([{
+ selectionManager.clearCurrentSelections();
+ selectionManager.addSelections([{
primary: null,
style: null,
range: {
diff --git a/packages/sheets-ui/src/commands/commands/__tests__/auto-fill.controller.spec.ts b/packages/sheets-ui/src/commands/commands/__tests__/auto-fill.controller.spec.ts
index 482cff5757..b6769638c0 100644
--- a/packages/sheets-ui/src/commands/commands/__tests__/auto-fill.controller.spec.ts
+++ b/packages/sheets-ui/src/commands/commands/__tests__/auto-fill.controller.spec.ts
@@ -27,11 +27,10 @@ import {
} from '@univerjs/core';
import {
AddWorksheetMergeMutation,
- NORMAL_SELECTION_PLUGIN_NAME,
RemoveWorksheetMergeMutation,
- SelectionManagerService,
SetRangeValuesMutation,
SetSelectionsOperation,
+ SheetsSelectionsService,
} from '@univerjs/sheets';
import { EditorService, IEditorService, IPlatformService, IShortcutService, PlatformService, ShortcutService } from '@univerjs/ui';
import type { Injector } from '@wendellhu/redi';
@@ -42,11 +41,12 @@ import { AutoFillController } from '../../../controllers/auto-fill.controller';
import { AutoFillService, IAutoFillService } from '../../../services/auto-fill/auto-fill.service';
import { APPLY_TYPE } from '../../../services/auto-fill/type';
import { EditorBridgeService, IEditorBridgeService } from '../../../services/editor-bridge.service';
-import { ISelectionRenderService, SelectionRenderService } from '../../../services/selection/selection-render.service';
import { SheetSkeletonManagerService } from '../../../services/sheet-skeleton-manager.service';
import { RefillCommand } from '../refill.command';
import { AutoClearContentCommand, AutoFillCommand } from '../auto-fill.command';
import { SheetsRenderService } from '../../../services/sheets-render.service';
+import { ISheetSelectionRenderService } from '../../../services/selection/base-selection-render.service';
+import { SheetSelectionRenderService } from '../../../services/selection/selection-render.service';
import { createCommandTestBed } from './create-command-test-bed';
const theme = {
@@ -279,10 +279,10 @@ describe('Test auto fill rules in controller', () => {
endRow: number,
endColumn: number
) => Array<Array<Nullable<IStyleData>>> | undefined;
- let selectionManagerService: SelectionManagerService;
+ let selectionManagerService: SheetsSelectionsService;
beforeEach(() => {
const testBed = createCommandTestBed(TEST_WORKBOOK_DATA, [
- [ISelectionRenderService, { useClass: SelectionRenderService }],
+ [ISheetSelectionRenderService, { useClass: SheetSelectionRenderService }],
[IAutoFillService, { useClass: AutoFillService }],
[IShortcutService, { useClass: ShortcutService }],
[IPlatformService, { useClass: PlatformService }],
@@ -300,12 +300,7 @@ describe('Test auto fill rules in controller', () => {
themeService = get(ThemeService);
themeService.setTheme(theme);
autoFillController = get(AutoFillController);
- selectionManagerService = get(SelectionManagerService);
- selectionManagerService.setCurrentSelection({
- pluginName: NORMAL_SELECTION_PLUGIN_NAME,
- unitId: 'test',
- sheetId: 'sheet1',
- });
+ selectionManagerService = get(SheetsSelectionsService);
commandService.registerCommand(SetRangeValuesMutation);
commandService.registerCommand(SetSelectionsOperation);
commandService.registerCommand(RemoveWorksheetMergeMutation);
@@ -547,8 +542,8 @@ describe('Test auto fill rules in controller', () => {
const workbook = get(IUniverInstanceService).getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET)!;
if (!workbook) throw new Error('This is an error');
- const selectionManagerService = get(SelectionManagerService);
- selectionManagerService.add([{
+ const selectionManagerService = get(SheetsSelectionsService);
+ selectionManagerService.addSelections([{
style: null,
range: {
startRow: 0,
@@ -583,7 +578,7 @@ describe('Test auto fill rules in controller', () => {
}
);
expect(workbook.getActiveSheet()?.getMergeData().length).toBe(2);
- expect(selectionManagerService.getLast()?.primary).toEqual(expect.objectContaining({
+ expect(selectionManagerService.getCurrentLastSelection()?.primary).toEqual(expect.objectContaining({
startRow: 0,
startColumn: 5,
endRow: 2,
@@ -597,8 +592,8 @@ describe('Test auto fill rules in controller', () => {
const workbook = get(IUniverInstanceService).getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET)!;
if (!workbook) throw new Error('This is an error');
- const selectionManagerService = get(SelectionManagerService);
- selectionManagerService.add([{
+ const selectionManagerService = get(SheetsSelectionsService);
+ selectionManagerService.addSelections([{
style: null,
range: {
startRow: 0,
@@ -634,7 +629,7 @@ describe('Test auto fill rules in controller', () => {
}
);
expect(workbook.getSheetBySheetId('sheet1')?.getCell(4, 0)?.v).toBeFalsy();
- expect(selectionManagerService.getLast()?.primary).toEqual(expect.objectContaining({
+ expect(selectionManagerService.getCurrentLastSelection()?.primary).toEqual(expect.objectContaining({
startRow: 0,
startColumn: 0,
endRow: 0,
diff --git a/packages/sheets-ui/src/commands/commands/__tests__/create-command-test-bed.ts b/packages/sheets-ui/src/commands/commands/__tests__/create-command-test-bed.ts
index 73ffd234aa..823e042ef1 100644
--- a/packages/sheets-ui/src/commands/commands/__tests__/create-command-test-bed.ts
+++ b/packages/sheets-ui/src/commands/commands/__tests__/create-command-test-bed.ts
@@ -17,6 +17,7 @@
import type { IWorkbookData, Workbook } from '@univerjs/core';
import {
BooleanNumber,
+ DisposableCollection,
ILogService,
IUniverInstanceService,
LocaleService,
@@ -27,16 +28,21 @@ import {
Univer,
UniverInstanceType,
} from '@univerjs/core';
-import { BorderStyleManagerService,
+import {
+ BorderStyleManagerService,
RangeProtectionRuleModel,
- SelectionManagerService,
+ SheetInterceptorService,
- SheetInterceptorService, WorkbookPermissionService, WorksheetPermissionService, WorksheetProtectionPointModel, WorksheetProtectionRuleModel } from '@univerjs/sheets';
+ SheetsSelectionsService, WorkbookPermissionService, WorksheetPermissionService, WorksheetProtectionPointModel, WorksheetProtectionRuleModel,
+} from '@univerjs/sheets';
import type { Dependency } from '@wendellhu/redi';
import { Inject, Injector } from '@wendellhu/redi';
import { LexerTreeBuilder } from '@univerjs/engine-formula';
+import type { IRenderContext } from '@univerjs/engine-render';
import enUS from '../../../locale/en-US';
+import { ISheetSelectionRenderService } from '../../../services/selection/base-selection-render.service';
+import { SheetSelectionRenderService } from '../../../services/selection/selection-render.service';
const getTestWorkbookDataDemo = (): IWorkbookData => {
return {
@@ -99,7 +105,7 @@ export function createCommandTestBed(workbookData?: IWorkbookData, dependencies?
}
override onStarting(injector: Injector): void {
- injector.add([SelectionManagerService]);
+ injector.add([SheetsSelectionsService]);
injector.add([BorderStyleManagerService]);
injector.add([SheetInterceptorService]);
injector.add([LexerTreeBuilder]);
@@ -108,18 +114,36 @@ export function createCommandTestBed(workbookData?: IWorkbookData, dependencies?
injector.add([WorkbookPermissionService]);
injector.add([WorksheetProtectionRuleModel]);
injector.add([RangeProtectionRuleModel]);
+
dependencies?.forEach((d) => injector.add(d));
}
}
univer.registerPlugin(TestPlugin);
- const sheet = univer.createUniverSheet(Tools.deepClone(workbookData || getTestWorkbookDataDemo()));
+
+ const snapshot = Tools.deepClone(workbookData || getTestWorkbookDataDemo());
+ const sheet = univer.createUnit<IWorkbookData, Workbook>(UniverInstanceType.UNIVER_SHEET, snapshot);
+
+ if (!dependencies || !dependencies.find((d) => d[0] === ISheetSelectionRenderService)) {
+ const context: IRenderContext<Workbook> = {
+ unitId: sheet.getUnitId(),
+ unit: sheet,
+ type: UniverInstanceType.UNIVER_SHEET,
+ engine: new DisposableCollection() as any,
+ scene: new DisposableCollection() as any,
+ mainComponent: null as any,
+ components: new Map(),
+ isMainScene: true,
+ };
+
+ injector.add([ISheetSelectionRenderService, { useFactory: () => injector.createInstance(SheetSelectionRenderService, context) }]);
+ }
const univerInstanceService = injector.get(IUniverInstanceService);
univerInstanceService.focusUnit('test');
const logService = injector.get(ILogService);
- logService.setLogLevel(LogLevel.SILENT); // change this to `LogLevel.VERBOSE` to debug tests via logs
+ logService.setLogLevel(LogLevel.VERBOSE); // change this to `LogLevel.VERBOSE` to debug tests via logs
const localeService = injector.get(LocaleService);
localeService.load({ enUS });
diff --git a/packages/sheets-ui/src/commands/commands/__tests__/hide-row-col-confirm.command.spec.ts b/packages/sheets-ui/src/commands/commands/__tests__/hide-row-col-confirm.command.spec.ts
index e845632c41..94fa42f8b4 100644
--- a/packages/sheets-ui/src/commands/commands/__tests__/hide-row-col-confirm.command.spec.ts
+++ b/packages/sheets-ui/src/commands/commands/__tests__/hide-row-col-confirm.command.spec.ts
@@ -18,16 +18,15 @@ import type { IRange, Univer } from '@univerjs/core';
import { ICommandService, IUniverInstanceService, LocaleService, RANGE_TYPE } from '@univerjs/core';
import {
AddWorksheetMergeMutation,
- NORMAL_SELECTION_PLUGIN_NAME,
RemoveWorksheetMergeCommand,
RemoveWorksheetMergeMutation,
- SelectionManagerService,
SetColHiddenCommand,
SetColHiddenMutation,
SetRangeValuesMutation,
SetRowHiddenCommand,
SetRowHiddenMutation,
SetSelectionsOperation,
+ SheetsSelectionsService,
} from '@univerjs/sheets';
import { type IConfirmPartMethodOptions, IConfirmService } from '@univerjs/ui';
import type { IDisposable, Injector } from '@wendellhu/redi';
@@ -101,13 +100,8 @@ describe('Test hide row col confirm commands', () => {
describe('Hide row', () => {
it('Will apply when select some rows', async () => {
- const selectionManager = get(SelectionManagerService);
- selectionManager.setCurrentSelection({
- pluginName: NORMAL_SELECTION_PLUGIN_NAME,
- unitId: 'test',
- sheetId: 'sheet1',
- });
- selectionManager.add([
+ const selectionManager = get(SheetsSelectionsService);
+ selectionManager.addSelections([
{
range: { startRow: 1, startColumn: Number.NaN, endRow: 1, endColumn: Number.NaN, rangeType: RANGE_TYPE.ROW },
primary: null,
@@ -137,13 +131,8 @@ describe('Test hide row col confirm commands', () => {
});
it('Will not apply when select all rows', async () => {
- const selectionManager = get(SelectionManagerService);
- selectionManager.setCurrentSelection({
- pluginName: NORMAL_SELECTION_PLUGIN_NAME,
- unitId: 'test',
- sheetId: 'sheet1',
- });
- selectionManager.add([
+ const selectionManager = get(SheetsSelectionsService);
+ selectionManager.addSelections([
{
range: { startRow: 0, startColumn: Number.NaN, endRow: 999, endColumn: Number.NaN, rangeType: RANGE_TYPE.ROW },
primary: null,
@@ -166,13 +155,8 @@ describe('Test hide row col confirm commands', () => {
describe('Hide col', () => {
it('Will apply when select some cols', async () => {
- const selectionManager = get(SelectionManagerService);
- selectionManager.setCurrentSelection({
- pluginName: NORMAL_SELECTION_PLUGIN_NAME,
- unitId: 'test',
- sheetId: 'sheet1',
- });
- selectionManager.add([
+ const selectionManager = get(SheetsSelectionsService);
+ selectionManager.addSelections([
{
range: { startRow: Number.NaN, startColumn: 1, endRow: Number.NaN, endColumn: 1, rangeType: RANGE_TYPE.COLUMN },
primary: null,
@@ -202,13 +186,8 @@ describe('Test hide row col confirm commands', () => {
});
it('Will not apply when select all cols', async () => {
- const selectionManager = get(SelectionManagerService);
- selectionManager.setCurrentSelection({
- pluginName: NORMAL_SELECTION_PLUGIN_NAME,
- unitId: 'test',
- sheetId: 'sheet1',
- });
- selectionManager.add([
+ const selectionManager = get(SheetsSelectionsService);
+ selectionManager.addSelections([
{
range: { startRow: Number.NaN, startColumn: 0, endRow: Number.NaN, endColumn: 19, rangeType: RANGE_TYPE.COLUMN },
primary: null,
diff --git a/packages/sheets-ui/src/commands/commands/__tests__/remove-row-col-confirm.command.spec.ts b/packages/sheets-ui/src/commands/commands/__tests__/remove-row-col-confirm.command.spec.ts
index c400946744..60eff500b9 100644
--- a/packages/sheets-ui/src/commands/commands/__tests__/remove-row-col-confirm.command.spec.ts
+++ b/packages/sheets-ui/src/commands/commands/__tests__/remove-row-col-confirm.command.spec.ts
@@ -18,16 +18,15 @@ import type { Univer } from '@univerjs/core';
import { ICommandService, IUniverInstanceService, LocaleService, RANGE_TYPE } from '@univerjs/core';
import {
AddWorksheetMergeMutation,
- NORMAL_SELECTION_PLUGIN_NAME,
RemoveColCommand,
RemoveColMutation,
RemoveRowCommand,
RemoveRowMutation,
RemoveWorksheetMergeCommand,
RemoveWorksheetMergeMutation,
- SelectionManagerService,
SetRangeValuesMutation,
SetSelectionsOperation,
+ SheetsSelectionsService,
} from '@univerjs/sheets';
import { type IConfirmPartMethodOptions, IConfirmService } from '@univerjs/ui';
import type { IDisposable, Injector } from '@wendellhu/redi';
@@ -101,13 +100,8 @@ describe('Test remove row col confirm commands', () => {
describe('Remove row', () => {
it('Will apply when select some rows', async () => {
- const selectionManager = get(SelectionManagerService);
- selectionManager.setCurrentSelection({
- pluginName: NORMAL_SELECTION_PLUGIN_NAME,
- unitId: 'test',
- sheetId: 'sheet1',
- });
- selectionManager.add([
+ const selectionManager = get(SheetsSelectionsService);
+ selectionManager.addSelections([
{
range: { startRow: 1, startColumn: Number.NaN, endRow: 1, endColumn: Number.NaN, rangeType: RANGE_TYPE.ROW },
primary: null,
@@ -128,13 +122,8 @@ describe('Test remove row col confirm commands', () => {
});
it('Will not apply when select all rows', async () => {
- const selectionManager = get(SelectionManagerService);
- selectionManager.setCurrentSelection({
- pluginName: NORMAL_SELECTION_PLUGIN_NAME,
- unitId: 'test',
- sheetId: 'sheet1',
- });
- selectionManager.add([
+ const selectionManager = get(SheetsSelectionsService);
+ selectionManager.addSelections([
{
range: { startRow: 0, startColumn: Number.NaN, endRow: 999, endColumn: Number.NaN, rangeType: RANGE_TYPE.ROW },
primary: null,
@@ -157,13 +146,8 @@ describe('Test remove row col confirm commands', () => {
describe('Remove col', () => {
it('Will apply when select some cols', async () => {
- const selectionManager = get(SelectionManagerService);
- selectionManager.setCurrentSelection({
- pluginName: NORMAL_SELECTION_PLUGIN_NAME,
- unitId: 'test',
- sheetId: 'sheet1',
- });
- selectionManager.add([
+ const selectionManager = get(SheetsSelectionsService);
+ selectionManager.addSelections([
{
range: { startRow: Number.NaN, startColumn: 1, endRow: Number.NaN, endColumn: 1, rangeType: RANGE_TYPE.COLUMN },
primary: null,
@@ -184,13 +168,8 @@ describe('Test remove row col confirm commands', () => {
});
it('Will not apply when select all cols', async () => {
- const selectionManager = get(SelectionManagerService);
- selectionManager.setCurrentSelection({
- pluginName: NORMAL_SELECTION_PLUGIN_NAME,
- unitId: 'test',
- sheetId: 'sheet1',
- });
- selectionManager.add([
+ const selectionManager = get(SheetsSelectionsService);
+ selectionManager.addSelections([
{
range: { startRow: Number.NaN, startColumn: 0, endRow: Number.NaN, endColumn: 19, rangeType: RANGE_TYPE.COLUMN },
primary: null,
diff --git a/packages/sheets-ui/src/commands/commands/__tests__/set-format-painter.command.spec.ts b/packages/sheets-ui/src/commands/commands/__tests__/set-format-painter.command.spec.ts
index 07de025ce5..48b66bfc97 100644
--- a/packages/sheets-ui/src/commands/commands/__tests__/set-format-painter.command.spec.ts
+++ b/packages/sheets-ui/src/commands/commands/__tests__/set-format-painter.command.spec.ts
@@ -29,14 +29,12 @@ import { IRenderManagerService } from '@univerjs/engine-render';
import type { ISelectionWithCoordAndStyle } from '@univerjs/sheets';
import {
AddWorksheetMergeMutation,
- NORMAL_SELECTION_PLUGIN_NAME,
RemoveWorksheetMergeMutation,
- SelectionManagerService,
SetRangeValuesCommand,
SetRangeValuesMutation,
SetSelectionsOperation,
} from '@univerjs/sheets';
-import type { Injector } from '@wendellhu/redi';
+import type { DependencyIdentifier, Injector } from '@wendellhu/redi';
import { BehaviorSubject } from 'rxjs';
import { beforeEach, describe, expect, it } from 'vitest';
@@ -49,7 +47,7 @@ import {
SetOnceFormatPainterCommand,
} from '../set-format-painter.command';
import { IMarkSelectionService } from '../../../services/mark-selection/mark-selection.service';
-import { ISelectionRenderService } from '../../../services/selection/selection-render.service';
+import { ISheetSelectionRenderService } from '../../../services/selection/base-selection-render.service';
import { createCommandTestBed } from './create-command-test-bed';
const theme = {
@@ -195,17 +193,6 @@ class MarkSelectionService extends Disposable implements IMarkSelectionService {
}
}
-class SelectionRenderService {
- private readonly _selectionMoveEnd$ = new BehaviorSubject<ISelectionWithCoordAndStyle[]>([]);
- readonly selectionMoveEnd$ = this._selectionMoveEnd$.asObservable();
-}
-
-class RenderManagerService {
- getRenderById(id: string) {
- return null;
- }
-}
-
describe('Test format painter rules in controller', () => {
let univer: Univer;
let get: Injector['get'];
@@ -214,16 +201,39 @@ describe('Test format painter rules in controller', () => {
let formatPainterController: FormatPainterController;
beforeEach(() => {
+ class SheetSelectionRenderService {
+ private readonly _selectionMoveEnd$ = new BehaviorSubject<ISelectionWithCoordAndStyle[]>([]);
+ readonly selectionMoveEnd$ = this._selectionMoveEnd$.asObservable();
+ }
+
const testBed = createCommandTestBed(TEST_WORKBOOK_DATA, [
[IMarkSelectionService, { useClass: MarkSelectionService }],
[IFormatPainterService, { useClass: FormatPainterService }],
- [ISelectionRenderService, { useClass: SelectionRenderService }],
- [IRenderManagerService, { useClass: RenderManagerService }],
+ [ISheetSelectionRenderService, { useClass: SheetSelectionRenderService }],
[FormatPainterController],
]);
+
univer = testBed.univer;
get = testBed.get;
+ class MockRenderManagerService {
+ getRenderById() {
+ return null;
+ }
+
+ getCurrentTypeOfRenderer() {
+ return {
+ with: <T>(identifier: DependencyIdentifier<T>) => {
+ return get(identifier);
+ },
+ };
+ }
+ }
+
+ const injector = univer.__getInjector();
+ // @ts-ignore
+ injector.add([IRenderManagerService, { useClass: MockRenderManagerService }]);
+
commandService = get(ICommandService);
themeService = get(ThemeService);
themeService.setTheme(theme);
@@ -238,13 +248,6 @@ describe('Test format painter rules in controller', () => {
commandService.registerCommand(SetRangeValuesMutation);
commandService.registerCommand(RemoveWorksheetMergeMutation);
commandService.registerCommand(AddWorksheetMergeMutation);
-
- const selectionManagerService = get(SelectionManagerService);
- selectionManagerService.setCurrentSelection({
- pluginName: NORMAL_SELECTION_PLUGIN_NAME,
- unitId: 'workbook-01',
- sheetId: 'sheet-0011',
- });
});
describe('format painter', () => {
@@ -255,7 +258,7 @@ describe('Test format painter rules in controller', () => {
await commandService.executeCommand(SetSelectionsOperation.id, {
unitId: 'workbook-01',
subUnitId: 'sheet-0011',
- pluginName: NORMAL_SELECTION_PLUGIN_NAME,
+
selections: [
{
range: {
@@ -310,7 +313,7 @@ describe('Test format painter rules in controller', () => {
await commandService.executeCommand(SetSelectionsOperation.id, {
unitId: 'workbook-01',
subUnitId: 'sheet-0011',
- pluginName: NORMAL_SELECTION_PLUGIN_NAME,
+
selections: [
{
range: {
diff --git a/packages/sheets-ui/src/commands/commands/__tests__/set-frozen.command.spec.ts b/packages/sheets-ui/src/commands/commands/__tests__/set-frozen.command.spec.ts
index 32d3621b1e..cf65c84813 100644
--- a/packages/sheets-ui/src/commands/commands/__tests__/set-frozen.command.spec.ts
+++ b/packages/sheets-ui/src/commands/commands/__tests__/set-frozen.command.spec.ts
@@ -16,7 +16,7 @@
import type { IFreeze, IWorkbookData, Univer, Workbook } from '@univerjs/core';
import { ICommandService, IUniverInstanceService, RANGE_TYPE, UniverInstanceType } from '@univerjs/core';
-import { NORMAL_SELECTION_PLUGIN_NAME, SelectionManagerService } from '@univerjs/sheets';
+import { SheetsSelectionsService } from '@univerjs/sheets';
import type { Injector } from '@wendellhu/redi';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
@@ -33,7 +33,7 @@ describe('Test commands used for change selections', () => {
let univer: Univer | null = null;
let get: Injector['get'];
let commandService: ICommandService;
- let selectionManagerService: SelectionManagerService;
+ let selectionManagerService: SheetsSelectionsService;
let scrollManagerService: ScrollManagerService;
const currentInfo = {
@@ -51,12 +51,7 @@ describe('Test commands used for change selections', () => {
isMerged: boolean,
isMergedMainCell: boolean
) {
- selectionManagerService.setCurrentSelection({
- pluginName: NORMAL_SELECTION_PLUGIN_NAME,
- ...currentInfo,
- });
-
- selectionManagerService.add([
+ selectionManagerService.addSelections([
{
range: { startRow, startColumn, endRow, endColumn, rangeType: RANGE_TYPE.NORMAL },
primary: {
@@ -102,11 +97,7 @@ describe('Test commands used for change selections', () => {
get = testBed.get;
commandService = get(ICommandService);
- selectionManagerService = get(SelectionManagerService);
- selectionManagerService.setCurrentSelection({
- pluginName: NORMAL_SELECTION_PLUGIN_NAME,
- ...currentInfo,
- });
+ selectionManagerService = get(SheetsSelectionsService);
scrollManagerService = get(ScrollManagerService);
scrollManagerService.setSearchParamAndRefresh({
...currentInfo,
diff --git a/packages/sheets-ui/src/commands/commands/__tests__/set-selections.command.spec.ts b/packages/sheets-ui/src/commands/commands/__tests__/set-selections.command.spec.ts
index 2d8e065920..833bdf779c 100644
--- a/packages/sheets-ui/src/commands/commands/__tests__/set-selections.command.spec.ts
+++ b/packages/sheets-ui/src/commands/commands/__tests__/set-selections.command.spec.ts
@@ -17,8 +17,6 @@
import type { IWorkbookData, Univer, Workbook } from '@univerjs/core';
import { Direction, ICommandService, IUniverInstanceService, RANGE_TYPE, UniverInstanceType } from '@univerjs/core';
import {
- NORMAL_SELECTION_PLUGIN_NAME,
- SelectionManagerService,
SetColHiddenCommand,
SetColHiddenMutation,
SetColVisibleMutation,
@@ -27,6 +25,7 @@ import {
SetRowVisibleMutation,
SetSelectedColsVisibleCommand,
SetSelectedRowsVisibleCommand,
+ SheetsSelectionsService,
} from '@univerjs/sheets';
import type { Injector } from '@wendellhu/redi';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
@@ -47,10 +46,10 @@ describe('Test commands used for change selections', () => {
let univer: Univer | null = null;
let get: Injector['get'];
let commandService: ICommandService;
- let selectionManagerService: SelectionManagerService;
+ let selectionManagerService: SheetsSelectionsService;
- function select00() {
- selectionManagerService.replace([
+ function selectTopLeft() {
+ selectionManagerService.setSelections([
{
range: { startRow: 0, startColumn: 0, endRow: 0, endColumn: 0, rangeType: RANGE_TYPE.NORMAL },
primary: {
@@ -78,13 +77,7 @@ describe('Test commands used for change selections', () => {
isMerged: boolean,
isMergedMainCell: boolean
) {
- selectionManagerService.setCurrentSelection({
- pluginName: NORMAL_SELECTION_PLUGIN_NAME,
- unitId: 'test',
- sheetId: 'sheet1',
- });
-
- selectionManagerService.add([
+ selectionManagerService.addSelections([
{
range: { startRow, startColumn, endRow, endColumn, rangeType: RANGE_TYPE.NORMAL },
primary: {
@@ -103,7 +96,7 @@ describe('Test commands used for change selections', () => {
}
function expectSelectionToBe(startRow: number, startColumn: number, endRow: number, endColumn: number) {
- expect(selectionManagerService.getLast()!.range).toEqual({
+ expect(selectionManagerService.getCurrentLastSelection()!.range).toEqual({
startRow,
startColumn,
endRow,
@@ -127,9 +120,9 @@ describe('Test commands used for change selections', () => {
}
function selectRow(rowStart: number, rowEnd: number): void {
- const selectionManagerService = get(SelectionManagerService);
+ const selectionManagerService = get(SheetsSelectionsService);
const endColumn = getColCount() - 1;
- selectionManagerService.add([
+ selectionManagerService.addSelections([
{
range: { startRow: rowStart, startColumn: 0, endColumn, endRow: rowEnd, rangeType: RANGE_TYPE.ROW },
primary: {
@@ -148,9 +141,9 @@ describe('Test commands used for change selections', () => {
}
function selectColumn(columnStart: number, columnEnd: number): void {
- const selectionManagerService = get(SelectionManagerService);
+ const selectionManagerService = get(SheetsSelectionsService);
const endRow = getRowCount() - 1;
- selectionManagerService.add([
+ selectionManagerService.addSelections([
{
range: {
startRow: 0,
@@ -185,12 +178,7 @@ describe('Test commands used for change selections', () => {
get = testBed.get;
commandService = get(ICommandService);
- selectionManagerService = get(SelectionManagerService);
- selectionManagerService.setCurrentSelection({
- pluginName: NORMAL_SELECTION_PLUGIN_NAME,
- unitId: 'test',
- sheetId: 'sheet1',
- });
+ selectionManagerService = get(SheetsSelectionsService);
}
afterEach(disposeTestBed);
@@ -199,7 +187,7 @@ describe('Test commands used for change selections', () => {
beforeEach(() => prepareTestBed());
it('Should move selection with command', async () => {
- select00();
+ selectTopLeft();
await commandService.executeCommand<IMoveSelectionCommandParams>(MoveSelectionCommand.id, {
direction: Direction.LEFT,
@@ -242,30 +230,30 @@ describe('Test commands used for change selections', () => {
});
selectRow(1, 1);
- await commandService.executeCommand(SetRowHiddenCommand.id);
+ expect(await commandService.executeCommand(SetRowHiddenCommand.id)).toBeTruthy();
selectColumn(1, 1);
- await commandService.executeCommand(SetColHiddenCommand.id);
+ expect(await commandService.executeCommand(SetColHiddenCommand.id)).toBeTruthy();
- select00();
+ selectTopLeft();
- await commandService.executeCommand<IMoveSelectionCommandParams>(MoveSelectionCommand.id, {
+ expect(await commandService.executeCommand<IMoveSelectionCommandParams>(MoveSelectionCommand.id, {
direction: Direction.RIGHT,
- });
+ })).toBeTruthy();
expectSelectionToBe(0, 2, 0, 2);
- await commandService.executeCommand<IMoveSelectionCommandParams>(MoveSelectionCommand.id, {
+ expect(await commandService.executeCommand<IMoveSelectionCommandParams>(MoveSelectionCommand.id, {
direction: Direction.DOWN,
- });
+ })).toBeTruthy();
expectSelectionToBe(2, 2, 2, 2);
- await commandService.executeCommand<IMoveSelectionCommandParams>(MoveSelectionCommand.id, {
+ expect(await commandService.executeCommand<IMoveSelectionCommandParams>(MoveSelectionCommand.id, {
direction: Direction.LEFT,
- });
+ })).toBeTruthy();
expectSelectionToBe(2, 0, 2, 0);
- await commandService.executeCommand<IMoveSelectionCommandParams>(MoveSelectionCommand.id, {
+ expect(await commandService.executeCommand<IMoveSelectionCommandParams>(MoveSelectionCommand.id, {
direction: Direction.UP,
- });
+ })).toBeTruthy();
expectSelectionToBe(0, 0, 0, 0);
});
});
@@ -281,7 +269,7 @@ describe('Test commands used for change selections', () => {
* When user clicks on C2 and move cursor left twice, A2 should not selected not A1.
*/
it('Should select merged cell and move to next cell', async () => {
- select00();
+ selectTopLeft();
await commandService.executeCommand<IMoveSelectionCommandParams>(MoveSelectionCommand.id, {
direction: Direction.LEFT,
@@ -319,7 +307,7 @@ describe('Test commands used for change selections', () => {
beforeEach(() => prepareTestBed(SELECTION_WITH_EMPTY_CELLS_DATA));
it('Works on move', async () => {
- select00();
+ selectTopLeft();
await commandService.executeCommand<IMoveSelectionCommandParams>(MoveSelectionCommand.id, {
direction: Direction.RIGHT,
@@ -357,7 +345,7 @@ describe('Test commands used for change selections', () => {
selectColumn(3, 10);
await commandService.executeCommand(SetColHiddenCommand.id);
- select00();
+ selectTopLeft();
await commandService.executeCommand<IMoveSelectionCommandParams>(MoveSelectionCommand.id, {
direction: Direction.RIGHT,
@@ -378,7 +366,7 @@ describe('Test commands used for change selections', () => {
beforeEach(() => prepareTestBed(SELECTION_WITH_EMPTY_CELLS_DATA));
it('Works on expand', async () => {
- select00();
+ selectTopLeft();
// expand
@@ -474,7 +462,7 @@ describe('Test commands used for change selections', () => {
beforeEach(() => prepareTestBed(SELECTION_WITH_EMPTY_CELLS_DATA));
it('Works on gap expand', async () => {
- select00();
+ selectTopLeft();
// expand
@@ -522,7 +510,7 @@ describe('Test commands used for change selections', () => {
beforeEach(() => prepareTestBed());
it('Should first select all neighbor cells, and then the whole sheet', async () => {
- select00();
+ selectTopLeft();
const unchangedPrimaryInfo = {
startRow: 0,
@@ -539,50 +527,50 @@ describe('Test commands used for change selections', () => {
loop: true,
expandToGapFirst: true,
});
- expect(selectionManagerService.getLast()!.range).toEqual({
+ expect(selectionManagerService.getCurrentLastSelection()!.range).toEqual({
startRow: 0,
startColumn: 0,
endRow: 1,
endColumn: 1,
rangeType: RANGE_TYPE.NORMAL,
});
- expect(selectionManagerService.getLast()!.primary).toEqual(unchangedPrimaryInfo);
+ expect(selectionManagerService.getCurrentLastSelection()!.primary).toEqual(unchangedPrimaryInfo);
await commandService.executeCommand<ISelectAllCommandParams>(SelectAllCommand.id, {
loop: true,
expandToGapFirst: true,
});
- expect(selectionManagerService.getLast()!.range).toEqual({
+ expect(selectionManagerService.getCurrentLastSelection()!.range).toEqual({
startRow: 0,
startColumn: 0,
endRow: 19,
endColumn: 19,
rangeType: RANGE_TYPE.ALL,
});
- expect(selectionManagerService.getLast()!.primary).toEqual(unchangedPrimaryInfo);
+ expect(selectionManagerService.getCurrentLastSelection()!.primary).toEqual(unchangedPrimaryInfo);
await commandService.executeCommand<ISelectAllCommandParams>(SelectAllCommand.id, {
loop: true,
expandToGapFirst: true,
});
- expect(selectionManagerService.getLast()!.range).toEqual({
+ expect(selectionManagerService.getCurrentLastSelection()!.range).toEqual({
startRow: 0,
startColumn: 0,
endRow: 0,
endColumn: 0,
rangeType: RANGE_TYPE.NORMAL,
});
- expect(selectionManagerService.getLast()!.primary).toEqual(unchangedPrimaryInfo);
+ expect(selectionManagerService.getCurrentLastSelection()!.primary).toEqual(unchangedPrimaryInfo);
});
it('Should directly select all if `expandToGapFirst` is false', async () => {
- select00();
+ selectTopLeft();
await commandService.executeCommand<ISelectAllCommandParams>(SelectAllCommand.id, {
loop: true,
expandToGapFirst: false,
});
- expect(selectionManagerService.getLast()!.range).toEqual({
+ expect(selectionManagerService.getCurrentLastSelection()!.range).toEqual({
startRow: 0,
startColumn: 0,
endRow: 19,
@@ -594,7 +582,7 @@ describe('Test commands used for change selections', () => {
loop: true,
expandToGapFirst: false,
});
- expect(selectionManagerService.getLast()!.range).toEqual({
+ expect(selectionManagerService.getCurrentLastSelection()!.range).toEqual({
startRow: 0,
startColumn: 0,
endRow: 0,
@@ -604,13 +592,13 @@ describe('Test commands used for change selections', () => {
});
it('Should not loop selection when `loop` is false', async () => {
- select00();
+ selectTopLeft();
await commandService.executeCommand<ISelectAllCommandParams>(SelectAllCommand.id, {
loop: false,
expandToGapFirst: false,
});
- expect(selectionManagerService.getLast()!.range).toEqual({
+ expect(selectionManagerService.getCurrentLastSelection()!.range).toEqual({
startRow: 0,
startColumn: 0,
endRow: 19,
@@ -622,7 +610,7 @@ describe('Test commands used for change selections', () => {
loop: false,
expandToGapFirst: false,
});
- expect(selectionManagerService.getLast()!.range).toEqual({
+ expect(selectionManagerService.getCurrentLastSelection()!.range).toEqual({
startRow: 0,
startColumn: 0,
endRow: 19,
@@ -639,7 +627,7 @@ describe('Test commands used for change selections', () => {
loop: true,
expandToGapFirst: true,
});
- expect(selectionManagerService.getLast()!.range).toEqual({
+ expect(selectionManagerService.getCurrentLastSelection()!.range).toEqual({
startRow: 0,
startColumn: 0,
endRow: 1,
diff --git a/packages/sheets-ui/src/commands/commands/add-worksheet-merge.command.ts b/packages/sheets-ui/src/commands/commands/add-worksheet-merge.command.ts
index 530270d7f2..2d77fef0fb 100644
--- a/packages/sheets-ui/src/commands/commands/add-worksheet-merge.command.ts
+++ b/packages/sheets-ui/src/commands/commands/add-worksheet-merge.command.ts
@@ -33,7 +33,7 @@ import {
AddWorksheetMergeMutation,
getAddMergeMutationRangeByType,
RemoveMergeUndoMutationFactory,
- RemoveWorksheetMergeMutation, SelectionManagerService,
+ RemoveWorksheetMergeMutation, SheetsSelectionsService,
} from '@univerjs/sheets';
import { IConfirmService } from '@univerjs/ui';
import type { IAccessor } from '@wendellhu/redi';
@@ -143,8 +143,8 @@ export const AddWorksheetMergeAllCommand: ICommand = {
id: 'sheet.command.add-worksheet-merge-all',
handler: async (accessor) => {
const commandService = accessor.get(ICommandService);
- const selectionManagerService = accessor.get(SelectionManagerService);
- const selections = selectionManagerService.getSelectionRanges();
+ const selectionManagerService = accessor.get(SheetsSelectionsService);
+ const selections = selectionManagerService.getCurrentSelections()?.map((s) => s.range);
const mergeableSelections = getMergeableSelectionsByType(MergeType.MergeAll, selections);
if (!mergeableSelections?.length) {
return false;
@@ -174,8 +174,8 @@ export const AddWorksheetMergeVerticalCommand: ICommand = {
id: 'sheet.command.add-worksheet-merge-vertical',
handler: async (accessor) => {
const commandService = accessor.get(ICommandService);
- const selectionManagerService = accessor.get(SelectionManagerService);
- const selections = selectionManagerService.getSelectionRanges();
+ const selectionManagerService = accessor.get(SheetsSelectionsService);
+ const selections = selectionManagerService.getCurrentSelections()?.map((s) => s.range);
const mergeableSelections = getMergeableSelectionsByType(MergeType.MergeVertical, selections);
if (!mergeableSelections?.length) {
return false;
@@ -206,8 +206,8 @@ export const AddWorksheetMergeHorizontalCommand: ICommand = {
id: 'sheet.command.add-worksheet-merge-horizontal',
handler: async (accessor) => {
const commandService = accessor.get(ICommandService);
- const selectionManagerService = accessor.get(SelectionManagerService);
- const selections = selectionManagerService.getSelectionRanges();
+ const selectionManagerService = accessor.get(SheetsSelectionsService);
+ const selections = selectionManagerService.getCurrentSelections()?.map((s) => s.range);
const mergeableSelections = getMergeableSelectionsByType(MergeType.MergeHorizontal, selections);
if (!mergeableSelections?.length) {
return false;
diff --git a/packages/sheets-ui/src/commands/commands/delete-range-move-left-confirm.command.ts b/packages/sheets-ui/src/commands/commands/delete-range-move-left-confirm.command.ts
index 251c366f6d..38f0ecef2b 100644
--- a/packages/sheets-ui/src/commands/commands/delete-range-move-left-confirm.command.ts
+++ b/packages/sheets-ui/src/commands/commands/delete-range-move-left-confirm.command.ts
@@ -16,7 +16,7 @@
import type { ICommand, IRange } from '@univerjs/core';
import { CommandType, ICommandService, IUniverInstanceService, LocaleService, Rectangle } from '@univerjs/core';
-import { DeleteRangeMoveLeftCommand, getSheetCommandTarget, SelectionManagerService } from '@univerjs/sheets';
+import { DeleteRangeMoveLeftCommand, getSheetCommandTarget, SheetsSelectionsService } from '@univerjs/sheets';
import { IConfirmService } from '@univerjs/ui';
export const DeleteRangeMoveLeftConfirmCommand: ICommand = {
@@ -26,10 +26,10 @@ export const DeleteRangeMoveLeftConfirmCommand: ICommand = {
const confirmService = accessor.get(IConfirmService);
const commandService = accessor.get(ICommandService);
const localeService = accessor.get(LocaleService);
- const selectionManagerService = accessor.get(SelectionManagerService);
+ const selectionManagerService = accessor.get(SheetsSelectionsService);
const univerInstanceService = accessor.get(IUniverInstanceService);
- const selection = selectionManagerService.getSelections();
+ const selection = selectionManagerService.getCurrentSelections();
if (!selection) {
return false;
}
diff --git a/packages/sheets-ui/src/commands/commands/delete-range-move-up-confirm.command.ts b/packages/sheets-ui/src/commands/commands/delete-range-move-up-confirm.command.ts
index 842786be37..d6b17a7fb8 100644
--- a/packages/sheets-ui/src/commands/commands/delete-range-move-up-confirm.command.ts
+++ b/packages/sheets-ui/src/commands/commands/delete-range-move-up-confirm.command.ts
@@ -16,7 +16,7 @@
import type { ICommand, IRange } from '@univerjs/core';
import { CommandType, ICommandService, IUniverInstanceService, LocaleService, Rectangle } from '@univerjs/core';
-import { DeleteRangeMoveUpCommand, getSheetCommandTarget, SelectionManagerService } from '@univerjs/sheets';
+import { DeleteRangeMoveUpCommand, getSheetCommandTarget, SheetsSelectionsService } from '@univerjs/sheets';
import { IConfirmService } from '@univerjs/ui';
export const DeleteRangeMoveUpConfirmCommand: ICommand = {
@@ -26,10 +26,10 @@ export const DeleteRangeMoveUpConfirmCommand: ICommand = {
const confirmService = accessor.get(IConfirmService);
const commandService = accessor.get(ICommandService);
const localeService = accessor.get(LocaleService);
- const selectionManagerService = accessor.get(SelectionManagerService);
+ const selectionManagerService = accessor.get(SheetsSelectionsService);
const univerInstanceService = accessor.get(IUniverInstanceService);
- const selection = selectionManagerService.getSelections();
+ const selection = selectionManagerService.getCurrentSelections();
if (!selection) return false;
const target = getSheetCommandTarget(univerInstanceService);
diff --git a/packages/sheets-ui/src/commands/commands/hide-row-col-confirm.command.ts b/packages/sheets-ui/src/commands/commands/hide-row-col-confirm.command.ts
index 9b22c06b05..44e38752d7 100644
--- a/packages/sheets-ui/src/commands/commands/hide-row-col-confirm.command.ts
+++ b/packages/sheets-ui/src/commands/commands/hide-row-col-confirm.command.ts
@@ -16,7 +16,7 @@
import type { ICommand } from '@univerjs/core';
import { CommandType, ICommandService, IUniverInstanceService, LocaleService } from '@univerjs/core';
-import { getSheetCommandTarget, SelectionManagerService, SetColHiddenCommand, SetRowHiddenCommand } from '@univerjs/sheets';
+import { getSheetCommandTarget, SetColHiddenCommand, SetRowHiddenCommand, SheetsSelectionsService } from '@univerjs/sheets';
import { IConfirmService } from '@univerjs/ui';
import type { IAccessor } from '@wendellhu/redi';
@@ -26,9 +26,9 @@ export const HideRowConfirmCommand: ICommand = {
id: 'sheet.command.hide-row-confirm',
type: CommandType.COMMAND,
handler: async (accessor: IAccessor) => {
- const selectionManagerService = accessor.get(SelectionManagerService);
+ const selectionManagerService = accessor.get(SheetsSelectionsService);
- const ranges = selectionManagerService.getSelections()?.map((s) => s.range);
+ const ranges = selectionManagerService.getCurrentSelections()?.map((s) => s.range);
if (!ranges?.length) return false;
const commandService = accessor.get(ICommandService);
@@ -66,9 +66,9 @@ export const HideColConfirmCommand: ICommand = {
id: 'sheet.command.hide-col-confirm',
type: CommandType.COMMAND,
handler: async (accessor: IAccessor) => {
- const selectionManagerService = accessor.get(SelectionManagerService);
+ const selectionManagerService = accessor.get(SheetsSelectionsService);
- const ranges = selectionManagerService.getSelections()?.map((s) => s.range);
+ const ranges = selectionManagerService.getCurrentSelections()?.map((s) => s.range);
if (!ranges?.length) {
return false;
}
diff --git a/packages/sheets-ui/src/commands/commands/insert-range-move-down-confirm.command.ts b/packages/sheets-ui/src/commands/commands/insert-range-move-down-confirm.command.ts
index 84309b1ab1..4b3ce45b16 100644
--- a/packages/sheets-ui/src/commands/commands/insert-range-move-down-confirm.command.ts
+++ b/packages/sheets-ui/src/commands/commands/insert-range-move-down-confirm.command.ts
@@ -16,7 +16,7 @@
import type { ICommand, IRange } from '@univerjs/core';
import { CommandType, ICommandService, IUniverInstanceService, LocaleService, Rectangle } from '@univerjs/core';
-import { getSheetCommandTarget, InsertRangeMoveDownCommand, SelectionManagerService } from '@univerjs/sheets';
+import { getSheetCommandTarget, InsertRangeMoveDownCommand, SheetsSelectionsService } from '@univerjs/sheets';
import { IConfirmService } from '@univerjs/ui';
export const InsertRangeMoveDownConfirmCommand: ICommand = {
@@ -26,10 +26,10 @@ export const InsertRangeMoveDownConfirmCommand: ICommand = {
const confirmService = accessor.get(IConfirmService);
const commandService = accessor.get(ICommandService);
const localeService = accessor.get(LocaleService);
- const selectionManagerService = accessor.get(SelectionManagerService);
+ const selectionManagerService = accessor.get(SheetsSelectionsService);
const univerInstanceService = accessor.get(IUniverInstanceService);
- const selection = selectionManagerService.getSelections();
+ const selection = selectionManagerService.getCurrentSelections();
if (!selection) {
return false;
}
diff --git a/packages/sheets-ui/src/commands/commands/insert-range-move-right-confirm.command.ts b/packages/sheets-ui/src/commands/commands/insert-range-move-right-confirm.command.ts
index 533a6b4e66..d00fb2b090 100644
--- a/packages/sheets-ui/src/commands/commands/insert-range-move-right-confirm.command.ts
+++ b/packages/sheets-ui/src/commands/commands/insert-range-move-right-confirm.command.ts
@@ -16,7 +16,7 @@
import type { ICommand, IRange } from '@univerjs/core';
import { CommandType, ICommandService, IUniverInstanceService, LocaleService, Rectangle } from '@univerjs/core';
-import { getSheetCommandTarget, InsertRangeMoveRightCommand, SelectionManagerService } from '@univerjs/sheets';
+import { getSheetCommandTarget, InsertRangeMoveRightCommand, SheetsSelectionsService } from '@univerjs/sheets';
import { IConfirmService } from '@univerjs/ui';
export const InsertRangeMoveRightConfirmCommand: ICommand = {
@@ -26,10 +26,10 @@ export const InsertRangeMoveRightConfirmCommand: ICommand = {
const confirmService = accessor.get(IConfirmService);
const commandService = accessor.get(ICommandService);
const localeService = accessor.get(LocaleService);
- const selectionManagerService = accessor.get(SelectionManagerService);
+ const selectionManagerService = accessor.get(SheetsSelectionsService);
const univerInstanceService = accessor.get(IUniverInstanceService);
- const selection = selectionManagerService.getSelections();
+ const selection = selectionManagerService.getCurrentSelections();
if (!selection) {
return false;
}
diff --git a/packages/sheets-ui/src/commands/commands/range-protection.command.ts b/packages/sheets-ui/src/commands/commands/range-protection.command.ts
index fdedc56921..5b5681ea28 100644
--- a/packages/sheets-ui/src/commands/commands/range-protection.command.ts
+++ b/packages/sheets-ui/src/commands/commands/range-protection.command.ts
@@ -17,7 +17,7 @@
import type { ICommand, Workbook } from '@univerjs/core';
import { CommandType, ICommandService, IUndoRedoService, IUniverInstanceService, Rectangle, sequenceExecute, UniverInstanceType } from '@univerjs/core';
import type { IRangeProtectionRule } from '@univerjs/sheets';
-import { AddRangeProtectionMutation, AddWorksheetProtectionMutation, DeleteRangeProtectionMutation, DeleteWorksheetProtectionMutation, RangeProtectionRuleModel, SelectionManagerService, SetRangeProtectionMutation, SetWorksheetProtectionMutation, WorksheetProtectionRuleModel } from '@univerjs/sheets';
+import { AddRangeProtectionMutation, AddWorksheetProtectionMutation, DeleteRangeProtectionMutation, DeleteWorksheetProtectionMutation, RangeProtectionRuleModel, SetRangeProtectionMutation, SetWorksheetProtectionMutation, SheetsSelectionsService, WorksheetProtectionRuleModel } from '@univerjs/sheets';
import { UnitObject } from '@univerjs/protocol';
import type { IPermissionPanelRule } from '../../services/permission/sheet-permission-panel.model';
import { SheetPermissionPanelModel } from '../../services/permission/sheet-permission-panel.model';
@@ -228,7 +228,7 @@ export const DeleteRangeProtectionFromContextMenuCommand: ICommand = {
const commandService = accessor.get(ICommandService);
const univerInstanceService = accessor.get(IUniverInstanceService);
const undoRedoService = accessor.get(IUndoRedoService);
- const selectionManagerService = accessor.get(SelectionManagerService);
+ const selectionManagerService = accessor.get(SheetsSelectionsService);
const worksheetRuleModel = accessor.get(WorksheetProtectionRuleModel);
const workbook = univerInstanceService.getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET)!;
@@ -240,7 +240,7 @@ export const DeleteRangeProtectionFromContextMenuCommand: ICommand = {
if (worksheetRule?.permissionId && worksheetRule?.name) {
return commandService.executeCommand(DeleteWorksheetProtectionCommand.id, { unitId, subUnitId, rule: worksheetRule });
} else {
- const selectRange = selectionManagerService.getLast()?.range;
+ const selectRange = selectionManagerService.getCurrentLastSelection()?.range;
if (!selectRange) {
return false;
}
@@ -280,7 +280,7 @@ export const SetRangeProtectionFromContextMenuCommand: ICommand = {
async handler(accessor) {
const commandService = accessor.get(ICommandService);
const univerInstanceService = accessor.get(IUniverInstanceService);
- const selectionManagerService = accessor.get(SelectionManagerService);
+ const selectionManagerService = accessor.get(SheetsSelectionsService);
const worksheetRuleModel = accessor.get(WorksheetProtectionRuleModel);
const workbook = univerInstanceService.getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET)!;
const worksheet = workbook.getActiveSheet()!;
@@ -300,7 +300,7 @@ export const SetRangeProtectionFromContextMenuCommand: ICommand = {
await commandService.executeCommand(SheetPermissionOpenPanelOperation.id, { showDetail: true });
return true;
} else {
- const selectRange = selectionManagerService.getLast()?.range;
+ const selectRange = selectionManagerService.getCurrentLastSelection()?.range;
if (!selectRange) {
return false;
}
diff --git a/packages/sheets-ui/src/commands/commands/remove-row-col-confirm.command.ts b/packages/sheets-ui/src/commands/commands/remove-row-col-confirm.command.ts
index dcdbc1745c..6e3ab2b984 100644
--- a/packages/sheets-ui/src/commands/commands/remove-row-col-confirm.command.ts
+++ b/packages/sheets-ui/src/commands/commands/remove-row-col-confirm.command.ts
@@ -17,7 +17,7 @@
import type { ICommand } from '@univerjs/core';
import { CommandType, ICommandService, IUniverInstanceService, LocaleService } from '@univerjs/core';
import type { IRemoveRowColCommandParams } from '@univerjs/sheets';
-import { getSheetCommandTarget, RemoveColCommand, RemoveRowCommand, SelectionManagerService } from '@univerjs/sheets';
+import { getSheetCommandTarget, RemoveColCommand, RemoveRowCommand, SheetsSelectionsService } from '@univerjs/sheets';
import { IConfirmService } from '@univerjs/ui';
import type { IAccessor } from '@wendellhu/redi';
@@ -27,11 +27,11 @@ export const RemoveRowConfirmCommand: ICommand = {
id: 'sheet.command.remove-row-confirm',
type: CommandType.COMMAND,
handler: async (accessor: IAccessor, params?: IRemoveRowColCommandParams) => {
- const selectionManagerService = accessor.get(SelectionManagerService);
+ const selectionManagerService = accessor.get(SheetsSelectionsService);
let range = params?.range;
if (!range) {
- range = selectionManagerService.getLast()?.range;
+ range = selectionManagerService.getCurrentLastSelection()?.range;
}
if (!range) {
return false;
@@ -72,11 +72,11 @@ export const RemoveColConfirmCommand: ICommand = {
id: 'sheet.command.remove-col-confirm',
type: CommandType.COMMAND,
handler: async (accessor: IAccessor, params?: IRemoveRowColCommandParams) => {
- const selectionManagerService = accessor.get(SelectionManagerService);
+ const selectionManagerService = accessor.get(SheetsSelectionsService);
let range = params?.range;
if (!range) {
- range = selectionManagerService.getLast()?.range;
+ range = selectionManagerService.getCurrentLastSelection()?.range;
}
if (!range) {
return false;
diff --git a/packages/sheets-ui/src/commands/commands/set-frozen.command.ts b/packages/sheets-ui/src/commands/commands/set-frozen.command.ts
index 7023a78f48..2c190a7e9b 100644
--- a/packages/sheets-ui/src/commands/commands/set-frozen.command.ts
+++ b/packages/sheets-ui/src/commands/commands/set-frozen.command.ts
@@ -17,7 +17,7 @@
import type { ICommand } from '@univerjs/core';
import { CommandType, ICommandService, IUndoRedoService, IUniverInstanceService, RANGE_TYPE } from '@univerjs/core';
import type { ISetFrozenMutationParams } from '@univerjs/sheets';
-import { getSheetCommandTarget, SelectionManagerService, SetFrozenMutation, SetFrozenMutationFactory } from '@univerjs/sheets';
+import { getSheetCommandTarget, SetFrozenMutation, SetFrozenMutationFactory, SheetsSelectionsService } from '@univerjs/sheets';
import { ScrollManagerService } from '../../services/scroll-manager.service';
@@ -43,8 +43,8 @@ export const SetSelectionFrozenCommand: ICommand<ISetSelectionFrozenCommandParam
const { unitId, subUnitId } = target;
const commandService = accessor.get(ICommandService);
- const selectionManagerService = accessor.get(SelectionManagerService);
- const selections = selectionManagerService.getSelections();
+ const selectionManagerService = accessor.get(SheetsSelectionsService);
+ const selections = selectionManagerService.getCurrentSelections();
if (!selections) {
return false;
}
diff --git a/packages/sheets-ui/src/commands/commands/set-selection.command.ts b/packages/sheets-ui/src/commands/commands/set-selection.command.ts
index c40daddc9a..096c98d825 100644
--- a/packages/sheets-ui/src/commands/commands/set-selection.command.ts
+++ b/packages/sheets-ui/src/commands/commands/set-selection.command.ts
@@ -18,9 +18,8 @@ import type { Direction, ICommand, IRange } from '@univerjs/core';
import { CommandType, ICommandService, IUniverInstanceService, RANGE_TYPE, Rectangle, Tools } from '@univerjs/core';
import {
getCellAtRowCol,
+ getSelectionsService,
getSheetCommandTarget,
- NORMAL_SELECTION_PLUGIN_NAME,
- SelectionManagerService,
SetSelectionsOperation,
} from '@univerjs/sheets';
import { KeyCode } from '@univerjs/ui';
@@ -69,7 +68,7 @@ export const MoveSelectionCommand: ICommand<IMoveSelectionCommandParams> = {
if (!target) return false;
const { workbook, worksheet } = target;
- const selection = accessor.get(SelectionManagerService).getLast();
+ const selection = getSelectionsService(accessor).getCurrentLastSelection();
if (!selection) {
return false;
}
@@ -100,7 +99,7 @@ export const MoveSelectionCommand: ICommand<IMoveSelectionCommandParams> = {
return accessor.get(ICommandService).executeCommand(SetSelectionsOperation.id, {
unitId: workbook.getUnitId(),
subUnitId: worksheet.getSheetId(),
- pluginName: NORMAL_SELECTION_PLUGIN_NAME,
+
selections: [
{
range: Rectangle.clone(destRange),
@@ -142,7 +141,7 @@ export const MoveSelectionEnterAndTabCommand: ICommand<IMoveSelectionEnterAndTab
const { workbook, worksheet } = target;
- const selection = accessor.get(SelectionManagerService).getLast();
+ const selection = getSelectionsService(accessor).getCurrentLastSelection();
if (!selection) {
return false;
}
@@ -262,7 +261,7 @@ export const MoveSelectionEnterAndTabCommand: ICommand<IMoveSelectionEnterAndTab
return accessor.get(ICommandService).executeCommand(SetSelectionsOperation.id, {
unitId,
subUnitId: sheetId,
- pluginName: NORMAL_SELECTION_PLUGIN_NAME,
+
selections: [resultRange],
});
},
@@ -287,7 +286,7 @@ export const ExpandSelectionCommand: ICommand<IExpandSelectionCommandParams> = {
const { worksheet, unitId, subUnitId } = target;
- const selection = accessor.get(SelectionManagerService).getLast();
+ const selection = getSelectionsService(accessor).getCurrentLastSelection();
if (!selection) return false;
const { range: startRange, primary } = selection;
@@ -314,7 +313,7 @@ export const ExpandSelectionCommand: ICommand<IExpandSelectionCommandParams> = {
return accessor.get(ICommandService).executeCommand(SetSelectionsOperation.id, {
unitId,
subUnitId,
- pluginName: NORMAL_SELECTION_PLUGIN_NAME,
+
selections: [
{
range: destRange,
@@ -345,7 +344,7 @@ export const SelectAllCommand: ICommand<ISelectAllCommandParams> = {
SELECTED_RANGE_WORKSHEET = '';
},
handler: async (accessor, params = { expandToGapFirst: true, loop: false }) => {
- const selection = accessor.get(SelectionManagerService).getLast();
+ const selection = getSelectionsService(accessor).getCurrentLastSelection();
const target = getSheetCommandTarget(accessor.get(IUniverInstanceService));
if (!target) return false;
@@ -407,7 +406,7 @@ export const SelectAllCommand: ICommand<ISelectAllCommandParams> = {
return accessor.get(ICommandService).executeCommand(SetSelectionsOperation.id, {
unitId,
subUnitId,
- pluginName: NORMAL_SELECTION_PLUGIN_NAME,
+
selections: [
{
range: destRange,
diff --git a/packages/sheets-ui/src/controllers/auto-fill.controller.ts b/packages/sheets-ui/src/controllers/auto-fill.controller.ts
index d6ebce8dab..6105390047 100644
--- a/packages/sheets-ui/src/controllers/auto-fill.controller.ts
+++ b/packages/sheets-ui/src/controllers/auto-fill.controller.ts
@@ -30,7 +30,7 @@ import {
Tools,
UniverInstanceType,
} from '@univerjs/core';
-import { DeviceInputEventType } from '@univerjs/engine-render';
+import { DeviceInputEventType, IRenderManagerService } from '@univerjs/engine-render';
import type {
IAddWorksheetMergeMutationParams,
IRemoveSheetMutationParams,
@@ -46,13 +46,11 @@ import {
MoveColsMutation,
MoveRangeMutation,
MoveRowsMutation,
- NORMAL_SELECTION_PLUGIN_NAME,
RemoveColMutation,
RemoveMergeUndoMutationFactory,
RemoveRowMutation,
RemoveSheetMutation,
RemoveWorksheetMergeMutation,
- SelectionManagerService,
SetRangeValuesCommand,
SetRangeValuesMutation,
SetRangeValuesUndoMutationFactory,
@@ -77,10 +75,10 @@ import type {
} from '../services/auto-fill/type';
import { APPLY_TYPE, AutoFillHookType, DATA_TYPE } from '../services/auto-fill/type';
import { IEditorBridgeService } from '../services/editor-bridge.service';
-import { ISelectionRenderService } from '../services/selection/selection-render.service';
import { SetCellEditVisibleOperation } from '../commands/operations/cell-edit.operation';
import { SetZoomRatioOperation } from '../commands/operations/set-zoom-ratio.operation';
import { SheetsRenderService } from '../services/sheets-render.service';
+import { ISheetSelectionRenderService } from '../services/selection/base-selection-render.service';
import type { IDiscreteRange } from './utils/range-tools';
import { discreteRangeToRange, generateNullCellValueRowCol, rangeToDiscreteRange } from './utils/range-tools';
@@ -93,11 +91,10 @@ export class AutoFillController extends Disposable {
private _defaultHook: ISheetAutoFillHook;
constructor(
@IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService,
- @ISelectionRenderService private readonly _selectionRenderService: ISelectionRenderService,
@ICommandService private readonly _commandService: ICommandService,
@IAutoFillService private readonly _autoFillService: IAutoFillService,
@IEditorBridgeService private readonly _editorBridgeService: IEditorBridgeService,
- @Inject(SelectionManagerService) private readonly _selectionManagerService: SelectionManagerService,
+ @IRenderManagerService private readonly _renderManagerService: IRenderManagerService,
@Inject(Injector) private readonly _injector: Injector,
@Inject(SheetsRenderService) private _sheetsRenderService: SheetsRenderService
) {
@@ -156,7 +153,7 @@ export class AutoFillController extends Disposable {
}
if (command.id === RemoveSheetMutation.id) {
if ((command.params as IRemoveSheetMutationParams).unitId === this._currentLocation?.unitId &&
- (command.params as IRemoveSheetMutationParams).subUnitId === this._currentLocation?.subUnitId) {
+ (command.params as IRemoveSheetMutationParams).subUnitId === this._currentLocation?.subUnitId) {
this._quit();
}
}
@@ -175,33 +172,28 @@ export class AutoFillController extends Disposable {
this._autoFillService.setShowMenu(false);
}
- // eslint-disable-next-line max-lines-per-function
+ // eslint-disable-next-line max-lines-per-function
private _onSelectionControlFillChanged() {
const disposableCollection = new DisposableCollection();
const addListener = (disposableCollection: DisposableCollection) => {
- /**
- * Auto fill only responds to regular selections;
- * it does not apply to selections for features like formulas or charts.
- */
- const current = this._selectionManagerService.getCurrent();
- if (current?.pluginName !== NORMAL_SELECTION_PLUGIN_NAME) {
- return;
- }
-
- // Each range change requires re-listening
+ // Each range change requires re-listening
disposableCollection.dispose();
- const selectionControls = this._selectionRenderService.getSelectionControls();
+ const currentRenderer = this._renderManagerService.getCurrentTypeOfRenderer(UniverInstanceType.UNIVER_SHEET);
+ if (!currentRenderer) return;
+
+ const selectionRenderService = currentRenderer.with(ISheetSelectionRenderService);
+ const selectionControls = selectionRenderService.getSelectionControls();
selectionControls.forEach((controlSelection) => {
disposableCollection.add(
toDisposable(
controlSelection.selectionFilled$.subscribe((filled) => {
if (
filled == null ||
- filled.startColumn === -1 ||
- filled.startRow === -1 ||
- filled.endColumn === -1 ||
- filled.endRow === -1
+ filled.startColumn === -1 ||
+ filled.startRow === -1 ||
+ filled.endColumn === -1 ||
+ filled.endRow === -1
) {
return;
}
@@ -223,8 +215,8 @@ export class AutoFillController extends Disposable {
)
);
- // double click to fill range, range length will align to left or right column.
- // fill results will be as same as drag operation
+ // double click to fill range, range length will align to left or right column.
+ // fill results will be as same as drag operation
disposableCollection.add(
toDisposable(
controlSelection.fillControl.onDblclick$.subscribeEvent(() => {
@@ -266,7 +258,7 @@ export class AutoFillController extends Disposable {
);
}
- // refill when apply type changed
+ // refill when apply type changed
private _onApplyTypeChanged() {
this.disposeWithMe(
toDisposable(
@@ -277,18 +269,18 @@ export class AutoFillController extends Disposable {
);
}
- // eslint-disable-next-line max-lines-per-function
+ // eslint-disable-next-line max-lines-per-function
private _triggerAutoFill(source: IRange, selection: IRange) {
- // if source range === dest range, do nothing;
+ // if source range === dest range, do nothing;
if (
source.startColumn === selection.startColumn &&
- source.startRow === selection.startRow &&
- source.endColumn === selection.endColumn &&
- source.endRow === selection.endRow
+ source.startRow === selection.startRow &&
+ source.endColumn === selection.endColumn &&
+ source.endRow === selection.endRow
) {
return;
}
- // situation 1: drag to smaller range, horizontally.
+ // situation 1: drag to smaller range, horizontally.
if (selection.endColumn < source.endColumn && selection.endColumn > source.startColumn) {
this._commandService.executeCommand(AutoClearContentCommand.id, {
clearRange: {
@@ -301,7 +293,7 @@ export class AutoFillController extends Disposable {
});
return;
}
- // situation 2: drag to smaller range, vertically.
+ // situation 2: drag to smaller range, vertically.
if (selection.endRow < source.endRow && selection.endRow > source.startRow) {
this._commandService.executeCommand(AutoClearContentCommand.id, {
clearRange: {
@@ -314,9 +306,9 @@ export class AutoFillController extends Disposable {
});
return;
}
- // situation 3: drag to larger range, expand to fill
+ // situation 3: drag to larger range, expand to fill
- // save ranges
+ // save ranges
const target = {
startRow: selection.startRow,
endRow: selection.endRow,
@@ -390,11 +382,11 @@ export class AutoFillController extends Disposable {
private _handleDbClickFill(source: IRange) {
const selection = this._detectFillRange(source);
- // double click only works when dest range is longer than source range
+ // double click only works when dest range is longer than source range
if (selection.endRow <= source.endRow) {
return;
}
- // double click effect is the same as drag effect, but the apply area is automatically calculated (by method '_detectFillRange')
+ // double click effect is the same as drag effect, but the apply area is automatically calculated (by method '_detectFillRange')
this._triggerAutoFill(source, selection);
}
@@ -408,7 +400,7 @@ export class AutoFillController extends Disposable {
const maxRow = worksheet.getMaxRows() - 1;
const maxColumn = worksheet.getMaxColumns() - 1;
let detectEndRow = endRow;
- // left column first, or consider right column.
+ // left column first, or consider right column.
if (startColumn > 0 && matrix.getValue(startRow, startColumn - 1)?.v != null) {
let cur = startRow;
while (matrix.getValue(cur, startColumn - 1)?.v != null && cur < maxRow) {
@@ -447,7 +439,7 @@ export class AutoFillController extends Disposable {
this._commandService.executeCommand(AutoFillCommand.id, { unitId: this._currentLocation?.unitId, subUnitId: this._currentLocation?.subUnitId });
}
- // calc apply data according to copy data and direction
+ // calc apply data according to copy data and direction
private _getApplyData(
copyDataPiece: ICopyDataPiece,
csLen: number,
@@ -472,15 +464,15 @@ export class AutoFillController extends Disposable {
applyDataInTypes[r.type] = [];
});
- // calc cell data to apply
+ // calc cell data to apply
rules.forEach((r) => {
const { type, applyFunctions: customApplyFunctions = {} } = r;
const copyDataInType = copyDataPiece[type];
if (!copyDataInType) {
return;
}
- // copyDataInType is an array of copy-squads in same types
- // a copy-squad is an array of continuous cells that has the same type, e.g. [1, 3, 5] is a copy squad, but [1, 3, ab, 5] will be divided into two copy-squads
+ // copyDataInType is an array of copy-squads in same types
+ // a copy-squad is an array of continuous cells that has the same type, e.g. [1, 3, 5] is a copy squad, but [1, 3, ab, 5] will be divided into two copy-squads
copyDataInType.forEach((copySquad) => {
const s = getLenS(copySquad.index, rsd);
const len = copySquad.index.length * num + s;
@@ -497,7 +489,7 @@ export class AutoFillController extends Disposable {
});
});
- // calc index
+ // calc index
for (let x = 0; x < asLen; x++) {
rules.forEach((r) => {
const { type } = r;
@@ -524,7 +516,7 @@ export class AutoFillController extends Disposable {
const { data } = copySquad;
const isReverse = direction === Direction.UP || direction === Direction.LEFT;
- // according to applyType, apply functions. if customApplyFunctions is provided, use it instead of default apply functions
+ // according to applyType, apply functions. if customApplyFunctions is provided, use it instead of default apply functions
if (applyType === APPLY_TYPE.COPY) {
const custom = customApplyFunctions?.[APPLY_TYPE.COPY];
if (custom) {
@@ -539,7 +531,7 @@ export class AutoFillController extends Disposable {
return custom(copySquad, len, direction, copyDataPiece);
}
isReverse && data.reverse();
- // special rules, if not provide custom SERIES apply functions, will be applied as copy
+ // special rules, if not provide custom SERIES apply functions, will be applied as copy
if (customApplyFunctions?.[APPLY_TYPE.COPY]) {
return customApplyFunctions[APPLY_TYPE.COPY](copySquad, len, direction, copyDataPiece);
}
@@ -582,7 +574,7 @@ export class AutoFillController extends Disposable {
};
aArray.forEach((a) => {
- // a copyDataPiece is an array of original cells in same column or row, depending on direction (horizontal or vertical)
+ // a copyDataPiece is an array of original cells in same column or row, depending on direction (horizontal or vertical)
const copyDataPiece = this._getEmptyCopyDataPiece();
const prevData: IRuleConfirmedData = {
type: undefined,
@@ -713,7 +705,7 @@ export class AutoFillController extends Disposable {
private _presetAndCacheData(location: IAutoFillLocation, direction: Direction) {
const { source, target } = location;
- // cache original data of apply range
+ // cache original data of apply range
const worksheet = this._univerInstanceService
.getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET)!
.getActiveSheet();
@@ -723,7 +715,7 @@ export class AutoFillController extends Disposable {
}
const currentCellDatas = worksheet.getCellMatrix();
- // cache the original data in currentCellDatas in apply range for later use / refill
+ // cache the original data in currentCellDatas in apply range for later use / refill
const applyData: Nullable<ICellData>[][] = [];
target.rows.forEach((i) => {
const row: Nullable<ICellData>[] = [];
@@ -744,8 +736,8 @@ export class AutoFillController extends Disposable {
return this._getPreferredApplyType(this._copyData);
}
- // auto fill entry
- // eslint-disable-next-line max-lines-per-function
+ // auto fill entry
+ // eslint-disable-next-line max-lines-per-function
private _fillData(location: IAutoFillLocation, direction: Direction, applyType: APPLY_TYPE) {
const undos: IMutationInfo[] = [];
const redos: IMutationInfo[] = [];
@@ -817,7 +809,7 @@ export class AutoFillController extends Disposable {
});
}
- // deal with styles
+ // deal with styles
let applyMergeRanges: IRange[] = [];
const style = this._univerInstanceService.getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET)!.getStyles();
if (hasStyle) {
@@ -858,7 +850,7 @@ export class AutoFillController extends Disposable {
const accessor = {
get: this._injector.get.bind(this._injector),
};
- // delete cross merge
+ // delete cross merge
const deleteMergeRanges: IRange[] = [];
const mergeData = this._univerInstanceService
.getUniverSheetInstance(unitId)
@@ -886,7 +878,7 @@ export class AutoFillController extends Disposable {
undos.push({ id: AddWorksheetMergeMutation.id, params: undoRemoveMergeMutationParams });
}
- // clear range value
+ // clear range value
const clearMutationParams: ISetRangeValuesMutationParams = {
subUnitId,
unitId,
@@ -897,11 +889,11 @@ export class AutoFillController extends Disposable {
clearMutationParams
);
- // const intercepted = this._sheetInterceptorService.onCommandExecute({ id: ClearSelectionContentCommand.id });
+ // const intercepted = this._sheetInterceptorService.onCommandExecute({ id: ClearSelectionContentCommand.id });
redos.push({ id: SetRangeValuesMutation.id, params: clearMutationParams });
undos.push({ id: SetRangeValuesMutation.id, params: undoClearMutationParams });
- // set range value
+ // set range value
const cellValue = new ObjectMatrix<ICellData>();
targetRows.forEach((row, rowIndex) => {
targetCols.forEach((col, colIndex) => {
@@ -925,7 +917,7 @@ export class AutoFillController extends Disposable {
undos.push({ id: SetRangeValuesMutation.id, params: undoSetRangeValuesMutationParams });
redos.push({ id: SetRangeValuesMutation.id, params: setRangeValuesMutationParams });
- // add worksheet merge
+ // add worksheet merge
if (applyMergeRanges?.length) {
const ranges = getAddMergeMutationRangeByType(applyMergeRanges);
diff --git a/packages/sheets-ui/src/controllers/auto-height.controller.ts b/packages/sheets-ui/src/controllers/auto-height.controller.ts
index ae9b988781..3aefc637b6 100644
--- a/packages/sheets-ui/src/controllers/auto-height.controller.ts
+++ b/packages/sheets-ui/src/controllers/auto-height.controller.ts
@@ -23,13 +23,13 @@ import type {
ISetWorksheetRowIsAutoHeightMutationParams,
} from '@univerjs/sheets';
import {
- SelectionManagerService,
SetRangeValuesCommand,
SetStyleCommand,
SetWorksheetRowAutoHeightMutation,
SetWorksheetRowAutoHeightMutationFactory,
SetWorksheetRowIsAutoHeightCommand,
SheetInterceptorService,
+ SheetsSelectionsService,
} from '@univerjs/sheets';
import { Inject, Injector } from '@wendellhu/redi';
import type { RenderManagerService } from '@univerjs/engine-render';
@@ -42,7 +42,7 @@ export class AutoHeightController extends Disposable {
@IRenderManagerService private readonly _renderManagerService: RenderManagerService,
@Inject(Injector) private readonly _injector: Injector,
@Inject(SheetInterceptorService) private readonly _sheetInterceptorService: SheetInterceptorService,
- @Inject(SelectionManagerService) private readonly _selectionManagerService: SelectionManagerService,
+ @Inject(SheetsSelectionsService) private readonly _selectionManagerService: SheetsSelectionsService,
@Inject(IUniverInstanceService) private readonly _univerInstanceService: IUniverInstanceService
) {
super();
@@ -146,7 +146,7 @@ export class AutoHeightController extends Disposable {
};
}
- const selections = selectionManagerService.getSelectionRanges();
+ const selections = selectionManagerService.getCurrentSelections()?.map((s) => s.range);
if (!selections?.length) {
return {
diff --git a/packages/sheets-ui/src/controllers/clipboard/utils.ts b/packages/sheets-ui/src/controllers/clipboard/utils.ts
index 9eb8973989..e9b40ec971 100644
--- a/packages/sheets-ui/src/controllers/clipboard/utils.ts
+++ b/packages/sheets-ui/src/controllers/clipboard/utils.ts
@@ -29,7 +29,6 @@ import {
getAddMergeMutationRangeByType,
MoveRangeCommand,
MoveRangeMutation,
- NORMAL_SELECTION_PLUGIN_NAME,
RemoveMergeUndoMutationFactory,
RemoveWorksheetMergeMutation,
SetRangeValuesMutation,
@@ -251,7 +250,7 @@ export function getMoveRangeMutations(
params: {
unitId,
subUnitId: toSubUnitId,
- pluginName: NORMAL_SELECTION_PLUGIN_NAME,
+
selections: [{ range: toRange }],
} as ISetSelectionsOperationParams,
},
@@ -265,7 +264,7 @@ export function getMoveRangeMutations(
params: {
unitId,
sheetId: fromSubUnitId,
- pluginName: NORMAL_SELECTION_PLUGIN_NAME,
+
selections: [{ range: fromRange }],
},
},
diff --git a/packages/sheets-ui/src/controllers/defined-name/defined-name.controller.ts b/packages/sheets-ui/src/controllers/defined-name/defined-name.controller.ts
new file mode 100644
index 0000000000..9a12dffe44
--- /dev/null
+++ b/packages/sheets-ui/src/controllers/defined-name/defined-name.controller.ts
@@ -0,0 +1,147 @@
+/**
+ * Copyright 2023-present DreamNum Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { Workbook } from '@univerjs/core';
+import { Disposable, ICommandService, IUniverInstanceService, LifecycleStages, OnLifecycle, ThemeService, UniverInstanceType } from '@univerjs/core';
+import { deserializeRangeWithSheet, IDefinedNamesService, isReferenceStrings, operatorToken } from '@univerjs/engine-formula';
+import type { ISelectionWithStyle } from '@univerjs/sheets';
+import { getNormalSelectionStyle, getPrimaryForRange, ScrollToCellOperation, SetWorksheetActivateCommand, SheetsSelectionsService } from '@univerjs/sheets';
+import { Inject } from '@wendellhu/redi';
+import { filter, merge } from 'rxjs';
+
+@OnLifecycle(LifecycleStages.Rendered, SheetsDefinedNameController)
+export class SheetsDefinedNameController extends Disposable {
+ constructor(
+ @Inject(SheetsSelectionsService) private readonly _selectionManagerService: SheetsSelectionsService,
+ @Inject(ThemeService) private readonly _themeService: ThemeService,
+ @IUniverInstanceService private readonly _instanceSrv: IUniverInstanceService,
+ @ICommandService private readonly _cmdSrv: ICommandService,
+ @IDefinedNamesService private readonly _definedNamesService: IDefinedNamesService
+ ) {
+ super();
+
+ this._init();
+ }
+
+ private _init(): void {
+ this.disposeWithMe(merge(
+ this._selectionManagerService.selectionMoveStart$,
+ this._selectionManagerService.selectionMoving$,
+ this._selectionManagerService.selectionMoveEnd$
+ )
+ .pipe(filter((params) => !!params))
+ .subscribe((params) => {
+ this._syncDefinedNameRange(params as ISelectionWithStyle[]);
+ }));
+
+ this.disposeWithMe(this._definedNamesService.focusRange$.subscribe(async (item) => {
+ if (item == null) return;
+
+ const { unitId } = item;
+ let { formulaOrRefString } = item;
+
+ if (formulaOrRefString.substring(0, 1) === operatorToken.EQUALS) {
+ formulaOrRefString = formulaOrRefString.substring(1);
+ }
+
+ const result = isReferenceStrings(formulaOrRefString);
+ if (!result) {
+ return;
+ }
+
+ const workbook = this._instanceSrv.getUnit<Workbook>(unitId)!;
+ const selections = await this._getSelections(workbook, unitId, formulaOrRefString);
+
+ this._selectionManagerService.setSelections(selections);
+
+ this._cmdSrv.executeCommand(ScrollToCellOperation.id, selections[0].range);
+ }));
+ }
+
+ private _syncDefinedNameRange(params: ISelectionWithStyle[]) {
+ if (params.length === 0) {
+ return;
+ }
+
+ const lastSelection = params[params.length - 1];
+ const workbook = this._instanceSrv.getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET);
+ const worksheet = workbook?.getActiveSheet();
+ if (!worksheet) {
+ return;
+ }
+
+ this._definedNamesService.setCurrentRange({
+ range: lastSelection.range,
+ unitId: workbook!.getUnitId(),
+ sheetId: worksheet.getSheetId(),
+ });
+ }
+
+ private async _getSelections(workbook: Workbook, unitId: string, formulaOrRefString: string) {
+ const valueArray = formulaOrRefString.split(',');
+
+ let worksheet = workbook.getActiveSheet();
+
+ if (!worksheet) {
+ return [];
+ }
+
+ const selections = [];
+
+ for (let i = 0; i < valueArray.length; i++) {
+ const refString = valueArray[i].trim();
+
+ const unitRange = deserializeRangeWithSheet(refString.trim());
+
+ // WTF@DR-Univer: side effects in get methods
+ if (i === 0) {
+ const worksheetCache = workbook.getSheetBySheetName(unitRange.sheetName);
+ if (worksheetCache && worksheet.getSheetId() !== worksheetCache.getSheetId()) {
+ worksheet = worksheetCache;
+ await this._cmdSrv.executeCommand(SetWorksheetActivateCommand.id, {
+ subUnitId: worksheet.getSheetId(),
+ unitId,
+ });
+ }
+ }
+
+ if (worksheet.getName() !== unitRange.sheetName) {
+ continue;
+ }
+
+ let primary = null;
+ if (i === valueArray.length - 1) {
+ const range = unitRange.range;
+ const { startRow, startColumn, endRow, endColumn } = range;
+ primary = getPrimaryForRange({
+ startRow,
+ startColumn,
+ endRow,
+ endColumn,
+
+ }, worksheet);
+ }
+
+ selections.push({
+ range: unitRange.range,
+ style: getNormalSelectionStyle(this._themeService),
+ primary,
+ });
+ }
+
+ return selections;
+ }
+}
diff --git a/packages/sheets-ui/src/controllers/editor/__tests__/create-test-bed.ts b/packages/sheets-ui/src/controllers/editor/__tests__/create-test-bed.ts
index f5c21e7aed..13aedd060c 100644
--- a/packages/sheets-ui/src/controllers/editor/__tests__/create-test-bed.ts
+++ b/packages/sheets-ui/src/controllers/editor/__tests__/create-test-bed.ts
@@ -16,7 +16,7 @@
import type { IWorkbookData, Workbook } from '@univerjs/core';
import { ILogService, IUniverInstanceService, LocaleType, LogLevel, Plugin, Univer, UniverInstanceType } from '@univerjs/core';
-import { SelectionManagerService, SheetInterceptorService } from '@univerjs/sheets';
+import { SheetInterceptorService, SheetsSelectionsService } from '@univerjs/sheets';
import type { Dependency } from '@wendellhu/redi';
import { Inject, Injector } from '@wendellhu/redi';
@@ -61,7 +61,7 @@ export function createTestBed(workbookData?: IWorkbookData, dependencies?: Depen
}
override onStarting(injector: Injector): void {
- injector.add([SelectionManagerService]);
+ injector.add([SheetsSelectionsService]);
injector.add([SheetInterceptorService]);
dependencies?.forEach((d) => injector.add(d));
diff --git a/packages/sheets-ui/src/controllers/editor/editing.render-controller.ts b/packages/sheets-ui/src/controllers/editor/editing.render-controller.ts
index 30d26a5ad4..b822f90cf6 100644
--- a/packages/sheets-ui/src/controllers/editor/editing.render-controller.ts
+++ b/packages/sheets-ui/src/controllers/editor/editing.render-controller.ts
@@ -14,6 +14,8 @@
* limitations under the License.
*/
+/* eslint-disable max-lines-per-function */
+
import type { ICellData, ICommandInfo, IDocumentBody, IPosition, Nullable, Workbook } from '@univerjs/core';
import {
CellValueType,
@@ -63,7 +65,7 @@ import {
} from '@univerjs/engine-render';
import { IEditorService, KeyCode, SetEditorResizeOperation } from '@univerjs/ui';
import { Inject } from '@wendellhu/redi';
-import { ClearSelectionFormatCommand, SelectionManagerService, SetRangeValuesCommand, SetSelectionsOperation, SetWorksheetActivateCommand } from '@univerjs/sheets';
+import { ClearSelectionFormatCommand, SetRangeValuesCommand, SetSelectionsOperation, SetWorksheetActivateCommand, SheetsSelectionsService } from '@univerjs/sheets';
import { distinctUntilChanged, filter } from 'rxjs';
import { LexerTreeBuilder, matchToken } from '@univerjs/engine-formula';
@@ -110,7 +112,7 @@ export class EditingRenderController extends Disposable implements IRenderModule
@IEditorBridgeService private readonly _editorBridgeService: IEditorBridgeService,
@ICellEditorManagerService private readonly _cellEditorManagerService: ICellEditorManagerService,
@ITextSelectionRenderManager private readonly _textSelectionRenderManager: ITextSelectionRenderManager,
- @Inject(SelectionManagerService) private readonly _selectionManagerService: SelectionManagerService,
+ @Inject(SheetsSelectionsService) private readonly _selectionManagerService: SheetsSelectionsService,
@Inject(LexerTreeBuilder) private readonly _lexerTreeBuilder: LexerTreeBuilder,
@Inject(TextSelectionManagerService) private readonly _textSelectionManagerService: TextSelectionManagerService,
@ICommandService private readonly _commandService: ICommandService,
@@ -358,7 +360,7 @@ export class EditingRenderController extends Disposable implements IRenderModule
* determine whether a scrollbar appears,
* and calculate the editor's boundaries relative to the browser.
*/
- // eslint-disable-next-line max-lines-per-function
+
private _editAreaProcessing(
editorWidth: number,
editorHeight: number,
@@ -490,7 +492,7 @@ export class EditingRenderController extends Disposable implements IRenderModule
}
// You can double-click on the cell or input content by keyboard to put the cell into the edit state.
- // eslint-disable-next-line max-lines-per-function
+
private _handleEditorVisible(param: IEditorBridgeServiceVisibleParam) {
const { eventType, keycode } = param;
@@ -759,33 +761,9 @@ export class EditingRenderController extends Disposable implements IRenderModule
this._cursorChange = CursorChange.InitialState;
- const selections = this._selectionManagerService.getSelections();
- const currentSelection = this._selectionManagerService.getCurrent();
-
- if (currentSelection == null) {
- return;
- }
-
- const { unitId: workbookId, sheetId: worksheetId, pluginName } = currentSelection;
-
this._exitInput(param);
- if (keycode === KeyCode.ESC) {
- // Reselect the current selections, when exist cell editor by press ESC.
- if (selections) {
- this._commandService.syncExecuteCommand(SetSelectionsOperation.id, {
- unitId: workbookId,
- subUnitId: worksheetId,
- pluginName,
- selections,
- });
- }
-
- return;
- }
-
const editCellState = this._editorBridgeService.getEditCellState();
-
if (editCellState == null) {
return;
}
@@ -802,13 +780,28 @@ export class EditingRenderController extends Disposable implements IRenderModule
}
const workbook = this._univerInstanceService.getUniverSheetInstance(unitId);
-
- const worksheet = workbook?.getSheetBySheetId(sheetId);
+ const worksheet = workbook?.getActiveSheet();
if (worksheet == null) {
return;
}
+ const workbookId = workbook!.getUnitId();
+ const worksheetId = worksheet.getSheetId();
+ if (keycode === KeyCode.ESC) {
+ const selections = this._selectionManagerService.getCurrentSelections();
+ // Reselect the current selections, when exist cell editor by press ESC.
+ if (selections) {
+ this._commandService.syncExecuteCommand(SetSelectionsOperation.id, {
+ unitId: workbookId,
+ subUnitId: worksheetId,
+ selections,
+ });
+ }
+
+ return;
+ }
+
const cellData: Nullable<ICellData> = getCellDataByInput(
worksheet.getCellRaw(row, column) || {},
documentLayoutObject,
@@ -840,11 +833,6 @@ export class EditingRenderController extends Disposable implements IRenderModule
unitId,
});
}
- /**
- * When switching tabs while the editor is open,
- * the operation to refresh the selection will be blocked and needs to be triggered manually.
- */
- this._selectionManagerService.refreshSelection();
const cell = this._editorBridgeService.interceptor.fetchThroughInterceptors(
this._editorBridgeService.interceptor.getInterceptPoints().AFTER_CELL_EDIT
diff --git a/packages/sheets-ui/src/controllers/format-painter/format-painter.controller.ts b/packages/sheets-ui/src/controllers/format-painter/format-painter.controller.ts
index c6d3a1051a..c5b9dbf66f 100644
--- a/packages/sheets-ui/src/controllers/format-painter/format-painter.controller.ts
+++ b/packages/sheets-ui/src/controllers/format-painter/format-painter.controller.ts
@@ -24,31 +24,31 @@ import {
LifecycleStages,
ObjectMatrix,
OnLifecycle,
- toDisposable,
Tools,
UniverInstanceType,
} from '@univerjs/core';
import { Inject, Injector } from '@wendellhu/redi';
import type { IAddWorksheetMergeMutationParams, IRemoveWorksheetMergeMutationParams, ISetRangeValuesMutationParams } from '@univerjs/sheets';
-import { AddMergeUndoMutationFactory, AddWorksheetMergeMutation, getAddMergeMutationRangeByType, RemoveMergeUndoMutationFactory, RemoveWorksheetMergeMutation, SelectionManagerService, SetRangeValuesCommand, SetRangeValuesMutation, SetRangeValuesUndoMutationFactory, SheetInterceptorService } from '@univerjs/sheets';
+import { AddMergeUndoMutationFactory, AddWorksheetMergeMutation, getAddMergeMutationRangeByType, RemoveMergeUndoMutationFactory, RemoveWorksheetMergeMutation, SetRangeValuesCommand, SetRangeValuesMutation, SetRangeValuesUndoMutationFactory, SheetInterceptorService, SheetsSelectionsService } from '@univerjs/sheets';
+import { IRenderManagerService } from '@univerjs/engine-render';
import {
ApplyFormatPainterCommand,
SetOnceFormatPainterCommand,
} from '../../commands/commands/set-format-painter.command';
import type { IFormatPainterHook, ISelectionFormatInfo } from '../../services/format-painter/format-painter.service';
import { FormatPainterStatus, IFormatPainterService } from '../../services/format-painter/format-painter.service';
-import { ISelectionRenderService } from '../../services/selection/selection-render.service';
import { checkCellContentInRanges, getClearContentMutationParamsForRanges } from '../../common/utils';
+import { ISheetSelectionRenderService } from '../../services/selection/base-selection-render.service';
-@OnLifecycle(LifecycleStages.Rendered, FormatPainterController)
+@OnLifecycle(LifecycleStages.Steady, FormatPainterController)
export class FormatPainterController extends Disposable {
constructor(
@ICommandService private readonly _commandService: ICommandService,
@IFormatPainterService private readonly _formatPainterService: IFormatPainterService,
@IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService,
- @ISelectionRenderService private readonly _selectionRenderService: ISelectionRenderService,
- @Inject(SelectionManagerService) private readonly _selectionManagerService: SelectionManagerService,
+ @IRenderManagerService private readonly _renderManagerService: IRenderManagerService,
+ @Inject(SheetsSelectionsService) private readonly _selectionManagerService: SheetsSelectionsService,
@Inject(SheetInterceptorService) private readonly _sheetInterceptorService: SheetInterceptorService,
@Inject(Injector) private readonly _injector: Injector
) {
@@ -63,28 +63,29 @@ export class FormatPainterController extends Disposable {
}
private _commandExecutedListener() {
+ const selectionRenderService = this._renderManagerService.getCurrentTypeOfRenderer(UniverInstanceType.UNIVER_SHEET)!.with(ISheetSelectionRenderService);
+
this.disposeWithMe(
- toDisposable(
- this._selectionRenderService.selectionMoveEnd$.subscribe((selections) => {
- if (this._formatPainterService.getStatus() !== FormatPainterStatus.OFF) {
- const { rangeWithCoord } = selections[selections.length - 1];
- this._commandService.executeCommand(ApplyFormatPainterCommand.id, {
- unitId: this._univerInstanceService.getFocusedUnit()?.getUnitId() || '',
- subUnitId: (this._univerInstanceService.getFocusedUnit() as Workbook).getActiveSheet()?.getSheetId() || '',
- range: {
- startRow: rangeWithCoord.startRow,
- startColumn: rangeWithCoord.startColumn,
- endRow: rangeWithCoord.endRow,
- endColumn: rangeWithCoord.endColumn,
- },
- });
- // if once, turn off the format painter
- if (this._formatPainterService.getStatus() === FormatPainterStatus.ONCE) {
- this._commandService.executeCommand(SetOnceFormatPainterCommand.id);
- }
+ selectionRenderService.selectionMoveEnd$.subscribe((selections) => {
+ if (this._formatPainterService.getStatus() !== FormatPainterStatus.OFF) {
+ const { rangeWithCoord } = selections[selections.length - 1];
+ this._commandService.executeCommand(ApplyFormatPainterCommand.id, {
+ unitId: this._univerInstanceService.getFocusedUnit()?.getUnitId() || '',
+ subUnitId: (this._univerInstanceService.getFocusedUnit() as Workbook).getActiveSheet()?.getSheetId() || '',
+ range: {
+ startRow: rangeWithCoord.startRow,
+ startColumn: rangeWithCoord.startColumn,
+ endRow: rangeWithCoord.endRow,
+ endColumn: rangeWithCoord.endColumn,
+ },
+ });
+
+ // if once, turn off the format painter
+ if (this._formatPainterService.getStatus() === FormatPainterStatus.ONCE) {
+ this._commandService.executeCommand(SetOnceFormatPainterCommand.id);
}
- })
- )
+ }
+ })
);
}
@@ -109,7 +110,7 @@ export class FormatPainterController extends Disposable {
}
private _collectSelectionRangeFormat() {
- const selection = this._selectionManagerService.getLast();
+ const selection = this._selectionManagerService.getCurrentLastSelection();
const range = selection?.range;
if (!range) return null;
const { startRow, endRow, startColumn, endColumn } = range;
diff --git a/packages/sheets-ui/src/controllers/menu/__tests__/create-menu-test-bed.ts b/packages/sheets-ui/src/controllers/menu/__tests__/create-menu-test-bed.ts
index 5a61123e20..f500a4ce1b 100644
--- a/packages/sheets-ui/src/controllers/menu/__tests__/create-menu-test-bed.ts
+++ b/packages/sheets-ui/src/controllers/menu/__tests__/create-menu-test-bed.ts
@@ -16,8 +16,8 @@
import type { IWorkbookData } from '@univerjs/core';
import { LocaleType, Plugin, Univer, UniverInstanceType } from '@univerjs/core';
-import { RangeProtectionRefRangeService, RangeProtectionRenderModel, RangeProtectionRuleModel, RangeProtectionService, RefRangeService, SelectionManagerService,
- SheetInterceptorService,
+import { RangeProtectionRefRangeService, RangeProtectionRenderModel, RangeProtectionRuleModel, RangeProtectionService, RefRangeService, SheetInterceptorService,
+ SheetsSelectionsService,
WorkbookPermissionService,
WorksheetPermissionService,
WorksheetProtectionPointModel,
@@ -68,7 +68,7 @@ export function createMenuTestBed() {
override onStarting(injector: Injector): void {
injector.add([IPlatformService, { useClass: PlatformService }]);
- injector.add([SelectionManagerService]);
+ injector.add([SheetsSelectionsService]);
injector.add([IShortcutService, { useClass: ShortcutService }]);
injector.add([IMenuService, { useClass: MenuService }]);
injector.add([WorkbookPermissionService]);
diff --git a/packages/sheets-ui/src/controllers/menu/__tests__/menu.spec.ts b/packages/sheets-ui/src/controllers/menu/__tests__/menu.spec.ts
index b5d4b8b0c4..e049f7722f 100644
--- a/packages/sheets-ui/src/controllers/menu/__tests__/menu.spec.ts
+++ b/packages/sheets-ui/src/controllers/menu/__tests__/menu.spec.ts
@@ -21,11 +21,10 @@ import {
RANGE_TYPE,
} from '@univerjs/core';
import {
- NORMAL_SELECTION_PLUGIN_NAME,
- SelectionManagerService,
SetBoldCommand,
SetRangeValuesMutation,
SetStyleCommand,
+ SheetsSelectionsService,
} from '@univerjs/sheets';
import { Injector } from '@wendellhu/redi';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
@@ -60,15 +59,10 @@ describe('test menu items', () => {
});
function select(range: IRange) {
- const selectionManager = get(SelectionManagerService);
- selectionManager.setCurrentSelection({
- pluginName: NORMAL_SELECTION_PLUGIN_NAME,
- unitId: 'test',
- sheetId: 'sheet1',
- });
+ const selectionManager = get(SheetsSelectionsService);
const { startColumn, startRow, endColumn, endRow } = range;
- selectionManager.add([
+ selectionManager.addSelections([
{
range: { startRow, startColumn, endColumn, endRow, rangeType: RANGE_TYPE.NORMAL },
primary: {
diff --git a/packages/sheets-ui/src/controllers/menu/__tests__/row-col.menu.spec.ts b/packages/sheets-ui/src/controllers/menu/__tests__/row-col.menu.spec.ts
index 0f9b2e63a3..bd27c9c100 100644
--- a/packages/sheets-ui/src/controllers/menu/__tests__/row-col.menu.spec.ts
+++ b/packages/sheets-ui/src/controllers/menu/__tests__/row-col.menu.spec.ts
@@ -24,8 +24,6 @@ import {
UniverInstanceType,
} from '@univerjs/core';
import {
- NORMAL_SELECTION_PLUGIN_NAME,
- SelectionManagerService,
SetColHiddenCommand,
SetColHiddenMutation,
SetColVisibleMutation,
@@ -75,13 +73,6 @@ describe('Test row col menu items', () => {
});
disposableCollection = new DisposableCollection();
-
- const selectionManager = get(SelectionManagerService);
- selectionManager.setCurrentSelection({
- pluginName: NORMAL_SELECTION_PLUGIN_NAME,
- unitId: 'test',
- sheetId: 'sheet1',
- });
});
afterEach(() => univer.dispose());
@@ -108,7 +99,7 @@ describe('Test row col menu items', () => {
return commandService.executeCommand<ISetSelectionsOperationParams, boolean>(SetSelectionsOperation.id, {
unitId: workbook.getUnitId(),
subUnitId: worksheet.getSheetId(),
- pluginName: NORMAL_SELECTION_PLUGIN_NAME,
+
selections: [
{
range: { startRow: rowStart, startColumn: 0, endColumn, endRow: rowEnd, rangeType: RANGE_TYPE.ROW },
@@ -136,7 +127,7 @@ describe('Test row col menu items', () => {
return commandService.executeCommand<ISetSelectionsOperationParams, boolean>(SetSelectionsOperation.id, {
unitId: workbook.getUnitId(),
subUnitId: worksheet.getSheetId(),
- pluginName: NORMAL_SELECTION_PLUGIN_NAME,
+
selections: [
{
range: {
diff --git a/packages/sheets-ui/src/controllers/menu/menu-util.ts b/packages/sheets-ui/src/controllers/menu/menu-util.ts
index 6393a790f2..1435de97ec 100644
--- a/packages/sheets-ui/src/controllers/menu/menu-util.ts
+++ b/packages/sheets-ui/src/controllers/menu/menu-util.ts
@@ -19,7 +19,7 @@ import { FOCUSING_COMMON_DRAWINGS, IContextService, IPermissionService, IUniverI
import { UnitAction } from '@univerjs/protocol';
import type { ICellPermission } from '@univerjs/sheets';
-import { RangeProtectionRuleModel, SelectionManagerService, WorkbookEditablePermission, WorkbookManageCollaboratorPermission, WorksheetProtectionRuleModel } from '@univerjs/sheets';
+import { RangeProtectionRuleModel, SheetsSelectionsService, WorkbookEditablePermission, WorkbookManageCollaboratorPermission, WorksheetProtectionRuleModel } from '@univerjs/sheets';
import type { IAccessor } from '@wendellhu/redi';
import type { Observable } from 'rxjs';
import { combineLatest, map, of, startWith, switchMap } from 'rxjs';
@@ -63,7 +63,7 @@ export function getCurrentRangeDisable$(accessor: IAccessor, permissionTypes: IP
return of(true);
}
- const selectionManagerService = accessor.get(SelectionManagerService);
+ const selectionManagerService = accessor.get(SheetsSelectionsService);
const rangeProtectionRuleModel = accessor.get(RangeProtectionRuleModel);
const worksheetRuleModel = accessor.get(WorksheetProtectionRuleModel);
@@ -128,12 +128,12 @@ export function getCurrentRangeDisable$(accessor: IAccessor, permissionTypes: IP
export function getBaseRangeMenuHidden$(accessor: IAccessor) {
const univerInstanceService = accessor.get(IUniverInstanceService);
- const selectionManagerService = accessor.get(SelectionManagerService);
+ const selectionManagerService = accessor.get(SheetsSelectionsService);
const rangeProtectionRuleModel = accessor.get(RangeProtectionRuleModel);
return selectionManagerService.selectionMoveEnd$.pipe(
map(() => {
- const range = selectionManagerService.getLast()?.range;
+ const range = selectionManagerService.getCurrentLastSelection()?.range;
if (!range) return true;
const workbook = univerInstanceService.getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET)!;
@@ -168,12 +168,12 @@ export function getBaseRangeMenuHidden$(accessor: IAccessor) {
export function getInsertAfterMenuHidden$(accessor: IAccessor, type: 'row' | 'col') {
const univerInstanceService = accessor.get(IUniverInstanceService);
- const selectionManagerService = accessor.get(SelectionManagerService);
+ const selectionManagerService = accessor.get(SheetsSelectionsService);
const rangeProtectionRuleModel = accessor.get(RangeProtectionRuleModel);
return selectionManagerService.selectionMoveEnd$.pipe(
map(() => {
- const range = selectionManagerService.getLast()?.range;
+ const range = selectionManagerService.getCurrentLastSelection()?.range;
if (!range) return true;
const workbook = univerInstanceService.getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET)!;
@@ -214,12 +214,12 @@ export function getInsertAfterMenuHidden$(accessor: IAccessor, type: 'row' | 'co
export function getInsertBeforeMenuHidden$(accessor: IAccessor, type: 'row' | 'col') {
const univerInstanceService = accessor.get(IUniverInstanceService);
- const selectionManagerService = accessor.get(SelectionManagerService);
+ const selectionManagerService = accessor.get(SheetsSelectionsService);
const rangeProtectionRuleModel = accessor.get(RangeProtectionRuleModel);
return selectionManagerService.selectionMoveEnd$.pipe(
map(() => {
- const range = selectionManagerService.getLast()?.range;
+ const range = selectionManagerService.getCurrentLastSelection()?.range;
if (!range) return true;
const workbook = univerInstanceService.getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET)!;
@@ -260,12 +260,12 @@ export function getInsertBeforeMenuHidden$(accessor: IAccessor, type: 'row' | 'c
export function getDeleteMenuHidden$(accessor: IAccessor, type: 'row' | 'col') {
const univerInstanceService = accessor.get(IUniverInstanceService);
- const selectionManagerService = accessor.get(SelectionManagerService);
+ const selectionManagerService = accessor.get(SheetsSelectionsService);
const rangeProtectionRuleModel = accessor.get(RangeProtectionRuleModel);
return selectionManagerService.selectionMoveEnd$.pipe(
map(() => {
- const range = selectionManagerService.getLast()?.range;
+ const range = selectionManagerService.getCurrentLastSelection()?.range;
if (!range) return true;
const workbook = univerInstanceService.getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET)!;
@@ -309,12 +309,12 @@ export function getDeleteMenuHidden$(accessor: IAccessor, type: 'row' | 'col') {
export function getCellMenuHidden$(accessor: IAccessor, type: 'row' | 'col') {
const univerInstanceService = accessor.get(IUniverInstanceService);
- const selectionManagerService = accessor.get(SelectionManagerService);
+ const selectionManagerService = accessor.get(SheetsSelectionsService);
const rangeProtectionRuleModel = accessor.get(RangeProtectionRuleModel);
return selectionManagerService.selectionMoveEnd$.pipe(
map(() => {
- const range = selectionManagerService.getLast()?.range;
+ const range = selectionManagerService.getCurrentLastSelection()?.range;
if (!range) return true;
const workbook = univerInstanceService.getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET)!;
diff --git a/packages/sheets-ui/src/controllers/menu/menu.ts b/packages/sheets-ui/src/controllers/menu/menu.ts
index 783f451696..e3102aadeb 100644
--- a/packages/sheets-ui/src/controllers/menu/menu.ts
+++ b/packages/sheets-ui/src/controllers/menu/menu.ts
@@ -38,7 +38,6 @@ import {
RangeProtectionPermissionViewPoint,
ResetBackgroundColorCommand,
ResetTextColorCommand,
- SelectionManagerService,
SetBackgroundColorCommand,
SetColHiddenMutation,
SetColVisibleMutation,
@@ -58,6 +57,7 @@ import {
SetWorksheetColWidthMutation,
SetWorksheetRowIsAutoHeightCommand,
SetWorksheetRowIsAutoHeightMutation,
+ SheetsSelectionsService,
WorkbookCopyPermission,
WorkbookEditablePermission,
WorksheetCopyPermission,
@@ -158,7 +158,7 @@ export function BoldMenuItemFactory(accessor: IAccessor): IMenuButtonItem {
const commandService = accessor.get(ICommandService);
const univerInstanceService = accessor.get(IUniverInstanceService);
const contextService = accessor.get(IContextService);
- const selectionManagerService = accessor.get(SelectionManagerService);
+ const selectionManagerService = accessor.get(SheetsSelectionsService);
return {
id: SetRangeBoldCommand.id,
@@ -173,7 +173,7 @@ export function BoldMenuItemFactory(accessor: IAccessor): IMenuButtonItem {
const disposable = commandService.onCommandExecuted((c) => {
const id = c.id;
if (id === SetRangeValuesMutation.id || id === SetSelectionsOperation.id || id === SetWorksheetActiveOperation.id) {
- const primary = selectionManagerService.getLast()?.primary;
+ const primary = selectionManagerService.getCurrentLastSelection()?.primary;
let isBold = FontWeight.NORMAL;
if (primary != null) {
@@ -199,7 +199,7 @@ export function BoldMenuItemFactory(accessor: IAccessor): IMenuButtonItem {
}
});
- const primary = selectionManagerService.getLast()?.primary;
+ const primary = selectionManagerService.getCurrentLastSelection()?.primary;
if (!worksheet) {
subscriber.next(false);
return;
@@ -221,7 +221,7 @@ export function BoldMenuItemFactory(accessor: IAccessor): IMenuButtonItem {
export function ItalicMenuItemFactory(accessor: IAccessor): IMenuButtonItem {
const commandService = accessor.get(ICommandService);
const univerInstanceService = accessor.get(IUniverInstanceService);
- const selectionManagerService = accessor.get(SelectionManagerService);
+ const selectionManagerService = accessor.get(SheetsSelectionsService);
const contextService = accessor.get(IContextService);
return {
@@ -237,7 +237,7 @@ export function ItalicMenuItemFactory(accessor: IAccessor): IMenuButtonItem {
const disposable = commandService.onCommandExecuted((c) => {
const id = c.id;
if (id === SetRangeValuesMutation.id || id === SetSelectionsOperation.id || id === SetWorksheetActiveOperation.id) {
- const primary = selectionManagerService.getLast()?.primary;
+ const primary = selectionManagerService.getCurrentLastSelection()?.primary;
let isItalic = FontItalic.NORMAL;
if (primary != null) {
const range = worksheet.getRange(primary.startRow, primary.startColumn);
@@ -260,7 +260,7 @@ export function ItalicMenuItemFactory(accessor: IAccessor): IMenuButtonItem {
}
});
- const primary = selectionManagerService.getLast()?.primary;
+ const primary = selectionManagerService.getCurrentLastSelection()?.primary;
let isItalic = FontItalic.NORMAL;
if (primary != null) {
const range = worksheet.getRange(primary.startRow, primary.startColumn);
@@ -277,7 +277,7 @@ export function ItalicMenuItemFactory(accessor: IAccessor): IMenuButtonItem {
export function UnderlineMenuItemFactory(accessor: IAccessor): IMenuButtonItem {
const commandService = accessor.get(ICommandService);
const univerInstanceService = accessor.get(IUniverInstanceService);
- const selectionManagerService = accessor.get(SelectionManagerService);
+ const selectionManagerService = accessor.get(SheetsSelectionsService);
const contextService = accessor.get(IContextService);
return {
@@ -292,7 +292,7 @@ export function UnderlineMenuItemFactory(accessor: IAccessor): IMenuButtonItem {
const disposable = commandService.onCommandExecuted((c) => {
const id = c.id;
if (id === SetRangeValuesMutation.id || id === SetSelectionsOperation.id || id === SetWorksheetActiveOperation.id) {
- const primary = selectionManagerService.getLast()?.primary;
+ const primary = selectionManagerService.getCurrentLastSelection()?.primary;
let isUnderline;
if (primary != null) {
const range = worksheet.getRange(primary.startRow, primary.startColumn);
@@ -315,7 +315,7 @@ export function UnderlineMenuItemFactory(accessor: IAccessor): IMenuButtonItem {
}
});
- const primary = selectionManagerService.getLast()?.primary;
+ const primary = selectionManagerService.getCurrentLastSelection()?.primary;
let isUnderline;
if (primary != null) {
const range = worksheet.getRange(primary.startRow, primary.startColumn);
@@ -333,7 +333,7 @@ export function UnderlineMenuItemFactory(accessor: IAccessor): IMenuButtonItem {
export function StrikeThroughMenuItemFactory(accessor: IAccessor): IMenuButtonItem {
const commandService = accessor.get(ICommandService);
const univerInstanceService = accessor.get(IUniverInstanceService);
- const selectionManagerService = accessor.get(SelectionManagerService);
+ const selectionManagerService = accessor.get(SheetsSelectionsService);
const contextService = accessor.get(IContextService);
return {
@@ -349,7 +349,7 @@ export function StrikeThroughMenuItemFactory(accessor: IAccessor): IMenuButtonIt
const disposable = commandService.onCommandExecuted((c) => {
const id = c.id;
if (id === SetRangeValuesMutation.id || id === SetSelectionsOperation.id || id === SetWorksheetActiveOperation.id) {
- const primary = selectionManagerService.getLast()?.primary;
+ const primary = selectionManagerService.getCurrentLastSelection()?.primary;
let st;
if (primary != null) {
const range = worksheet.getRange(primary.startRow, primary.startColumn);
@@ -376,7 +376,7 @@ export function StrikeThroughMenuItemFactory(accessor: IAccessor): IMenuButtonIt
}
});
- const primary = selectionManagerService.getLast()?.primary;
+ const primary = selectionManagerService.getCurrentLastSelection()?.primary;
let st;
if (primary != null) {
const range = worksheet.getRange(primary.startRow, primary.startColumn);
@@ -393,7 +393,7 @@ export function StrikeThroughMenuItemFactory(accessor: IAccessor): IMenuButtonIt
export function FontFamilySelectorMenuItemFactory(accessor: IAccessor): IMenuSelectorItem<string> {
const commandService = accessor.get(ICommandService);
const univerInstanceService = accessor.get(IUniverInstanceService);
- const selectionManagerService = accessor.get(SelectionManagerService);
+ const selectionManagerService = accessor.get(SheetsSelectionsService);
const defaultValue = DEFAULT_STYLES.ff;
@@ -420,7 +420,7 @@ export function FontFamilySelectorMenuItemFactory(accessor: IAccessor): IMenuSel
return;
}
- const primary = selectionManagerService.getLast()?.primary;
+ const primary = selectionManagerService.getCurrentLastSelection()?.primary;
let ff;
if (primary != null) {
const range = worksheet.getRange(primary.startRow, primary.startColumn);
@@ -430,7 +430,7 @@ export function FontFamilySelectorMenuItemFactory(accessor: IAccessor): IMenuSel
subscriber.next(ff ?? defaultValue);
});
- const primary = selectionManagerService.getLast()?.primary;
+ const primary = selectionManagerService.getCurrentLastSelection()?.primary;
let ff;
if (primary != null) {
const range = worksheet.getRange(primary.startRow, primary.startColumn);
@@ -447,7 +447,7 @@ export function FontFamilySelectorMenuItemFactory(accessor: IAccessor): IMenuSel
export function FontSizeSelectorMenuItemFactory(accessor: IAccessor): IMenuSelectorItem<number> {
const commandService = accessor.get(ICommandService);
const univerInstanceService = accessor.get(IUniverInstanceService);
- const selectionManagerService = accessor.get(SelectionManagerService);
+ const selectionManagerService = accessor.get(SheetsSelectionsService);
const contextService = accessor.get(IContextService);
const defaultValue = DEFAULT_STYLES.fs;
@@ -473,7 +473,7 @@ export function FontSizeSelectorMenuItemFactory(accessor: IAccessor): IMenuSelec
const disposable = commandService.onCommandExecuted((c) => {
const id = c.id;
if (id === SetRangeValuesMutation.id || id === SetSelectionsOperation.id || id === SetWorksheetActiveOperation.id) {
- const primary = selectionManagerService.getLast()?.primary;
+ const primary = selectionManagerService.getCurrentLastSelection()?.primary;
let fs;
if (primary != null) {
const range = worksheet.getRange(primary.startRow, primary.startColumn);
@@ -498,7 +498,7 @@ export function FontSizeSelectorMenuItemFactory(accessor: IAccessor): IMenuSelec
}
});
- const primary = selectionManagerService.getLast()?.primary;
+ const primary = selectionManagerService.getCurrentLastSelection()?.primary;
let fs;
if (primary != null) {
const range = worksheet.getRange(primary.startRow, primary.startColumn);
@@ -628,7 +628,7 @@ export const HORIZONTAL_ALIGN_CHILDREN = [
export function HorizontalAlignMenuItemFactory(accessor: IAccessor): IMenuSelectorItem<HorizontalAlign> {
const univerInstanceService = accessor.get(IUniverInstanceService);
- const selectionManagerService = accessor.get(SelectionManagerService);
+ const selectionManagerService = accessor.get(SheetsSelectionsService);
const defaultValue = HorizontalAlign.LEFT;
@@ -647,7 +647,7 @@ export function HorizontalAlignMenuItemFactory(accessor: IAccessor): IMenuSelect
return;
}
- const primary = selectionManagerService.getLast()?.primary;
+ const primary = selectionManagerService.getCurrentLastSelection()?.primary;
let ha;
if (primary != null) {
const range = worksheet.getRange(primary.startRow, primary.startColumn);
@@ -657,7 +657,7 @@ export function HorizontalAlignMenuItemFactory(accessor: IAccessor): IMenuSelect
subscriber.next(ha ?? defaultValue);
});
- const primary = selectionManagerService.getLast()?.primary;
+ const primary = selectionManagerService.getCurrentLastSelection()?.primary;
let ha;
if (primary != null) {
const range = worksheet.getRange(primary.startRow, primary.startColumn);
@@ -693,7 +693,7 @@ export const VERTICAL_ALIGN_CHILDREN = [
export function VerticalAlignMenuItemFactory(accessor: IAccessor): IMenuSelectorItem<VerticalAlign> {
const univerInstanceService = accessor.get(IUniverInstanceService);
- const selectionManagerService = accessor.get(SelectionManagerService);
+ const selectionManagerService = accessor.get(SheetsSelectionsService);
const defaultValue = VerticalAlign.BOTTOM;
@@ -712,7 +712,7 @@ export function VerticalAlignMenuItemFactory(accessor: IAccessor): IMenuSelector
return;
}
- const primary = selectionManagerService.getLast()?.primary;
+ const primary = selectionManagerService.getCurrentLastSelection()?.primary;
let va;
if (primary != null) {
const range = worksheet.getRange(primary.startRow, primary.startColumn);
@@ -722,7 +722,7 @@ export function VerticalAlignMenuItemFactory(accessor: IAccessor): IMenuSelector
subscriber.next(va ?? defaultValue);
});
- const primary = selectionManagerService.getLast()?.primary;
+ const primary = selectionManagerService.getCurrentLastSelection()?.primary;
let va;
if (primary != null) {
const range = worksheet.getRange(primary.startRow, primary.startColumn);
@@ -757,7 +757,7 @@ export const TEXT_WRAP_CHILDREN = [
];
export function WrapTextMenuItemFactory(accessor: IAccessor): IMenuSelectorItem<WrapStrategy> {
- const selectionManagerService = accessor.get(SelectionManagerService);
+ const selectionManagerService = accessor.get(SheetsSelectionsService);
const univerInstanceService = accessor.get(IUniverInstanceService);
const defaultValue = WrapStrategy.OVERFLOW;
@@ -777,7 +777,7 @@ export function WrapTextMenuItemFactory(accessor: IAccessor): IMenuSelectorItem<
return;
}
- const primary = selectionManagerService.getLast()?.primary;
+ const primary = selectionManagerService.getCurrentLastSelection()?.primary;
let ws;
if (primary != null) {
const range = worksheet.getRange(primary.startRow, primary.startColumn);
@@ -787,7 +787,7 @@ export function WrapTextMenuItemFactory(accessor: IAccessor): IMenuSelectorItem<
subscriber.next(ws ?? defaultValue);
});
- const primary = selectionManagerService.getLast()?.primary;
+ const primary = selectionManagerService.getCurrentLastSelection()?.primary;
let ws;
if (primary != null) {
const range = worksheet.getRange(primary.startRow, primary.startColumn);
@@ -837,7 +837,7 @@ export const TEXT_ROTATE_CHILDREN = [
];
export function TextRotateMenuItemFactory(accessor: IAccessor): IMenuSelectorItem<number | string> {
- const selectionManagerService = accessor.get(SelectionManagerService);
+ const selectionManagerService = accessor.get(SheetsSelectionsService);
const univerInstanceService = accessor.get(IUniverInstanceService);
const defaultValue = 0;
@@ -857,7 +857,7 @@ export function TextRotateMenuItemFactory(accessor: IAccessor): IMenuSelectorIte
return;
}
- const primary = selectionManagerService.getLast()?.primary;
+ const primary = selectionManagerService.getCurrentLastSelection()?.primary;
let tr;
if (primary != null) {
const range = worksheet.getRange(primary.startRow, primary.startColumn);
@@ -871,7 +871,7 @@ export function TextRotateMenuItemFactory(accessor: IAccessor): IMenuSelectorIte
}
});
- const primary = selectionManagerService.getLast()?.primary;
+ const primary = selectionManagerService.getCurrentLastSelection()?.primary;
let tr;
if (primary != null) {
const range = worksheet.getRange(primary.startRow, primary.startColumn);
@@ -1141,7 +1141,7 @@ export function HideColMenuItemFactory(accessor: IAccessor): IMenuButtonItem {
export function ShowRowMenuItemFactory(accessor: IAccessor): IMenuButtonItem {
const univerInstanceService = accessor.get(IUniverInstanceService);
- const selectionManagerService = accessor.get(SelectionManagerService);
+ const selectionManagerService = accessor.get(SheetsSelectionsService);
const commandService = accessor.get(ICommandService);
@@ -1155,7 +1155,7 @@ export function ShowRowMenuItemFactory(accessor: IAccessor): IMenuButtonItem {
title: 'rightClick.showHideRow',
hidden$: deriveStateFromActiveSheet$(univerInstanceService, true, ({ worksheet }) => new Observable((subscriber) => {
function hasHiddenRowsInSelections(): boolean {
- const rowRanges = selectionManagerService.getSelections()?.map((s) => s.range).filter((r) => r.rangeType === RANGE_TYPE.ROW);
+ const rowRanges = selectionManagerService.getCurrentSelections()?.map((s) => s.range).filter((r) => r.rangeType === RANGE_TYPE.ROW);
return !!rowRanges?.some((range) => {
for (let r = range.startRow; r <= range.endRow; r++) {
if (!worksheet.getRowRawVisible(r)) return true; // should not take filtered out rows into account
@@ -1179,7 +1179,7 @@ export function ShowRowMenuItemFactory(accessor: IAccessor): IMenuButtonItem {
export function ShowColMenuItemFactory(accessor: IAccessor): IMenuButtonItem {
const univerInstanceService = accessor.get(IUniverInstanceService);
- const selectionManagerService = accessor.get(SelectionManagerService);
+ const selectionManagerService = accessor.get(SheetsSelectionsService);
const commandService = accessor.get(ICommandService);
const affectedCommands = [SetSelectionsOperation, SetColHiddenMutation, SetColVisibleMutation].map((c) => c.id);
@@ -1191,7 +1191,7 @@ export function ShowColMenuItemFactory(accessor: IAccessor): IMenuButtonItem {
title: 'rightClick.showHideColumn',
hidden$: deriveStateFromActiveSheet$(univerInstanceService, true, ({ worksheet }) => new Observable((subscriber) => {
function hasHiddenColsInSelections(): boolean {
- const colRanges = selectionManagerService.getSelections()?.map((s) => s.range).filter((r) => r.rangeType === RANGE_TYPE.COLUMN);
+ const colRanges = selectionManagerService.getCurrentSelections()?.map((s) => s.range).filter((r) => r.rangeType === RANGE_TYPE.COLUMN);
if (!colRanges || colRanges.length === 0) return false;
return !!colRanges.some((range) => {
@@ -1217,7 +1217,7 @@ export function ShowColMenuItemFactory(accessor: IAccessor): IMenuButtonItem {
export function SetRowHeightMenuItemFactory(accessor: IAccessor): IMenuButtonItem<number> {
const commandService = accessor.get(ICommandService);
const univerInstanceService = accessor.get(IUniverInstanceService);
- const selectionManagerService = accessor.get(SelectionManagerService);
+ const selectionManagerService = accessor.get(SheetsSelectionsService);
const defaultValue = 0;
@@ -1238,7 +1238,7 @@ export function SetRowHeightMenuItemFactory(accessor: IAccessor): IMenuButtonIte
},
value$: deriveStateFromActiveSheet$(univerInstanceService, defaultValue, ({ worksheet }) => new Observable((subscriber) => {
function update() {
- const primary = selectionManagerService.getLast()?.primary;
+ const primary = selectionManagerService.getCurrentLastSelection()?.primary;
const rowHeight = primary ? worksheet.getRowHeight(primary.startRow) : defaultValue;
subscriber.next(rowHeight);
}
@@ -1260,7 +1260,7 @@ export function SetRowHeightMenuItemFactory(accessor: IAccessor): IMenuButtonIte
export function SetColWidthMenuItemFactory(accessor: IAccessor): IMenuButtonItem<number> {
const commandService = accessor.get(ICommandService);
const univerInstanceService = accessor.get(IUniverInstanceService);
- const selectionManagerService = accessor.get(SelectionManagerService);
+ const selectionManagerService = accessor.get(SheetsSelectionsService);
const defaultValue = 0;
@@ -1281,7 +1281,7 @@ export function SetColWidthMenuItemFactory(accessor: IAccessor): IMenuButtonItem
},
value$: deriveStateFromActiveSheet$(univerInstanceService, defaultValue, ({ worksheet }) => new Observable((subscriber) => {
function update() {
- const primary = selectionManagerService.getLast()?.primary;
+ const primary = selectionManagerService.getCurrentLastSelection()?.primary;
let colWidth: number = defaultValue;
if (primary != null) {
colWidth = worksheet.getColumnWidth(primary.startColumn);
diff --git a/packages/sheets-ui/src/controllers/menu/permission-menu-util.ts b/packages/sheets-ui/src/controllers/menu/permission-menu-util.ts
index 044666ad87..2a70cd2c66 100644
--- a/packages/sheets-ui/src/controllers/menu/permission-menu-util.ts
+++ b/packages/sheets-ui/src/controllers/menu/permission-menu-util.ts
@@ -16,7 +16,7 @@
import type { Workbook } from '@univerjs/core';
import { FOCUSING_COMMON_DRAWINGS, IContextService, IPermissionService, IUniverInstanceService, Rectangle, UniverInstanceType, UserManagerService } from '@univerjs/core';
-import { RangeProtectionRuleModel, SelectionManagerService, WorkbookEditablePermission, WorkbookManageCollaboratorPermission, WorksheetProtectionRuleModel } from '@univerjs/sheets';
+import { RangeProtectionRuleModel, SheetsSelectionsService, WorkbookEditablePermission, WorkbookManageCollaboratorPermission, WorksheetProtectionRuleModel } from '@univerjs/sheets';
import type { IAccessor } from '@wendellhu/redi';
import { combineLatest, map, merge, of, startWith, switchMap } from 'rxjs';
@@ -38,7 +38,7 @@ export function getAddPermissionHidden$(accessor: IAccessor) {
}
const rangeProtectionRuleModel = accessor.get(RangeProtectionRuleModel);
const worksheetRuleModel = accessor.get(WorksheetProtectionRuleModel);
- const selectionManagerService = accessor.get(SelectionManagerService);
+ const selectionManagerService = accessor.get(SheetsSelectionsService);
return merge(
selectionManagerService.selectionMoveEnd$,
rangeProtectionRuleModel.ruleChange$,
@@ -48,7 +48,7 @@ export function getAddPermissionHidden$(accessor: IAccessor) {
const unitId = workbook.getUnitId();
const subUnitId = worksheet.getSheetId();
const subUnitRuleList = rangeProtectionRuleModel.getSubunitRuleList(unitId, subUnitId);
- const selections = selectionManagerService.getSelections();
+ const selections = selectionManagerService.getCurrentSelections();
const selectionsRanges = selections?.map((selection) => selection.range);
const ruleRanges = subUnitRuleList.map((rule) => rule.ranges).flat();
if (!selectionsRanges) {
@@ -92,7 +92,7 @@ export function getEditPermissionHidden$(accessor: IAccessor) {
const rangeProtectionRuleModel = accessor.get(RangeProtectionRuleModel);
const worksheetRuleModel = accessor.get(WorksheetProtectionRuleModel);
- const selectionManagerService = accessor.get(SelectionManagerService);
+ const selectionManagerService = accessor.get(SheetsSelectionsService);
return merge(
selectionManagerService.selectionMoveEnd$,
rangeProtectionRuleModel.ruleChange$,
@@ -102,7 +102,7 @@ export function getEditPermissionHidden$(accessor: IAccessor) {
const unitId = workbook.getUnitId();
const subUnitId = worksheet.getSheetId();
const subUnitRuleList = rangeRuleModel.getSubunitRuleList(unitId, subUnitId);
- const selectionRanges = selectionManagerService.getSelections()?.map((selection) => selection.range);
+ const selectionRanges = selectionManagerService.getCurrentSelections()?.map((selection) => selection.range);
const ruleRanges = subUnitRuleList.map((rule) => rule.ranges).flat();
if (!selectionRanges?.length) {
@@ -149,7 +149,7 @@ export function getPermissionDisableBase$(accessor: IAccessor) {
return of(true);
}
const unitId = workbook.getUnitId();
- const selectionManagerService = accessor.get(SelectionManagerService);
+ const selectionManagerService = accessor.get(SheetsSelectionsService);
const selectionProtectionRuleModel = accessor.get(RangeProtectionRuleModel);
const worksheetProtectionRuleModel = accessor.get(WorksheetProtectionRuleModel);
const permission$ = permissionService.composePermission$([new WorkbookManageCollaboratorPermission(unitId).id, new WorkbookEditablePermission(unitId).id]).pipe(map((permissions) => permissions.every((permission) => permission.value))) ?? of(false);
@@ -164,7 +164,7 @@ export function getPermissionDisableBase$(accessor: IAccessor) {
if (!permission) {
return true;
}
- const selections = selectionManagerService.getSelections();
+ const selections = selectionManagerService.getCurrentSelections();
const selectionRanges = selections?.map((selection) => selection.range);
if (!selectionRanges?.length) {
return false;
@@ -205,7 +205,7 @@ export function getAddPermissionDisableBase$(accessor: IAccessor) {
const subUnitId = worksheet.getSheetId();
const selectionProtectionRuleModel = accessor.get(RangeProtectionRuleModel);
const worksheetProtectionRuleModel = accessor.get(WorksheetProtectionRuleModel);
- const selectionManagerService = accessor.get(SelectionManagerService);
+ const selectionManagerService = accessor.get(SheetsSelectionsService);
const permission$ = permissionService.composePermission$([new WorkbookManageCollaboratorPermission(unitId).id, new WorkbookEditablePermission(unitId).id]).pipe(map((permissions) => permissions.every((permission) => permission.value))) ?? of(false);
const ruleChange$ = merge(
selectionProtectionRuleModel.ruleChange$,
@@ -218,7 +218,7 @@ export function getAddPermissionDisableBase$(accessor: IAccessor) {
if (!permission || focus) {
return true;
}
- const selections = selectionManagerService.getSelections();
+ const selections = selectionManagerService.getCurrentSelections();
const selectionRanges = selections?.map((selection) => selection.range);
if (!selectionRanges?.length) {
return true;
@@ -398,7 +398,7 @@ export function getRemovePermissionDisable$(accessor: IAccessor) {
if (!permission) {
return true;
}
- const selections = accessor.get(SelectionManagerService).getSelections();
+ const selections = accessor.get(SheetsSelectionsService).getCurrentSelections();
const selectionRanges = selections?.map((selection) => selection.range);
if (!selectionRanges?.length || selectionRanges.length > 1) {
return true;
diff --git a/packages/sheets-ui/src/controllers/move-range.controller.ts b/packages/sheets-ui/src/controllers/move-range.controller.ts
index ec48ee479d..29ea428e8e 100644
--- a/packages/sheets-ui/src/controllers/move-range.controller.ts
+++ b/packages/sheets-ui/src/controllers/move-range.controller.ts
@@ -14,26 +14,25 @@
* limitations under the License.
*/
-import type { IRange } from '@univerjs/core';
+import type { IRange, Workbook } from '@univerjs/core';
import {
Disposable,
DisposableCollection,
ICommandService,
- LifecycleStages,
- OnLifecycle,
toDisposable,
} from '@univerjs/core';
import type { IMoveRangeCommandParams } from '@univerjs/sheets';
-import { MoveRangeCommand, NORMAL_SELECTION_PLUGIN_NAME, SelectionManagerService } from '@univerjs/sheets';
+import { MoveRangeCommand, SheetsSelectionsService } from '@univerjs/sheets';
import { Inject } from '@wendellhu/redi';
-import { ISelectionRenderService } from '../services/selection/selection-render.service';
+import type { IRenderContext, IRenderModule } from '@univerjs/engine-render';
+import { ISheetSelectionRenderService } from '../services/selection/base-selection-render.service';
-@OnLifecycle(LifecycleStages.Steady, MoveRangeController)
-export class MoveRangeController extends Disposable {
+export class MoveRangeRenderController extends Disposable implements IRenderModule {
constructor(
- @Inject(ISelectionRenderService) private readonly _selectionRenderService: ISelectionRenderService,
- @Inject(SelectionManagerService) private readonly _selectionManagerService: SelectionManagerService,
+ private readonly _context: IRenderContext<Workbook>,
+ @Inject(ISheetSelectionRenderService) private readonly _selectionRenderService: ISheetSelectionRenderService,
+ @Inject(SheetsSelectionsService) private readonly _selectionManagerService: SheetsSelectionsService,
@Inject(ICommandService) private readonly _commandService: ICommandService
) {
super();
@@ -44,68 +43,56 @@ export class MoveRangeController extends Disposable {
const disposableCollection = new DisposableCollection();
this.disposeWithMe(
- toDisposable(
- this._selectionManagerService.selectionMoveEnd$.subscribe(() => {
- // Each range change requires re-listening
- disposableCollection.dispose();
+ this._selectionManagerService.selectionMoveEnd$.subscribe(() => {
+ // Each range change requires re-listening
+ disposableCollection.dispose();
- const current = this._selectionManagerService.getCurrent();
+ const selectionControls = this._selectionRenderService.getSelectionControls();
+ selectionControls.forEach((controlSelection) => {
+ disposableCollection.add(
+ toDisposable(
+ controlSelection.selectionMoved$.subscribe((_toRange) => {
+ if (!_toRange) {
+ return;
+ }
+ const _fromRange = controlSelection.model.getRange();
+ const fromRange: IRange = {
+ startRow: _fromRange.startRow,
+ startColumn: _fromRange.startColumn,
+ endRow: _fromRange.endRow,
+ endColumn: _fromRange.endColumn,
+ rangeType: _fromRange.rangeType,
+ };
+ const toRange: IRange = {
+ startRow: _toRange.startRow,
+ startColumn: _toRange.startColumn,
+ endRow: _toRange.endRow,
+ endColumn: _toRange.endColumn,
+ // rangeType must equal to fromRange
+ rangeType: _fromRange.rangeType,
+ };
- /**
- * Moving the selection only responds to regular selections;
- * it does not apply to selections for features like formulas or charts.
- */
- if (current?.pluginName !== NORMAL_SELECTION_PLUGIN_NAME) {
- return;
- }
+ if (
+ fromRange.startRow === toRange.startRow &&
+ fromRange.startColumn === toRange.startColumn
+ ) {
+ return;
+ }
- const selectionControls = this._selectionRenderService.getSelectionControls();
- selectionControls.forEach((controlSelection) => {
- disposableCollection.add(
- toDisposable(
- controlSelection.selectionMoved$.subscribe((_toRange) => {
- if (!_toRange) {
- return;
- }
- const _fromRange = controlSelection.model.getRange();
- const fromRange: IRange = {
- startRow: _fromRange.startRow,
- startColumn: _fromRange.startColumn,
- endRow: _fromRange.endRow,
- endColumn: _fromRange.endColumn,
- rangeType: _fromRange.rangeType,
- };
- const toRange: IRange = {
- startRow: _toRange.startRow,
- startColumn: _toRange.startColumn,
- endRow: _toRange.endRow,
- endColumn: _toRange.endColumn,
- // rangeType must equal to fromRange
- rangeType: _fromRange.rangeType,
- };
+ if (toRange.startRow < 0 || toRange.startColumn < 0) {
+ return;
+ }
- if (
- fromRange.startRow === toRange.startRow &&
- fromRange.startColumn === toRange.startColumn
- ) {
- return;
- }
-
- if (toRange.startRow < 0 || toRange.startColumn < 0) {
- return;
- }
-
- const params: IMoveRangeCommandParams = {
- fromRange,
- toRange,
- };
- this._commandService.executeCommand(MoveRangeCommand.id, params);
- })
- )
- );
- });
- })
- )
+ const params: IMoveRangeCommandParams = {
+ fromRange,
+ toRange,
+ };
+ this._commandService.executeCommand(MoveRangeCommand.id, params);
+ })
+ )
+ );
+ });
+ })
);
};
}
diff --git a/packages/sheets-ui/src/controllers/permission/sheet-permission-interceptor-base.controller.ts b/packages/sheets-ui/src/controllers/permission/sheet-permission-interceptor-base.controller.ts
index 40c138b38c..26e98c80d7 100644
--- a/packages/sheets-ui/src/controllers/permission/sheet-permission-interceptor-base.controller.ts
+++ b/packages/sheets-ui/src/controllers/permission/sheet-permission-interceptor-base.controller.ts
@@ -20,7 +20,7 @@
import type { ICellData, ICellDataForSheetInterceptor, ICommandInfo, IObjectMatrixPrimitiveType, IPermissionTypes, IRange, Nullable, Workbook, WorkbookPermissionPointConstructor, Worksheet } from '@univerjs/core';
import { Disposable, DisposableCollection, FOCUSING_EDITOR_STANDALONE, ICommandService, IContextService, IPermissionService, isICellData, IUniverInstanceService, LifecycleStages, LocaleService, ObjectMatrix, OnLifecycle, Rectangle, UniverInstanceType } from '@univerjs/core';
import type { IMoveColsCommandParams, IMoveRangeCommandParams, IMoveRowsCommandParams, ISetRangeValuesCommandParams, ISetSpecificColsVisibleCommandParams, ISetSpecificRowsVisibleCommandParams, ISetWorksheetNameMutationParams } from '@univerjs/sheets';
-import { ClearSelectionContentCommand, DeleteRangeMoveLeftCommand, DeleteRangeMoveUpCommand, DeltaColumnWidthCommand, DeltaRowHeightCommand, getSheetCommandTarget, InsertRangeMoveDownCommand, InsertRangeMoveRightCommand, MoveColsCommand, MoveRangeCommand, MoveRowsCommand, RangeProtectionPermissionEditPoint, RangeProtectionPermissionViewPoint, RangeProtectionRuleModel, SelectionManagerService, SetBackgroundColorCommand, SetColWidthCommand, SetRangeValuesCommand, SetRowHeightCommand, SetSelectedColsVisibleCommand, SetSelectedRowsVisibleCommand, SetSpecificColsVisibleCommand, SetSpecificRowsVisibleCommand, SetWorksheetNameCommand, SetWorksheetNameMutation, SetWorksheetOrderCommand, SetWorksheetRowIsAutoHeightCommand, SetWorksheetShowCommand, WorkbookCopyPermission, WorkbookEditablePermission, WorkbookHideSheetPermission, WorkbookManageCollaboratorPermission, WorkbookMoveSheetPermission, WorkbookRenameSheetPermission, WorksheetCopyPermission, WorksheetEditPermission, WorksheetProtectionRuleModel, WorksheetSetCellStylePermission, WorksheetSetCellValuePermission, WorksheetSetColumnStylePermission, WorksheetSetRowStylePermission, WorksheetViewPermission } from '@univerjs/sheets';
+import { ClearSelectionContentCommand, DeleteRangeMoveLeftCommand, DeleteRangeMoveUpCommand, DeltaColumnWidthCommand, DeltaRowHeightCommand, getSheetCommandTarget, InsertRangeMoveDownCommand, InsertRangeMoveRightCommand, MoveColsCommand, MoveRangeCommand, MoveRowsCommand, RangeProtectionPermissionEditPoint, RangeProtectionPermissionViewPoint, RangeProtectionRuleModel, SetBackgroundColorCommand, SetColWidthCommand, SetRangeValuesCommand, SetRowHeightCommand, SetSelectedColsVisibleCommand, SetSelectedRowsVisibleCommand, SetSpecificColsVisibleCommand, SetSpecificRowsVisibleCommand, SetWorksheetNameCommand, SetWorksheetNameMutation, SetWorksheetOrderCommand, SetWorksheetRowIsAutoHeightCommand, SetWorksheetShowCommand, SheetsSelectionsService, WorkbookCopyPermission, WorkbookEditablePermission, WorkbookHideSheetPermission, WorkbookManageCollaboratorPermission, WorkbookMoveSheetPermission, WorkbookRenameSheetPermission, WorksheetCopyPermission, WorksheetEditPermission, WorksheetProtectionRuleModel, WorksheetSetCellStylePermission, WorksheetSetCellValuePermission, WorksheetSetColumnStylePermission, WorksheetSetRowStylePermission, WorksheetViewPermission } from '@univerjs/sheets';
import { Inject } from '@wendellhu/redi';
import { IDialogService } from '@univerjs/ui';
import { IMEInputCommand, InsertCommand } from '@univerjs/docs';
@@ -49,7 +49,7 @@ export class SheetPermissionInterceptorBaseController extends Disposable {
@ICommandService private readonly _commandService: ICommandService,
@IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService,
@IPermissionService private readonly _permissionService: IPermissionService,
- @Inject(SelectionManagerService) private readonly _selectionManagerService: SelectionManagerService,
+ @Inject(SheetsSelectionsService) private readonly _selectionManagerService: SheetsSelectionsService,
@IDialogService private readonly _dialogService: IDialogService,
@Inject(RangeProtectionRuleModel) private _rangeProtectionRuleModel: RangeProtectionRuleModel,
@Inject(WorksheetProtectionRuleModel) private _worksheetProtectionRuleModel: WorksheetProtectionRuleModel,
@@ -318,7 +318,7 @@ export class SheetPermissionInterceptorBaseController extends Disposable {
return false;
}
const { worksheet, unitId, subUnitId } = target;
- const selectionRange = this._selectionManagerService.getLast()?.range;
+ const selectionRange = this._selectionManagerService.getCurrentLastSelection()?.range;
if (!selectionRange) {
return false;
};
@@ -363,7 +363,7 @@ export class SheetPermissionInterceptorBaseController extends Disposable {
return false;
}
const { worksheet, unitId, subUnitId } = target;
- const selection = this._selectionManagerService.getLast();
+ const selection = this._selectionManagerService.getCurrentLastSelection();
if (!selection) {
return true;
}
@@ -423,7 +423,7 @@ export class SheetPermissionInterceptorBaseController extends Disposable {
if (!subUnitId) {
subUnitId = worksheet.getSheetId();
}
- const ranges = selectionRanges ?? this._selectionManagerService.getSelections()?.map((selection) => {
+ const ranges = selectionRanges ?? this._selectionManagerService.getCurrentSelections()?.map((selection) => {
return selection.range;
});
diff --git a/packages/sheets-ui/src/controllers/permission/sheet-permission-interceptor-canvas-render.controller.ts b/packages/sheets-ui/src/controllers/permission/sheet-permission-interceptor-canvas-render.controller.ts
index 7b86a4b2ca..bd315adad3 100644
--- a/packages/sheets-ui/src/controllers/permission/sheet-permission-interceptor-canvas-render.controller.ts
+++ b/packages/sheets-ui/src/controllers/permission/sheet-permission-interceptor-canvas-render.controller.ts
@@ -16,16 +16,16 @@
import type { ICellDataForSheetInterceptor, IRange, Nullable, Workbook } from '@univerjs/core';
import { DisposableCollection, IPermissionService, IUniverInstanceService, LifecycleStages, OnLifecycle, Rectangle, RxDisposable, UniverInstanceType } from '@univerjs/core';
-import { getSheetCommandTarget, RangeProtectionRuleModel, SelectionManagerService, WorkbookEditablePermission, WorksheetEditPermission, WorksheetSetColumnStylePermission, WorksheetSetRowStylePermission } from '@univerjs/sheets';
+import { getSheetCommandTarget, RangeProtectionRuleModel, SheetsSelectionsService, WorkbookEditablePermission, WorksheetEditPermission, WorksheetSetColumnStylePermission, WorksheetSetRowStylePermission } from '@univerjs/sheets';
import { Inject, Optional } from '@wendellhu/redi';
import type { IRenderContext, IRenderModule, Scene, SpreadsheetSkeleton } from '@univerjs/engine-render';
import { UnitAction } from '@univerjs/protocol';
import { HeaderMoveRenderController } from '../render-controllers/header-move.render-controller';
import { HeaderResizeRenderController } from '../render-controllers/header-resize.render-controller';
-import { ISelectionRenderService } from '../../services/selection/selection-render.service';
import { HeaderFreezeRenderController } from '../render-controllers/freeze.render-controller';
import { getTransformCoord } from '../utils/component-tools';
+import { ISheetSelectionRenderService } from '../../services/selection/base-selection-render.service';
type ICellPermission = Record<UnitAction, boolean> & { ruleId?: string; ranges?: IRange[] };
@@ -39,10 +39,10 @@ export class SheetPermissionInterceptorCanvasRenderController extends RxDisposab
private readonly _context: IRenderContext<Workbook>,
@IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService,
@IPermissionService private readonly _permissionService: IPermissionService,
- @Inject(SelectionManagerService) private readonly _selectionManagerService: SelectionManagerService,
+ @Inject(SheetsSelectionsService) private readonly _selectionManagerService: SheetsSelectionsService,
@Inject(RangeProtectionRuleModel) private _rangeProtectionRuleModel: RangeProtectionRuleModel,
@Inject(HeaderMoveRenderController) private _headerMoveRenderController: HeaderMoveRenderController,
- @ISelectionRenderService private _selectionRenderService: ISelectionRenderService,
+ @ISheetSelectionRenderService private _selectionRenderService: ISheetSelectionRenderService,
@Inject(HeaderFreezeRenderController) private _headerFreezeRenderController: HeaderFreezeRenderController,
@Optional(HeaderResizeRenderController) private _headerResizeRenderController?: HeaderResizeRenderController
) {
@@ -191,7 +191,7 @@ export class SheetPermissionInterceptorCanvasRenderController extends RxDisposab
return false;
}
- const ranges = this._selectionManagerService.getSelections()?.map((selection) => {
+ const ranges = this._selectionManagerService.getCurrentSelections()?.map((selection) => {
return selection.range;
});
@@ -238,7 +238,7 @@ export class SheetPermissionInterceptorCanvasRenderController extends RxDisposab
return false;
}
- const ranges = this._selectionManagerService.getSelections()?.map((selection) => {
+ const ranges = this._selectionManagerService.getCurrentSelections()?.map((selection) => {
return selection.range;
});
diff --git a/packages/sheets-ui/src/controllers/permission/sheet-permission-interceptor-clipboard.controller.ts b/packages/sheets-ui/src/controllers/permission/sheet-permission-interceptor-clipboard.controller.ts
index 5d46881488..b3fad0d01b 100644
--- a/packages/sheets-ui/src/controllers/permission/sheet-permission-interceptor-clipboard.controller.ts
+++ b/packages/sheets-ui/src/controllers/permission/sheet-permission-interceptor-clipboard.controller.ts
@@ -16,7 +16,7 @@
import type { ICellDataForSheetInterceptor, IRange, Workbook } from '@univerjs/core';
import { Disposable, DisposableCollection, IUniverInstanceService, LifecycleStages, LocaleService, OnLifecycle, UniverInstanceType } from '@univerjs/core';
-import { SelectionManagerService } from '@univerjs/sheets';
+import { SheetsSelectionsService } from '@univerjs/sheets';
import { Inject } from '@wendellhu/redi';
import { UnitAction } from '@univerjs/protocol';
import { ISheetClipboardService } from '../../services/clipboard/clipboard.service';
@@ -32,7 +32,7 @@ export class SheetPermissionInterceptorClipboardController extends Disposable {
constructor(
@IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService,
- @Inject(SelectionManagerService) private readonly _selectionManagerService: SelectionManagerService,
+ @Inject(SheetsSelectionsService) private readonly _selectionManagerService: SheetsSelectionsService,
@Inject(LocaleService) private readonly _localService: LocaleService,
@Inject(ISheetClipboardService) private _sheetClipboardService: ISheetClipboardService,
@Inject(SheetPermissionInterceptorBaseController) private readonly _sheetPermissionInterceptorBaseController: SheetPermissionInterceptorBaseController
@@ -47,7 +47,7 @@ export class SheetPermissionInterceptorClipboardController extends Disposable {
id: SHEET_PERMISSION_PASTE_PLUGIN,
onBeforePaste: (pasteTo) => {
const [ranges] = virtualizeDiscreteRanges([pasteTo.range]).ranges;
- const startRange = this._selectionManagerService.getLast()?.range;
+ const startRange = this._selectionManagerService.getCurrentLastSelection()?.range;
if (!startRange) {
return false;
}
diff --git a/packages/sheets-ui/src/controllers/render-controllers/contextmenu.render-controller.ts b/packages/sheets-ui/src/controllers/render-controllers/contextmenu.render-controller.ts
index cf6f059fb3..3c1c9d1db4 100644
--- a/packages/sheets-ui/src/controllers/render-controllers/contextmenu.render-controller.ts
+++ b/packages/sheets-ui/src/controllers/render-controllers/contextmenu.render-controller.ts
@@ -21,13 +21,14 @@ import {
RANGE_TYPE,
} from '@univerjs/core';
import type { IRenderContext, IRenderModule, Spreadsheet, SpreadsheetColumnHeader, SpreadsheetHeader } from '@univerjs/engine-render';
-import { SelectionManagerService } from '@univerjs/sheets';
+import { SheetsSelectionsService } from '@univerjs/sheets';
import { IContextMenuService, MenuPosition } from '@univerjs/ui';
import { Inject } from '@wendellhu/redi';
-import { ISelectionRenderService } from '../../services/selection/selection-render.service';
import { SheetMenuPosition } from '../menu/menu';
import { SHEET_VIEW_KEY } from '../../common/keys';
+import { ISheetSelectionRenderService } from '../../services/selection/base-selection-render.service';
+import { attachSelectionWithCoord } from '../../services/selection/util';
/**
* This controller subscribe to context menu events in sheet rendering views and invoke context menu at a correct
@@ -37,8 +38,8 @@ export class SheetContextMenuRenderController extends Disposable implements IRen
constructor(
private readonly _context: IRenderContext<Workbook>,
@IContextMenuService private readonly _contextMenuService: IContextMenuService,
- @Inject(SelectionManagerService) private readonly _selectionManagerService: SelectionManagerService,
- @ISelectionRenderService private readonly _selectionRenderService: ISelectionRenderService
+ @Inject(SheetsSelectionsService) private readonly _selectionManagerService: SheetsSelectionsService,
+ @ISheetSelectionRenderService private readonly _selectionRenderService: ISheetSelectionRenderService
) {
super();
@@ -51,13 +52,15 @@ export class SheetContextMenuRenderController extends Disposable implements IRen
// Content range context menu
const spreadsheetSubscription = spreadsheetPointerDownObserver.subscribeEvent((event) => {
if (event.button === 2) {
- const selections = this._selectionManagerService.getSelections();
+ const selections = this._selectionManagerService.getCurrentSelections();
const currentSelection = selections?.[0];
if (!currentSelection) {
return;
}
const rangeType = currentSelection.range.rangeType;
- const range = this._selectionRenderService.attachSelectionWithCoord(currentSelection).rangeWithCoord;
+ const skeleton = this._selectionRenderService.getSkeleton();
+ const selectionRangeWithCoord = attachSelectionWithCoord(currentSelection, skeleton);
+ const range = selectionRangeWithCoord.rangeWithCoord;
const isPointerInRange = () => {
if (!range) {
return false;
diff --git a/packages/sheets-ui/src/controllers/render-controllers/editor-bridge.render-controller.ts b/packages/sheets-ui/src/controllers/render-controllers/editor-bridge.render-controller.ts
index beb770a616..70ba147000 100644
--- a/packages/sheets-ui/src/controllers/render-controllers/editor-bridge.render-controller.ts
+++ b/packages/sheets-ui/src/controllers/render-controllers/editor-bridge.render-controller.ts
@@ -21,9 +21,8 @@ import { DeviceInputEventType } from '@univerjs/engine-render';
import type { ISelectionWithStyle } from '@univerjs/sheets';
import {
COMMAND_LISTENER_SKELETON_CHANGE,
- NORMAL_SELECTION_PLUGIN_NAME,
- SelectionManagerService,
SetWorksheetActiveOperation,
+ SheetsSelectionsService,
} from '@univerjs/sheets';
import { Inject } from '@wendellhu/redi';
import { merge, takeUntil } from 'rxjs';
@@ -40,7 +39,7 @@ export class EditorBridgeRenderController extends RxDisposable implements IRende
private readonly _context: IRenderContext<Workbook>,
@ICommandService private readonly _commandService: ICommandService,
@IEditorBridgeService private readonly _editorBridgeService: IEditorBridgeService,
- @Inject(SelectionManagerService) private readonly _selectionManagerService: SelectionManagerService,
+ @Inject(SheetsSelectionsService) private readonly _selectionManagerService: SheetsSelectionsService,
@IRangeSelectorService private readonly _rangeSelectorService: IRangeSelectorService
) {
super();
@@ -82,10 +81,7 @@ export class EditorBridgeRenderController extends RxDisposable implements IRende
}
private _handleSelectionChange(params: Nullable<ISelectionWithStyle[]>) {
- const current = this._selectionManagerService.getCurrent();
-
// The editor only responds to regular selections.
- if (current?.pluginName !== NORMAL_SELECTION_PLUGIN_NAME) return;
if (this._editorBridgeService.isVisible().visible) return;
const primary = params?.[params.length - 1]?.primary;
@@ -104,12 +100,6 @@ export class EditorBridgeRenderController extends RxDisposable implements IRende
return;
}
- const current = this._selectionManagerService.getCurrent();
- if (current?.pluginName !== NORMAL_SELECTION_PLUGIN_NAME) {
- return;
- }
-
- // this._editorBridgeService.show(DeviceInputEventType.Dblclick);
this._commandService.executeCommand(SetCellEditVisibleOperation.id, {
visible: true,
eventType: DeviceInputEventType.Dblclick,
@@ -137,25 +127,10 @@ export class EditorBridgeRenderController extends RxDisposable implements IRende
return;
}
- this._selectionManagerService.makeDirty(false);
this._commandService.executeCommand(SetCellEditVisibleOperation.id, {
visible: false,
eventType: DeviceInputEventType.PointerDown,
});
-
- /**
- * Hiding the editor triggers a SetRangeValuesMutation which saves the content.
- * This mutation, in turn, triggers a refresh of the skeleton,
- * causing the selection to update. In most scenarios,
- * this update is reasonable. However, when clicking on another cell and exiting the edit,
- * this causes the selection to be reset. Therefore,
- * a makeDirty method has been added here to block the refresh of selection.
- * The reason for using setTimeout is that it needs to wait for the process
- * to finish before allowing the refresh of the selection.
- */
- setTimeout(() => {
- this._selectionManagerService.makeDirty(true);
- }, 0);
}
private _initialRangeSelector() {
@@ -169,7 +144,7 @@ export class EditorBridgeRenderController extends RxDisposable implements IRende
*/
this.disposeWithMe(
this._rangeSelectorService.openSelector$.subscribe(() => {
- const selectionWithStyle = this._selectionManagerService.getSelections();
+ const selectionWithStyle = this._selectionManagerService.getCurrentSelections();
const { unitId, sheetId, sheetName } = this._getCurrentUnitIdAndSheetId();
if (!sheetId || !sheetName) return;
diff --git a/packages/sheets-ui/src/controllers/render-controllers/freeze.render-controller.ts b/packages/sheets-ui/src/controllers/render-controllers/freeze.render-controller.ts
index c63cd0b366..87f4f5f893 100644
--- a/packages/sheets-ui/src/controllers/render-controllers/freeze.render-controller.ts
+++ b/packages/sheets-ui/src/controllers/render-controllers/freeze.render-controller.ts
@@ -50,7 +50,6 @@ import {
MoveRowsCommand,
RemoveColCommand,
RemoveRowCommand,
- SelectionManagerService,
SetColHiddenMutation,
SetColVisibleMutation,
SetFrozenCommand,
@@ -63,6 +62,7 @@ import {
SetWorksheetRowAutoHeightMutation,
SetWorksheetRowHeightMutation,
SheetInterceptorService,
+ SheetsSelectionsService,
} from '@univerjs/sheets';
import { Inject, Injector } from '@wendellhu/redi';
@@ -148,7 +148,7 @@ export class HeaderFreezeRenderController extends Disposable implements IRenderM
// @IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService,
@ICommandService private readonly _commandService: ICommandService,
// @IRenderManagerService private readonly _renderManagerService: IRenderManagerService,
- @Inject(SelectionManagerService) private readonly _selectionManagerService: SelectionManagerService,
+ @Inject(SheetsSelectionsService) private readonly _selectionManagerService: SheetsSelectionsService,
@Inject(ScrollManagerService) private readonly _scrollManagerService: ScrollManagerService,
@Inject(ThemeService) private readonly _themeService: ThemeService,
@Inject(SheetInterceptorService) private _sheetInterceptorService: SheetInterceptorService,
@@ -1218,7 +1218,7 @@ export class HeaderFreezeRenderController extends Disposable implements IRenderM
}
if (command.id === MoveColsCommand.id) {
- const selections = this._selectionManagerService.getSelections();
+ const selections = this._selectionManagerService.getCurrentSelections();
const {
fromRange: { startColumn: fromCol },
toRange: { startColumn: toCol },
@@ -1282,7 +1282,7 @@ export class HeaderFreezeRenderController extends Disposable implements IRenderM
}
if (command.id === MoveRowsCommand.id) {
- const selections = this._selectionManagerService.getSelections();
+ const selections = this._selectionManagerService.getCurrentSelections();
const {
fromRange: { startRow: fromRow },
toRange: { startRow: toRow },
diff --git a/packages/sheets-ui/src/controllers/render-controllers/header-menu.render-controller.ts b/packages/sheets-ui/src/controllers/render-controllers/header-menu.render-controller.ts
index 53e8ab97f1..4912fb9f1e 100644
--- a/packages/sheets-ui/src/controllers/render-controllers/header-menu.render-controller.ts
+++ b/packages/sheets-ui/src/controllers/render-controllers/header-menu.render-controller.ts
@@ -23,7 +23,7 @@ import {
import type { IMouseEvent, IPointerEvent, IRenderContext, IRenderModule, SpreadsheetColumnHeader, SpreadsheetHeader } from '@univerjs/engine-render';
import { CURSOR_TYPE, Rect } from '@univerjs/engine-render';
import type { ISetSelectionsOperationParams } from '@univerjs/sheets';
-import { NORMAL_SELECTION_PLUGIN_NAME, SelectionManagerService, SetSelectionsOperation } from '@univerjs/sheets';
+import { SetSelectionsOperation, SheetsSelectionsService } from '@univerjs/sheets';
import { IContextMenuService } from '@univerjs/ui';
import { Inject } from '@wendellhu/redi';
@@ -70,7 +70,7 @@ export class HeaderMenuRenderController extends Disposable implements IRenderMod
@Inject(SheetSkeletonManagerService) private readonly _sheetSkeletonManagerService: SheetSkeletonManagerService,
@IContextMenuService private readonly _contextMenuService: IContextMenuService,
@ICommandService private readonly _commandService: ICommandService,
- @Inject(SelectionManagerService) private readonly _selectionManagerService: SelectionManagerService
+ @Inject(SheetsSelectionsService) private readonly _selectionManagerService: SheetsSelectionsService
) {
super();
@@ -240,7 +240,7 @@ export class HeaderMenuRenderController extends Disposable implements IRenderMod
this._hoverMenu.onPointerDown$.subscribeEvent((evt: IPointerEvent | IMouseEvent) => {
const currentColumn = this._currentColumn;
- const currentSelectionDatas = this._selectionManagerService.getSelectionRanges();
+ const currentSelectionDatas = this._selectionManagerService.getCurrentSelections()?.map((s) => s.range);
const menuInSelections: boolean = !!currentSelectionDatas
?.filter((range) => range.rangeType === RANGE_TYPE.COLUMN)
.find((data) => {
@@ -274,7 +274,7 @@ export class HeaderMenuRenderController extends Disposable implements IRenderMod
return {
unitId: workbook.getUnitId(),
subUnitId: worksheet.getSheetId(),
- pluginName: NORMAL_SELECTION_PLUGIN_NAME,
+
selections: [
{
range: {
diff --git a/packages/sheets-ui/src/controllers/render-controllers/header-move.render-controller.ts b/packages/sheets-ui/src/controllers/render-controllers/header-move.render-controller.ts
index d0b0a978a9..c47d43a415 100644
--- a/packages/sheets-ui/src/controllers/render-controllers/header-move.render-controller.ts
+++ b/packages/sheets-ui/src/controllers/render-controllers/header-move.render-controller.ts
@@ -14,11 +14,14 @@
* limitations under the License.
*/
-import type { IRange, Nullable, Workbook } from '@univerjs/core';
+import type {
+ EventState,
+ IRange,
+ Nullable,
+ Workbook,
+} from '@univerjs/core';
import {
- createInterceptorKey,
- Disposable,
- ICommandService,
+ createInterceptorKey, Disposable, ICommandService,
InterceptorManager,
RANGE_TYPE,
} from '@univerjs/core';
@@ -31,20 +34,19 @@ import {
SHEET_VIEWPORT_KEY,
Vector2,
} from '@univerjs/engine-render';
-import type { IMoveColsCommandParams, IMoveRowsCommandParams, ISelectionWithStyle } from '@univerjs/sheets';
+import type { IMoveColsCommandParams, IMoveRowsCommandParams, ISelectionWithStyle, WorkbookSelections } from '@univerjs/sheets';
import {
MoveColsCommand,
MoveRowsCommand,
- NORMAL_SELECTION_PLUGIN_NAME,
- SelectionManagerService,
+ SheetsSelectionsService,
} from '@univerjs/sheets';
import { Inject } from '@wendellhu/redi';
import { Subscription } from 'rxjs';
import { SHEET_COMPONENT_HEADER_LAYER_INDEX, SHEET_VIEW_KEY } from '../../common/keys';
-import { ISelectionRenderService } from '../../services/selection/selection-render.service';
import { SheetSkeletonManagerService } from '../../services/sheet-skeleton-manager.service';
import { getCoordByOffset } from '../utils/component-tools';
+import { checkInHeaderRanges } from '../utils/selections-tools';
const HEADER_MOVE_CONTROLLER_BACKGROUND = '__SpreadsheetHeaderMoveControllerBackground__';
@@ -56,70 +58,48 @@ const HEADER_MOVE_CONTROLLER_LINE_FILL = 'rgb(119, 119, 119)';
const HEADER_MOVE_CONTROLLER_LINE_SIZE = 4;
-enum HEADER_MOVE_TYPE {
- ROW,
- COLUMN,
-}
-
export const HEADER_MOVE_PERMISSION_CHECK = createInterceptorKey<boolean, IRange>('headerMovePermissionCheck');
export class HeaderMoveRenderController extends Disposable implements IRenderModule {
private _startOffsetX: number = Number.NEGATIVE_INFINITY;
-
private _startOffsetY: number = Number.NEGATIVE_INFINITY;
private _moveHelperBackgroundShape: Nullable<Rect>;
-
private _moveHelperLineShape: Nullable<Rect>;
private _headerPointerDownSubs: Nullable<Subscription>;
-
private _headerPointerMoveSubs: Nullable<Subscription>;
-
private _headerPointerLeaveSubs: Nullable<Subscription>;
- // /** @deprecated */
- // private _rowOrColumnDownObservers: Array<Nullable<Observer<IPointerEvent | IMouseEvent>>> = [];
-
- // private _rowOrColumnMoveObservers: Array<Nullable<Observer<IPointerEvent | IMouseEvent>>> = [];
-
- // private _rowOrColumnLeaveObservers: Array<Nullable<Observer<IPointerEvent | IMouseEvent>>> = [];
-
private _scenePointerMoveSub: Nullable<Subscription>;
-
private _scenePointerUpSub: Nullable<Subscription>;
private _scrollTimer: Nullable<ScrollTimer>;
private _changeFromColumn = -1;
-
private _changeFromRow = -1;
-
private _changeToColumn = -1;
-
private _changeToRow = -1;
- public interceptor = new InterceptorManager({ HEADER_MOVE_PERMISSION_CHECK });
- // private _colHeaderPointerMoveSub: Nullable<Subscription>;
- // private _rowHeaderPointerMoveSub: Nullable<Subscription>;
+ public readonly interceptor = new InterceptorManager({ HEADER_MOVE_PERMISSION_CHECK });
- override dispose(): void {
- this._moveHelperBackgroundShape?.dispose();
- this._moveHelperLineShape?.dispose();
+ private readonly _workbookSelections: WorkbookSelections;
- // const spreadsheetColumnHeader = this._context.components.get(SHEET_VIEW_KEY.COLUMN) as SpreadsheetColumnHeader;
- // const spreadsheetRowHeader = this._context.components.get(SHEET_VIEW_KEY.ROW) as SpreadsheetHeader;
- // const scene = this._context.scene;
+ constructor(
+ private readonly _context: IRenderContext<Workbook>,
+ @Inject(SheetsSelectionsService) selectionManagerService: SheetsSelectionsService,
+ @Inject(SheetSkeletonManagerService) private readonly _sheetSkeletonManagerService: SheetSkeletonManagerService,
+ @ICommandService private readonly _commandService: ICommandService
+ ) {
+ super();
- // this._rowOrColumnMoveObservers.forEach((obs) => {
- // spreadsheetRowHeader.onPointerMoveObserver.remove(obs);
- // spreadsheetColumnHeader.onPointerMoveObserver.remove(obs);
- // });
+ this._workbookSelections = selectionManagerService.getWorkbookSelections(this._context.unitId);
+ this._init();
+ }
- // this._rowOrColumnLeaveObservers.forEach((obs) => {
- // spreadsheetRowHeader.onPointerLeave$.remove(obs);
- // spreadsheetColumnHeader.onPointerLeave$.remove(obs);
- // });
+ override dispose(): void {
+ this._moveHelperBackgroundShape?.dispose();
+ this._moveHelperLineShape?.dispose();
this._headerPointerMoveSubs?.unsubscribe();
this._headerPointerLeaveSubs?.unsubscribe();
@@ -137,31 +117,18 @@ export class HeaderMoveRenderController extends Disposable implements IRenderMod
this._scrollTimer?.dispose();
}
- constructor(
- private readonly _context: IRenderContext<Workbook>,
- @Inject(SheetSkeletonManagerService) private readonly _sheetSkeletonManagerService: SheetSkeletonManagerService,
- @ICommandService private readonly _commandService: ICommandService,
- @ISelectionRenderService private readonly _selectionRenderService: ISelectionRenderService,
- @Inject(SelectionManagerService) private readonly _selectionManagerService: SelectionManagerService
- ) {
- super();
-
- this._initialize();
- }
-
- private _initialize() {
- this._initialRowOrColumn(HEADER_MOVE_TYPE.ROW);
-
- this._initialRowOrColumn(HEADER_MOVE_TYPE.COLUMN);
+ private _init() {
+ this._initialRowOrColumn(RANGE_TYPE.ROW);
+ this._initialRowOrColumn(RANGE_TYPE.COLUMN);
}
// eslint-disable-next-line max-lines-per-function
- private _initialRowOrColumn(initialType: HEADER_MOVE_TYPE = HEADER_MOVE_TYPE.ROW) {
+ private _initialRowOrColumn(initialType: RANGE_TYPE.ROW | RANGE_TYPE.COLUMN = RANGE_TYPE.ROW) {
const spreadsheetColumnHeader = this._context.components.get(SHEET_VIEW_KEY.COLUMN) as SpreadsheetColumnHeader;
const spreadsheetRowHeader = this._context.components.get(SHEET_VIEW_KEY.ROW) as SpreadsheetHeader;
const scene = this._context.scene;
const eventBindingObject =
- initialType === HEADER_MOVE_TYPE.ROW ? spreadsheetRowHeader : spreadsheetColumnHeader;
+ initialType === RANGE_TYPE.ROW ? spreadsheetRowHeader : spreadsheetColumnHeader;
const pointerMoveHandler = (evt: IPointerEvent | IMouseEvent) => {
const skeleton = this._sheetSkeletonManagerService.getCurrent()?.skeleton;
@@ -169,7 +136,7 @@ export class HeaderMoveRenderController extends Disposable implements IRenderMod
return;
}
- const selectionRange = this._selectionManagerService.getLast()?.range;
+ const selectionRange = this._workbookSelections.getCurrentLastSelection()?.range;
if (!selectionRange) return;
const permissionCheck = this.interceptor.fetchThroughInterceptors(HEADER_MOVE_PERMISSION_CHECK)(false, selectionRange);
@@ -178,50 +145,48 @@ export class HeaderMoveRenderController extends Disposable implements IRenderMod
return;
}
+ const currentSelections = this._workbookSelections.getCurrentSelections();
const { row, column } = getCoordByOffset(evt.offsetX, evt.offsetY, scene, skeleton);
-
- const matchSelectionData = this._checkInHeaderRange(
- initialType === HEADER_MOVE_TYPE.ROW ? row : column,
+ const matchSelectionData = checkInHeaderRanges(
+ currentSelections,
+ initialType === RANGE_TYPE.ROW ? row : column,
initialType
);
if (matchSelectionData === false) {
scene.resetCursor();
- this._selectionRenderService.enableSelection();
return;
}
scene.setCursor(CURSOR_TYPE.GRAB);
-
- this._selectionRenderService.disableSelection();
};
const pointerLeaveHandler = () => {
this._moveHelperBackgroundShape?.hide();
this._moveHelperLineShape?.hide();
scene.resetCursor();
- this._selectionRenderService.enableSelection();
};
// eslint-disable-next-line max-lines-per-function
- const pointerDownHandler = (evt: IPointerEvent | IMouseEvent) => {
+ const pointerDownHandler = (evt: IPointerEvent | IMouseEvent, state: EventState) => {
+ if (state.isStopPropagation) return;
+
const skeleton = this._sheetSkeletonManagerService.getCurrent()?.skeleton;
if (skeleton == null) {
return;
}
- const selectionRange = this._selectionManagerService.getLast()?.range;
+ const selectionRange = this._workbookSelections.getCurrentLastSelection()?.range;
if (!selectionRange) return;
const permissionCheck = this.interceptor.fetchThroughInterceptors(HEADER_MOVE_PERMISSION_CHECK)(false, selectionRange);
-
if (!permissionCheck) {
return;
}
const { offsetX: evtOffsetX, offsetY: evtOffsetY } = evt;
- const relativeCoords = scene.getRelativeCoord(Vector2.FromArray([evtOffsetX, evtOffsetY]));
+ const relativeCoords = scene.getRelativeToViewportCoord(Vector2.FromArray([evtOffsetX, evtOffsetY]));
const { x: newEvtOffsetX, y: newEvtOffsetY } = relativeCoords;
@@ -233,7 +198,7 @@ export class HeaderMoveRenderController extends Disposable implements IRenderMod
let scrollType: ScrollTimerType;
- if (initialType === HEADER_MOVE_TYPE.ROW) {
+ if (initialType === RANGE_TYPE.ROW) {
this._changeFromRow = row;
scrollType = ScrollTimerType.Y;
} else {
@@ -241,8 +206,10 @@ export class HeaderMoveRenderController extends Disposable implements IRenderMod
scrollType = ScrollTimerType.X;
}
- const matchSelectionData = this._checkInHeaderRange(
- initialType === HEADER_MOVE_TYPE.ROW ? row : column,
+ const currentSelections = this._workbookSelections.getCurrentSelections();
+ const matchSelectionData = checkInHeaderRanges(
+ currentSelections,
+ initialType === RANGE_TYPE.ROW ? row : column,
initialType
);
@@ -250,7 +217,7 @@ export class HeaderMoveRenderController extends Disposable implements IRenderMod
return;
}
- const startScrollXY = scene.getScrollXYByRelativeCoords(
+ const startScrollXY = scene.getVpScrollXYInfoByPosToVp(
Vector2.FromArray([this._startOffsetX, this._startOffsetY])
);
@@ -282,7 +249,7 @@ export class HeaderMoveRenderController extends Disposable implements IRenderMod
initScrollTimer();
const { offsetX: moveOffsetX, offsetY: moveOffsetY } = moveEvt;
- const { x: newMoveOffsetX, y: newMoveOffsetY } = scene.getRelativeCoord(
+ const { x: newMoveOffsetX, y: newMoveOffsetY } = scene.getRelativeToViewportCoord(
Vector2.FromArray([moveOffsetX, moveOffsetY])
);
@@ -316,9 +283,9 @@ export class HeaderMoveRenderController extends Disposable implements IRenderMod
// when multi ranges are selected, we should only move the range that contains
// `changeFromRow`
- const selections = this._selectionManagerService.getSelections();
+ const selections = this._workbookSelections.getCurrentSelections();
- if (initialType === HEADER_MOVE_TYPE.ROW) {
+ if (initialType === RANGE_TYPE.ROW) {
if (this._changeFromRow !== this._changeToRow && this._changeToRow !== -1) {
const filteredSelections =
selections?.filter(
@@ -393,7 +360,7 @@ export class HeaderMoveRenderController extends Disposable implements IRenderMod
x: number;
y: number;
},
- initialType: HEADER_MOVE_TYPE
+ initialType: RANGE_TYPE.ROW | RANGE_TYPE.COLUMN
) {
const scene = this._context.scene;
const skeleton = this._sheetSkeletonManagerService.getCurrent()?.skeleton;
@@ -404,7 +371,7 @@ export class HeaderMoveRenderController extends Disposable implements IRenderMod
const { rowHeaderWidth, columnHeaderHeight, rowTotalHeight, columnTotalWidth } = skeleton;
// const scrollXY = scene.getScrollXYByRelativeCoords(Vector2.FromArray([this._startOffsetX, this._startOffsetY]));
- const scrollXY = scene.getScrollXY(scene.getViewport(SHEET_VIEWPORT_KEY.VIEW_MAIN)!);
+ const scrollXY = scene.getViewportScrollXY(scene.getViewport(SHEET_VIEWPORT_KEY.VIEW_MAIN)!);
const { scaleX, scaleY } = scene.getAncestorScale();
const moveActualSelection = skeleton.getCellPositionByOffset(
@@ -421,7 +388,7 @@ export class HeaderMoveRenderController extends Disposable implements IRenderMod
const { startX: cellStartX, startY: cellStartY, endX: cellEndX, endY: cellEndY } = startCell;
- const selectionWithCoord = this._selectionRenderService.attachRangeWithCoord(matchSelectionData.range);
+ const selectionWithCoord = this._sheetSkeletonManagerService.attachRangeWithCoord(matchSelectionData.range);
if (selectionWithCoord == null) {
return;
@@ -441,7 +408,7 @@ export class HeaderMoveRenderController extends Disposable implements IRenderMod
endColumn: selectedEndColumn,
} = selectionWithCoord;
- if (initialType === HEADER_MOVE_TYPE.ROW) {
+ if (initialType === RANGE_TYPE.ROW) {
this._moveHelperBackgroundShape?.transformByState({
height: selectedEndY - selectedStartY,
width: columnTotalWidth + rowHeaderWidth,
@@ -461,7 +428,7 @@ export class HeaderMoveRenderController extends Disposable implements IRenderMod
const HEADER_MOVE_CONTROLLER_LINE_SIZE_SCALE = HEADER_MOVE_CONTROLLER_LINE_SIZE / scale;
- if (initialType === HEADER_MOVE_TYPE.ROW) {
+ if (initialType === RANGE_TYPE.ROW) {
let top = 0;
if (row <= selectedStartRow) {
top = cellStartY - HEADER_MOVE_CONTROLLER_LINE_SIZE_SCALE / 2;
@@ -502,46 +469,6 @@ export class HeaderMoveRenderController extends Disposable implements IRenderMod
this._moveHelperLineShape?.show();
}
- private _checkInHeaderRange(rowOrColumn: number, type: HEADER_MOVE_TYPE = HEADER_MOVE_TYPE.ROW) {
- const selections = this._selectionManagerService.getSelections();
-
- const pluginName = this._selectionManagerService.getCurrent()?.pluginName;
-
- if (pluginName !== NORMAL_SELECTION_PLUGIN_NAME) {
- return false;
- }
-
- const matchSelectionData = selections?.find((data) => {
- const range = data.range;
- const { startRow, endRow, startColumn, endColumn, rangeType } = range;
- if (type === HEADER_MOVE_TYPE.COLUMN) {
- if (rowOrColumn >= startColumn && rowOrColumn <= endColumn && RANGE_TYPE.COLUMN === rangeType) {
- return true;
- }
- return false;
- }
-
- if (rowOrColumn >= startRow && rowOrColumn <= endRow && RANGE_TYPE.ROW === rangeType) {
- return true;
- }
- return false;
- });
-
- const range = matchSelectionData?.range;
- if (
- matchSelectionData == null ||
- range == null ||
- range.rangeType === RANGE_TYPE.ALL ||
- range.rangeType === RANGE_TYPE.NORMAL ||
- (range.rangeType === RANGE_TYPE.ROW && type !== HEADER_MOVE_TYPE.ROW) ||
- (range.rangeType === RANGE_TYPE.COLUMN && type !== HEADER_MOVE_TYPE.COLUMN)
- ) {
- return false;
- }
-
- return matchSelectionData;
- }
-
private _clearObserverEvent() {
// const scene = this._context.scene;
// scene.onPointerMove$.remove(this._scenePointerMoveSub);
diff --git a/packages/sheets-ui/src/controllers/render-controllers/header-resize.render-controller.ts b/packages/sheets-ui/src/controllers/render-controllers/header-resize.render-controller.ts
index d5c3c7dc4c..d5b61c91e3 100644
--- a/packages/sheets-ui/src/controllers/render-controllers/header-resize.render-controller.ts
+++ b/packages/sheets-ui/src/controllers/render-controllers/header-resize.render-controller.ts
@@ -378,11 +378,11 @@ export class HeaderResizeRenderController extends Disposable implements IRenderM
// });
this._scenePointerMoveSub = scene.onPointerMove$.subscribeEvent((moveEvt: IPointerEvent | IMouseEvent) => {
- const relativeCoords = scene.getRelativeCoord(
+ const relativeCoords = scene.getRelativeToViewportCoord(
Vector2.FromArray([this._startOffsetX, this._startOffsetY])
);
- const scrollXY = scene.getScrollXYByRelativeCoords(relativeCoords, viewPort);
+ const scrollXY = scene.getVpScrollXYInfoByPosToVp(relativeCoords, viewPort);
const transformCoord = getTransformCoord(moveEvt.offsetX, moveEvt.offsetY, scene, skeleton);
diff --git a/packages/sheets-ui/src/controllers/render-controllers/header-unhide.render-controller.ts b/packages/sheets-ui/src/controllers/render-controllers/header-unhide.render-controller.ts
index 4ed99477ec..3b705ab13f 100644
--- a/packages/sheets-ui/src/controllers/render-controllers/header-unhide.render-controller.ts
+++ b/packages/sheets-ui/src/controllers/render-controllers/header-unhide.render-controller.ts
@@ -118,7 +118,7 @@ export class HeaderUnhideRenderController extends RxDisposable {
}
private _update(workbook: Workbook, worksheet: Worksheet): void {
- const skeleton = this._sheetSkeletonManagerService.getUnitSkeleton(workbook.getUnitId(), worksheet.getSheetId())?.skeleton;
+ const skeleton = this._sheetSkeletonManagerService.getWorksheetSkeleton(worksheet.getSheetId())?.skeleton;
if (!skeleton) return;
// steps to render the unhide button for the current worksheet
diff --git a/packages/sheets-ui/src/controllers/render-controllers/mobile/mobile-contextmenu.render-controller.ts b/packages/sheets-ui/src/controllers/render-controllers/mobile/mobile-contextmenu.render-controller.ts
index c85780b030..be600d5a38 100644
--- a/packages/sheets-ui/src/controllers/render-controllers/mobile/mobile-contextmenu.render-controller.ts
+++ b/packages/sheets-ui/src/controllers/render-controllers/mobile/mobile-contextmenu.render-controller.ts
@@ -14,14 +14,13 @@
* limitations under the License.
*/
-import type { Nullable, Workbook } from '@univerjs/core';
+import type { Workbook } from '@univerjs/core';
import { Disposable, RANGE_TYPE, Tools } from '@univerjs/core';
import { type IPointerEvent, type IRenderContext, type IRenderModule, SHEET_VIEWPORT_KEY } from '@univerjs/engine-render';
+import { type ISelectionWithStyle, SheetsSelectionsService } from '@univerjs/sheets';
import { IContextMenuService, ILayoutService, MenuPosition } from '@univerjs/ui';
-import type { ISelectionWithStyle } from '@univerjs/sheets';
-import { SelectionManagerService } from '@univerjs/sheets';
import { Inject } from '@wendellhu/redi';
-import { ISelectionRenderService } from '../../../services/selection/selection-render.service';
+import { ISheetSelectionRenderService } from '../../../services/selection/base-selection-render.service';
/**
* On mobile devices, the context menu would popup when
@@ -33,8 +32,8 @@ export class SheetContextMenuMobileRenderController extends Disposable implement
private readonly _context: IRenderContext<Workbook>,
@ILayoutService private readonly _layoutService: ILayoutService,
@IContextMenuService private readonly _contextMenuService: IContextMenuService,
- @Inject(SelectionManagerService) private readonly _selectionManagerService: SelectionManagerService,
- @ISelectionRenderService private readonly _selectionRenderService: ISelectionRenderService
+ @Inject(SheetsSelectionsService) private readonly _selectionManagerService: SheetsSelectionsService,
+ @ISheetSelectionRenderService private readonly _selectionRenderService: ISheetSelectionRenderService
) {
super();
@@ -43,9 +42,8 @@ export class SheetContextMenuMobileRenderController extends Disposable implement
private _init(): void {
let listenToSelectionChangeEvent = false;
-
this.disposeWithMe(this._selectionManagerService.selectionMoveStart$.subscribe(() => listenToSelectionChangeEvent = true));
- this.disposeWithMe(this._selectionManagerService.selectionMoveEnd$.subscribe((selectionsList: Nullable<ISelectionWithStyle[]>) => {
+ this.disposeWithMe(this._selectionManagerService.selectionMoveEnd$.subscribe((selectionsList: ISelectionWithStyle[]) => {
if (!selectionsList || listenToSelectionChangeEvent === false) {
return;
}
@@ -60,7 +58,7 @@ export class SheetContextMenuMobileRenderController extends Disposable implement
if (!selectionRangeWithStyle.primary) return;
const canvasRect = this._layoutService.getCanvasElement().getBoundingClientRect();
- const range = this._selectionRenderService.attachSelectionWithCoord(selectionRangeWithStyle);
+ const range = this._selectionRenderService.attachSelectionWithCoord(selectionRangeWithStyle as unknown as ISelectionWithStyle);
const rangeType = selectionRangeWithStyle.range.rangeType;
const { scene } = this._context;
@@ -89,7 +87,13 @@ export class SheetContextMenuMobileRenderController extends Disposable implement
clientX = (canvasRect.width - rowHeaderWidth) / 2 + 20;
clientY = range.rangeWithCoord.endY + canvasRect.top - viewportScrollY;
break;
+ case RANGE_TYPE.ALL:
+ clientX = range.rangeWithCoord.startX + canvasRect.left;
+ clientY = range.rangeWithCoord.startY + canvasRect.top;
+ break;
default:
+ clientX = range.rangeWithCoord.startX + canvasRect.left - viewportScrollX;
+ clientY = range.rangeWithCoord.endY + canvasRect.top - viewportScrollY;
break;
}
// in case clientXY is not in screen area.
diff --git a/packages/sheets-ui/src/controllers/render-controllers/mobile/mobile-scroll.render-controller.ts b/packages/sheets-ui/src/controllers/render-controllers/mobile/mobile-scroll.render-controller.ts
index 2de216f0a5..95a261cb05 100644
--- a/packages/sheets-ui/src/controllers/render-controllers/mobile/mobile-scroll.render-controller.ts
+++ b/packages/sheets-ui/src/controllers/render-controllers/mobile/mobile-scroll.render-controller.ts
@@ -26,7 +26,7 @@ import {
} from '@univerjs/core';
import type { IMouseEvent, IPoint, IPointerEvent, IRenderContext, IRenderModule, IScrollObserverParam } from '@univerjs/engine-render';
import { IRenderManagerService, SHEET_VIEWPORT_KEY } from '@univerjs/engine-render';
-import { ScrollToCellOperation, SelectionManagerService } from '@univerjs/sheets';
+import { ScrollToCellOperation, SheetsSelectionsService } from '@univerjs/sheets';
import { Inject } from '@wendellhu/redi';
import { ScrollCommand, SetScrollRelativeCommand } from '../../../commands/commands/set-scroll.command';
@@ -49,7 +49,7 @@ export class MobileSheetsScrollRenderController extends Disposable implements IR
@Inject(SheetSkeletonManagerService) private readonly _sheetSkeletonManagerService: SheetSkeletonManagerService,
@ICommandService private readonly _commandService: ICommandService,
@IRenderManagerService private readonly _renderManagerService: IRenderManagerService,
- @Inject(SelectionManagerService) private readonly _selectionManagerService: SelectionManagerService,
+ @Inject(SheetsSelectionsService) private readonly _selectionManagerService: SheetsSelectionsService,
@Inject(ScrollManagerService) private readonly _scrollManagerService: ScrollManagerService,
@IUniverInstanceService protected readonly _univerInstanceService: IUniverInstanceService
) {
@@ -104,7 +104,7 @@ export class MobileSheetsScrollRenderController extends Disposable implements IR
private _scrollToSelectionForExpand(param: IExpandSelectionCommandParams) {
setTimeout(() => {
- const selection = this._selectionManagerService.getLast();
+ const selection = this._selectionManagerService.getCurrentLastSelection();
if (selection == null) {
return;
}
@@ -343,8 +343,8 @@ export class MobileSheetsScrollRenderController extends Disposable implements IR
}
const _currentScroll: Readonly<Nullable<IScrollManagerParam>> = scrollManagerService.getCurrentScrollInfo();
- const { unitId } = this._context;
- const sheetId = workbook.getActiveSheet()!.getSheetId();
+ // const { unitId } = this._context;
+ // const sheetId = workbook.getActiveSheet()!.getSheetId();
// const {
// sheetViewStartRow = 0,
// sheetViewStartColumn = 0,
@@ -387,7 +387,6 @@ export class MobileSheetsScrollRenderController extends Disposable implements IR
// cancelInertiaAnimation();
if (!_pointerScrolling) return;
if (!viewportMain) return;
- // console.log('spreadsheet into moving...........');
const e = evt as IPointerEvent | IMouseEvent;
const deltaX = -(e.offsetX - lastPointerPos.x);
const deltaY = -(e.offsetY - lastPointerPos.y);
@@ -516,7 +515,7 @@ export class MobileSheetsScrollRenderController extends Disposable implements IR
}
private _scrollToSelection(targetIsActualRowAndColumn = true) {
- const selection = this._selectionManagerService.getLast();
+ const selection = this._selectionManagerService.getCurrentLastSelection();
if (selection == null) {
return;
}
diff --git a/packages/sheets-ui/src/controllers/render-controllers/mobile/mobile-selection.render-controller.ts b/packages/sheets-ui/src/controllers/render-controllers/mobile/mobile-selection.render-controller.ts
deleted file mode 100644
index 6447f98e46..0000000000
--- a/packages/sheets-ui/src/controllers/render-controllers/mobile/mobile-selection.render-controller.ts
+++ /dev/null
@@ -1,591 +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 { ICommandInfo, Workbook } from '@univerjs/core';
-import {
- Disposable,
- ICommandService,
- RANGE_TYPE,
- ThemeService,
- toDisposable,
-} from '@univerjs/core';
-import type { IMouseEvent, IPointerEvent, IRenderContext, IRenderModule, SpreadsheetSkeleton } from '@univerjs/engine-render';
-import { ScrollTimerType, SHEET_VIEWPORT_KEY, Vector2 } from '@univerjs/engine-render';
-import type { ISelectionWithCoordAndStyle, ISelectionWithStyle } from '@univerjs/sheets';
-import {
- convertSelectionDataToRange,
- getNormalSelectionStyle,
- getPrimaryForRange,
- NORMAL_SELECTION_PLUGIN_NAME,
- ScrollToCellOperation,
- SelectionManagerService,
- SelectionMoveType,
- SetSelectionsOperation,
- SetWorksheetActivateCommand,
- transformCellDataToSelectionData,
-} from '@univerjs/sheets';
-import { Inject } from '@wendellhu/redi';
-
-import { deserializeRangeWithSheet, IDefinedNamesService, isReferenceStrings, operatorToken } from '@univerjs/engine-formula';
-import type { ISetZoomRatioOperationParams } from '../../../commands/operations/set-zoom-ratio.operation';
-import { SetZoomRatioOperation } from '../../../commands/operations/set-zoom-ratio.operation';
-import { ISelectionRenderService } from '../../../services/selection/selection-render.service';
-import { SheetSkeletonManagerService } from '../../../services/sheet-skeleton-manager.service';
-import type { ISheetObjectParam } from '../../utils/component-tools';
-import { getSheetObject } from '../../utils/component-tools';
-import { ScrollManagerService } from '../../../services/scroll-manager.service';
-import type { MobileSelectionControl } from '../../../services/selection/mobile-selection-shape';
-
-export class MobileSelectionRenderController extends Disposable implements IRenderModule {
- constructor(
- private readonly _context: IRenderContext<Workbook>,
- @Inject(SheetSkeletonManagerService) private readonly _sheetSkeletonManagerService: SheetSkeletonManagerService,
- @ICommandService private readonly _commandService: ICommandService,
- // TODO@wzhudev: it is really necessary to split the selection services?
- @ISelectionRenderService private readonly _selectionRenderService: ISelectionRenderService,
- @Inject(SelectionManagerService) private readonly _selectionManagerService: SelectionManagerService,
- @Inject(ThemeService) private readonly _themeService: ThemeService,
- @IDefinedNamesService private readonly _definedNamesService: IDefinedNamesService,
- @Inject(ScrollManagerService) private _scrollManagerService: ScrollManagerService
- ) {
- super();
- this._init();
- }
-
- override dispose(): void {
- super.dispose();
-
- this._selectionRenderService.changeRuntime(null, null);
- this._selectionRenderService.reset();
- this._selectionManagerService.reset();
- }
-
- private _init() {
- const workbook = this._context.unit;
- const worksheet = workbook.getActiveSheet();
- const sheetObject = this._getSheetObject();
-
- this._initSpreadsheetEvent(sheetObject);
- this._initRowHeaderEvent(sheetObject);
- this._initColumnHeaderEvent(sheetObject);
- this._initLeftTop(sheetObject);
- this._initSelectionChangeListener();
- this._initThemeChangeListener();
- this._initSkeletonChangeListener();
- this._initCommandListener();
- this._initUserActionSyncListener();
- this._initDefinedNameListener();
- this._updateControlPointWhenScrolling();
- const unitId = workbook.getUnitId();
- if (!worksheet) return;
- const sheetId = worksheet.getSheetId();
- this._selectionManagerService.setCurrentSelection({
- pluginName: NORMAL_SELECTION_PLUGIN_NAME,
- unitId,
- sheetId,
- });
- }
-
- private _initDefinedNameListener() {
- this.disposeWithMe(
- this._definedNamesService.focusRange$.subscribe(async (item) => {
- if (item == null) {
- return;
- }
-
- const { unitId } = item;
- let { formulaOrRefString } = item;
-
- const workbook = this._context.unit;
-
- if (unitId !== workbook.getUnitId()) {
- return;
- }
-
- if (formulaOrRefString.substring(0, 1) === operatorToken.EQUALS) {
- formulaOrRefString = formulaOrRefString.substring(1);
- }
-
- const result = isReferenceStrings(formulaOrRefString);
-
- if (!result) {
- return;
- }
-
- const selections = await this._getSelections(workbook, unitId, formulaOrRefString);
-
- this._selectionManagerService.replace(selections);
-
- this._commandService.executeCommand(ScrollToCellOperation.id, selections[0].range);
- })
- );
- }
-
- private _updateControlPointWhenScrolling() {
- //this._scrollManagerService.scrollInfo$.subscribe((param) => {
- const { scene } = this._context;
- const viewportMain = scene.getViewport(SHEET_VIEWPORT_KEY.VIEW_MAIN);
- if (!viewportMain) return;
- // const sub = this._scrollManagerService.scrollInfo$.subscribe((param) => {
- // const sub = viewportMain.onScrollAfter$.subscribeEvent((param) => {
- const sub = this._scrollManagerService.validViewportScrollInfo$.subscribe((param) => {
- if (param == null) {
- return;
- }
- const { viewportScrollX, viewportScrollY } = param!;
- const activeControl = this._selectionRenderService.getActiveSelectionControl() as unknown as MobileSelectionControl;
- if (activeControl == null) {
- return;
- }
- const skeleton = this._sheetSkeletonManagerService.getCurrent()?.skeleton;
- const sheetContentHeight = skeleton?.rowTotalHeight;
- const sheetContentWidth = skeleton?.columnTotalWidth;
- const rangeType = activeControl.rangeType;
- if (rangeType === RANGE_TYPE.COLUMN) {
- activeControl.transformControlPoint(0, viewportScrollY, sheetContentWidth, sheetContentHeight);
- } else if (rangeType === RANGE_TYPE.ROW) {
- activeControl.transformControlPoint(viewportScrollX, 0, sheetContentWidth, sheetContentHeight);
- }
- });
- this.disposeWithMe(toDisposable(sub));
- }
-
- private async _getSelections(workbook: Workbook, unitId: string, formulaOrRefString: string) {
- const valueArray = formulaOrRefString.split(',');
-
- let worksheet = workbook.getActiveSheet();
- if (!worksheet) {
- return [];
- }
-
- const selections = [];
-
- for (let i = 0; i < valueArray.length; i++) {
- const refString = valueArray[i].trim();
-
- const unitRange = deserializeRangeWithSheet(refString.trim());
-
- if (i === 0) {
- const worksheetCache = workbook.getSheetBySheetName(unitRange.sheetName);
- if (worksheetCache && worksheet.getSheetId() !== worksheetCache.getSheetId()) {
- worksheet = worksheetCache;
- await this._commandService.executeCommand(SetWorksheetActivateCommand.id, {
- subUnitId: worksheet.getSheetId(),
- unitId,
- });
- }
- }
-
- if (worksheet.getName() !== unitRange.sheetName) {
- continue;
- }
-
- let primary = null;
- if (i === valueArray.length - 1) {
- const range = unitRange.range;
- const { startRow, startColumn, endRow, endColumn } = range;
- primary = getPrimaryForRange({
- startRow,
- startColumn,
- endRow,
- endColumn,
-
- }, worksheet);
- }
-
- selections.push({
- range: unitRange.range,
- style: getNormalSelectionStyle(this._themeService),
- primary,
- });
- }
-
- return selections;
- }
-
- private _getActiveViewport(evt: IPointerEvent | IMouseEvent) {
- const sheetObject = this._getSheetObject();
-
- return sheetObject?.scene.getActiveViewportByCoord(Vector2.FromArray([evt.offsetX, evt.offsetY]));
- }
-
- private _initSpreadsheetEvent(sheetObject: ISheetObjectParam) {
- const { spreadsheet } = sheetObject;
- let longPressTimer: ReturnType<typeof setTimeout>;
- const longPressDuration = 500; // Longpress duration in milliseconds
- const pointerDownPos = { x: 0, y: 0 };
-
- const clearLongPressTimer = () => {
- // Clear the timer if pointer is moved or released
- clearTimeout(longPressTimer);
- };
-
- const createNewSelection = (evt: IPointerEvent | IMouseEvent, showContextMenu: boolean) => {
- this._selectionRenderService.enableDetectMergedCell();
- this._selectionRenderService.eventTrigger(
- evt,
- spreadsheet.zIndex + 1,
- RANGE_TYPE.NORMAL,
- this._getActiveViewport(evt)
- );
- if (showContextMenu) {
- this._selectionManagerService.refreshSelection();
- }
- };
- spreadsheet?.onPointerMove$.subscribeEvent((evt: IPointerEvent | IMouseEvent, _state) => {
- const edge = 10;
- if (Math.abs(evt.offsetX - pointerDownPos.x) > edge ||
- Math.abs(evt.offsetY - pointerDownPos.y) > edge) {
- clearLongPressTimer();
- }
- });
- const spreadsheetPointerDownSub = spreadsheet?.onPointerDown$.subscribeEvent((evt: IPointerEvent | IMouseEvent, state) => {
- this._selectionRenderService.enableDetectMergedCell();
- pointerDownPos.x = evt.offsetX;
- pointerDownPos.y = evt.offsetY;
- longPressTimer = setTimeout(() => {
- createNewSelection(evt, true);
- }, longPressDuration);
-
- if (evt.button !== 2) {
- state.stopPropagation();
- }
- });
- const spreadsheetPointerUpSub = spreadsheet?.onPointerUp$.subscribeEvent((evt: IPointerEvent | IMouseEvent, state) => {
- clearTimeout(longPressTimer);
- const edge = 10;
- if (Math.abs(evt.offsetX - pointerDownPos.x) > edge ||
- Math.abs(evt.offsetY - pointerDownPos.y) > edge) {
- return;
- }
- createNewSelection(evt, false);
- state.stopPropagation();
- });
-
- this.disposeWithMe(toDisposable(spreadsheetPointerDownSub));
- this.disposeWithMe(toDisposable(spreadsheetPointerUpSub));
- }
-
- private _initThemeChangeListener() {
- this.disposeWithMe(
- toDisposable(
- this._themeService.currentTheme$.subscribe(() => {
- this._selectionRenderService.resetStyle();
- const param = this._selectionManagerService.getSelections();
- const current = this._selectionManagerService.getCurrent();
-
- if (param == null || current?.pluginName !== NORMAL_SELECTION_PLUGIN_NAME) {
- return;
- }
-
- this._refreshSelection(param);
- })
- )
- );
- }
-
- private _refreshSelection(params: readonly ISelectionWithStyle[]) {
- const selections = params.map((selectionWithStyle) => {
- const selectionData = this._selectionRenderService.attachSelectionWithCoord(selectionWithStyle);
- selectionData.style = getNormalSelectionStyle(this._themeService);
- return selectionData;
- });
-
- this._selectionRenderService.updateControlForCurrentByRangeData(selections);
- }
-
- private _initRowHeaderEvent(sheetObject: ISheetObjectParam) {
- const { spreadsheetRowHeader, spreadsheet } = sheetObject;
-
- this.disposeWithMe(
- spreadsheetRowHeader?.onPointerUp$.subscribeEvent((evt: IPointerEvent | IMouseEvent, state) => {
- this._selectionRenderService.disableDetectMergedCell();
- this._selectionRenderService.eventTrigger(
- evt,
- (spreadsheet?.zIndex || 1) + 1,
- RANGE_TYPE.ROW,
- this._getActiveViewport(evt),
- ScrollTimerType.Y
- );
- state.stopPropagation();
- // use this to show contextmenu
- this._selectionManagerService.refreshSelection();
- })
- );
-
- // spreadsheetRowHeader?.onPointerMoveObserver.add((evt: IPointerEvent | IMouseEvent, state) => {});
- }
-
- private _initColumnHeaderEvent(sheetObject: ISheetObjectParam) {
- const { spreadsheetColumnHeader, spreadsheet } = sheetObject;
-
- this.disposeWithMe(
- spreadsheetColumnHeader?.onPointerUp$.subscribeEvent((evt: IPointerEvent | IMouseEvent, state) => {
- this._selectionRenderService.disableDetectMergedCell();
-
- this._selectionRenderService.eventTrigger(
- evt,
- (spreadsheet?.zIndex || 1) + 1,
- RANGE_TYPE.COLUMN,
- this._getActiveViewport(evt),
- ScrollTimerType.X
- );
- state.stopPropagation();
- // use this to show contextmenu
- this._selectionManagerService.refreshSelection();
- })
- );
- }
-
- private _initLeftTop(sheetObject: ISheetObjectParam) {
- const { spreadsheetLeftTopPlaceholder } = sheetObject;
- this.disposeWithMe(
- spreadsheetLeftTopPlaceholder?.onPointerDown$.subscribeEvent((evt: IPointerEvent | IMouseEvent, state) => {
- const skeleton = this._sheetSkeletonManagerService.getCurrent()?.skeleton;
- if (skeleton == null) {
- return;
- }
-
- this._selectionRenderService.reset();
-
- const selectionWithStyle = this._getAllRange(skeleton);
-
- const selectionData = this._selectionRenderService.attachSelectionWithCoord(selectionWithStyle);
- this._selectionRenderService.addSelectionControlBySelectionData(selectionData);
-
- this._selectionRenderService.refreshSelectionMoveStart();
-
- // this._selectionManagerService.replace([selectionWithStyle]);
-
- if (evt.button !== 2) {
- state.stopPropagation();
- }
- })
- );
- }
-
- private _initSelectionChangeListener() {
- this.disposeWithMe(
- toDisposable(
- // selectionMoveEnd$ would also be invoked when changing sheet(_currentSkeleton$.next)
- this._selectionManagerService.selectionMoveEnd$.subscribe((params) => {
- this._selectionRenderService.reset();
- if (params == null) {
- return;
- }
-
- for (const selectionWithStyle of params) {
- if (selectionWithStyle == null) {
- continue;
- }
- const selectionData =
- this._selectionRenderService.attachSelectionWithCoord(selectionWithStyle);
- this._selectionRenderService.addSelectionControlBySelectionData(selectionData);
- }
-
- this._syncDefinedNameRange(params);
- })
- )
- );
-
- this.disposeWithMe(
- toDisposable(
- this._selectionManagerService.selectionMoving$.subscribe((params) => {
- if (params == null) {
- return;
- }
-
- this._syncDefinedNameRange(params);
- })
- )
- );
-
- this.disposeWithMe(
- toDisposable(
- this._selectionManagerService.selectionMoveStart$.subscribe((params) => {
- if (params == null) {
- return;
- }
-
- this._syncDefinedNameRange(params);
- })
- )
- );
- }
-
- private _syncDefinedNameRange(params: ISelectionWithStyle[]) {
- if (params.length === 0) {
- return;
- }
- const lastSelection = params[params.length - 1];
-
- const workbook = this._context.unit;
- const worksheet = workbook.getActiveSheet();
- if (!worksheet) {
- return;
- }
- this._definedNamesService.setCurrentRange({
- range: lastSelection.range,
- unitId: workbook.getUnitId(),
- sheetId: worksheet.getSheetId(),
- });
- }
-
- private _initUserActionSyncListener() {
- this.disposeWithMe(this._selectionRenderService.selectionMoveStart$.subscribe((params) => {
- this._move(params, SelectionMoveType.MOVE_START);
- }));
-
- this.disposeWithMe(this._selectionRenderService.selectionMoving$.subscribe((params) => {
- this._move(params, SelectionMoveType.MOVING);
- }));
-
- this.disposeWithMe(this._selectionRenderService.selectionMoveEnd$.subscribe((params) => {
- this._move(params, SelectionMoveType.MOVE_END);
- }));
- }
-
- private _move(selectionDataWithStyleList: ISelectionWithCoordAndStyle[], type: SelectionMoveType) {
- const workbook = this._context.unit;
- if (!workbook) return;
-
- const unitId = workbook.getUnitId();
- const sheetId = workbook.getActiveSheet()?.getSheetId();
- const current = this._selectionManagerService.getCurrent();
-
- if (selectionDataWithStyleList == null || selectionDataWithStyleList.length === 0) {
- return;
- }
-
- this._commandService.executeCommand(SetSelectionsOperation.id, {
- unitId,
- subUnitId: sheetId,
- type,
- pluginName: current?.pluginName || NORMAL_SELECTION_PLUGIN_NAME,
- selections: selectionDataWithStyleList.map((selectionDataWithStyle) =>
- convertSelectionDataToRange(selectionDataWithStyle)
- ),
- });
- }
-
- private _getSheetObject() {
- return getSheetObject(this._context.unit, this._context)!;
- }
-
- private _initCommandListener() {
- const updateCommandList = [SetZoomRatioOperation.id];
-
- this.disposeWithMe(this._commandService.onCommandExecuted((command: ICommandInfo) => {
- if (updateCommandList.includes(command.id)) {
- const workbook = this._context.unit;
- const worksheet = workbook.getActiveSheet();
-
- const params = command.params as ISetZoomRatioOperationParams;
- const { unitId, subUnitId } = params;
- if (!(unitId === workbook.getUnitId() && subUnitId === worksheet?.getSheetId())) {
- return;
- }
-
- this._selectionManagerService.refreshSelection();
- }
- }));
- }
-
- private _initSkeletonChangeListener() {
- this.disposeWithMe(this._sheetSkeletonManagerService.currentSkeleton$.subscribe((param) => {
- if (param == null) {
- this._selectionRenderService.changeRuntime(null, null);
- return;
- }
-
- const unitId = this._context.unitId;
- const { sheetId, skeleton } = param;
- const { scene } = this._context;
-
- const viewportMain = scene.getViewport(SHEET_VIEWPORT_KEY.VIEW_MAIN);
-
- this._selectionRenderService.changeRuntime(skeleton, scene, viewportMain);
-
- /**
- * Features like formulas can select ranges across sub-tables.
- * If the current pluginName is not in a normal state,
- * the current selection will not be refreshed.
- */
- const current = this._selectionManagerService.getCurrent();
- const pluginName = current?.pluginName || NORMAL_SELECTION_PLUGIN_NAME;
-
- if (current?.unitId === unitId && current.sheetId === sheetId) {
- const currentSelections = this._selectionManagerService.getSelections();
- if (currentSelections != null) {
- this._refreshSelection(currentSelections);
- }
- } else {
- this._selectionManagerService.setCurrentSelection({
- pluginName,
- unitId,
- sheetId,
- });
- }
-
- if (pluginName === NORMAL_SELECTION_PLUGIN_NAME) {
- // If there is no initial selection, add one by default in the top left corner.
- const last = this._selectionManagerService.getLast();
- if (last == null) {
- this._selectionManagerService.add([this._getZeroRange(skeleton)]);
- }
- }
- }));
- }
-
- private _getAllRange(skeleton: SpreadsheetSkeleton): ISelectionWithStyle {
- return {
- range: {
- startRow: 0,
- startColumn: 0,
- endRow: skeleton.getRowCount() - 1,
- endColumn: skeleton.getColumnCount() - 1,
- rangeType: RANGE_TYPE.ALL,
- },
- primary: this._getZeroRange(skeleton).primary,
- style: null,
- };
- }
-
- private _getZeroRange(skeleton: SpreadsheetSkeleton) {
- const mergeData = skeleton.mergeData;
- return (
- transformCellDataToSelectionData(0, 0, mergeData) || {
- range: {
- startRow: 0,
- startColumn: 0,
- endRow: 0,
- endColumn: 0,
- },
- primary: {
- actualRow: 0,
- actualColumn: 0,
- startRow: 0,
- startColumn: 0,
- endRow: 0,
- endColumn: 0,
- isMerged: false,
- isMergedMainCell: false,
- },
- style: null,
- }
- );
- }
-}
diff --git a/packages/sheets-ui/src/controllers/render-controllers/scroll.render-controller.ts b/packages/sheets-ui/src/controllers/render-controllers/scroll.render-controller.ts
index a2c8dda7c3..e70373e1ce 100644
--- a/packages/sheets-ui/src/controllers/render-controllers/scroll.render-controller.ts
+++ b/packages/sheets-ui/src/controllers/render-controllers/scroll.render-controller.ts
@@ -19,14 +19,14 @@ import {
Direction,
Disposable,
ICommandService,
- IUniverInstanceService,
RANGE_TYPE,
toDisposable,
} from '@univerjs/core';
import type { IRenderContext, IRenderModule, IScrollObserverParam } from '@univerjs/engine-render';
import { IRenderManagerService, SHEET_VIEWPORT_KEY } from '@univerjs/engine-render';
-import { ScrollToCellOperation, SelectionManagerService } from '@univerjs/sheets';
-import { Inject } from '@wendellhu/redi';
+import type { SheetsSelectionsService } from '@univerjs/sheets';
+import { getSelectionsService, ScrollToCellOperation } from '@univerjs/sheets';
+import { Inject, Injector } from '@wendellhu/redi';
import { ScrollCommand } from '../../commands/commands/set-scroll.command';
import type { IExpandSelectionCommandParams } from '../../commands/commands/set-selection.command';
@@ -45,12 +45,11 @@ const SHEET_NAVIGATION_COMMANDS = [MoveSelectionCommand.id, MoveSelectionEnterAn
export class SheetsScrollRenderController extends Disposable implements IRenderModule {
constructor(
private readonly _context: IRenderContext<Workbook>,
+ @Inject(Injector) private readonly _injector: Injector,
@Inject(SheetSkeletonManagerService) private readonly _sheetSkeletonManagerService: SheetSkeletonManagerService,
@ICommandService private readonly _commandService: ICommandService,
@IRenderManagerService private readonly _renderManagerService: IRenderManagerService,
- @Inject(SelectionManagerService) private readonly _selectionManagerService: SelectionManagerService,
- @Inject(ScrollManagerService) private readonly _scrollManagerService: ScrollManagerService,
- @IUniverInstanceService protected readonly _univerInstanceService: IUniverInstanceService
+ @Inject(ScrollManagerService) private readonly _scrollManagerService: ScrollManagerService
) {
super();
@@ -102,7 +101,7 @@ export class SheetsScrollRenderController extends Disposable implements IRenderM
private _scrollToSelectionForExpand(param: IExpandSelectionCommandParams) {
setTimeout(() => {
- const selection = this._selectionManagerService.getLast();
+ const selection = this._getSelectionsService().getCurrentLastSelection();
if (selection == null) {
return;
}
@@ -368,7 +367,7 @@ export class SheetsScrollRenderController extends Disposable implements IRenderM
}
private _scrollToSelection(targetIsActualRowAndColumn = true) {
- const selection = this._selectionManagerService.getLast();
+ const selection = this._getSelectionsService().getCurrentLastSelection();
if (selection == null) {
return;
}
@@ -380,6 +379,10 @@ export class SheetsScrollRenderController extends Disposable implements IRenderM
this._scrollToCell(selectionStartRow, selectionStartColumn);
}
+ private _getSelectionsService(): SheetsSelectionsService {
+ return getSelectionsService(this._injector);
+ }
+
private _getViewportBounding() {
const scene = this._getSheetObject()?.scene;
if (scene == null) {
diff --git a/packages/sheets-ui/src/controllers/render-controllers/selection.render-controller.ts b/packages/sheets-ui/src/controllers/render-controllers/selection.render-controller.ts
deleted file mode 100644
index 7b56494671..0000000000
--- a/packages/sheets-ui/src/controllers/render-controllers/selection.render-controller.ts
+++ /dev/null
@@ -1,536 +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 { ICommandInfo, Workbook } from '@univerjs/core';
-import {
- Disposable,
- ICommandService,
- RANGE_TYPE,
- ThemeService,
- toDisposable,
-} from '@univerjs/core';
-import type { IMouseEvent, IPointerEvent, IRenderContext, IRenderModule, SpreadsheetSkeleton } from '@univerjs/engine-render';
-import { ScrollTimerType, SHEET_VIEWPORT_KEY, Vector2 } from '@univerjs/engine-render';
-import type { ISelectionWithCoordAndStyle, ISelectionWithStyle } from '@univerjs/sheets';
-import {
- convertSelectionDataToRange,
- getNormalSelectionStyle,
- getPrimaryForRange,
- NORMAL_SELECTION_PLUGIN_NAME,
- ScrollToCellOperation,
- SelectionManagerService,
- SelectionMoveType,
- SetSelectionsOperation,
- SetWorksheetActivateCommand,
- transformCellDataToSelectionData,
-} from '@univerjs/sheets';
-import { Inject } from '@wendellhu/redi';
-
-import { deserializeRangeWithSheet, IDefinedNamesService, isReferenceStrings, operatorToken } from '@univerjs/engine-formula';
-import type { ISetZoomRatioOperationParams } from '../../commands/operations/set-zoom-ratio.operation';
-import { SetZoomRatioOperation } from '../../commands/operations/set-zoom-ratio.operation';
-import { ISelectionRenderService } from '../../services/selection/selection-render.service';
-import { SheetSkeletonManagerService } from '../../services/sheet-skeleton-manager.service';
-import type { ISheetObjectParam } from '../utils/component-tools';
-import { getSheetObject } from '../utils/component-tools';
-
-export class SelectionRenderController extends Disposable implements IRenderModule {
- constructor(
- private readonly _context: IRenderContext<Workbook>,
- @Inject(SheetSkeletonManagerService) private readonly _sheetSkeletonManagerService: SheetSkeletonManagerService,
- @ICommandService private readonly _commandService: ICommandService,
- // TODO@wzhudev: it is really necessary to split the selection services?
- @ISelectionRenderService private readonly _selectionRenderService: ISelectionRenderService,
- @Inject(SelectionManagerService) private readonly _selectionManagerService: SelectionManagerService,
- @Inject(ThemeService) private readonly _themeService: ThemeService,
- @IDefinedNamesService private readonly _definedNamesService: IDefinedNamesService
- ) {
- super();
-
- this._init();
- }
-
- override dispose(): void {
- super.dispose();
-
- this._selectionRenderService.changeRuntime(null, null);
- this._selectionRenderService.reset();
- this._selectionManagerService.reset();
- }
-
- private _init() {
- const workbook = this._context.unit;
- const worksheet = workbook.getActiveSheet();
- if (!worksheet) {
- throw new Error('No active sheet');
- }
- const sheetObject = this._getSheetObject();
-
- this._initSpreadsheetEvent(sheetObject);
- this._initRowHeader(sheetObject);
- this._initColumnHeader(sheetObject);
- this._initLeftTop(sheetObject);
- this._initSelectionChangeListener();
- this._initThemeChangeListener();
- this._initSkeletonChangeListener();
- this._initCommandListener();
- this._initUserActionSyncListener();
- this._initDefinedNameListener();
-
- const unitId = workbook.getUnitId();
- const sheetId = worksheet.getSheetId();
- this._selectionManagerService.setCurrentSelection({
- pluginName: NORMAL_SELECTION_PLUGIN_NAME,
- unitId,
- sheetId,
- });
- }
-
- private _initDefinedNameListener() {
- this.disposeWithMe(
- this._definedNamesService.focusRange$.subscribe(async (item) => {
- if (item == null) {
- return;
- }
-
- const { unitId } = item;
- let { formulaOrRefString } = item;
-
- const workbook = this._context.unit;
-
- if (unitId !== workbook.getUnitId()) {
- return;
- }
-
- if (formulaOrRefString.substring(0, 1) === operatorToken.EQUALS) {
- formulaOrRefString = formulaOrRefString.substring(1);
- }
-
- const result = isReferenceStrings(formulaOrRefString);
-
- if (!result) {
- return;
- }
-
- const selections = await this._getSelections(workbook, unitId, formulaOrRefString);
-
- this._selectionManagerService.replace(selections);
-
- this._commandService.executeCommand(ScrollToCellOperation.id, selections[0].range);
- })
- );
- }
-
- private async _getSelections(workbook: Workbook, unitId: string, formulaOrRefString: string) {
- const valueArray = formulaOrRefString.split(',');
-
- let worksheet = workbook.getActiveSheet();
-
- if (!worksheet) {
- return [];
- }
-
- const selections = [];
-
- for (let i = 0; i < valueArray.length; i++) {
- const refString = valueArray[i].trim();
-
- const unitRange = deserializeRangeWithSheet(refString.trim());
-
- if (i === 0) {
- const worksheetCache = workbook.getSheetBySheetName(unitRange.sheetName);
- if (worksheetCache && worksheet.getSheetId() !== worksheetCache.getSheetId()) {
- worksheet = worksheetCache;
- await this._commandService.executeCommand(SetWorksheetActivateCommand.id, {
- subUnitId: worksheet.getSheetId(),
- unitId,
- });
- }
- }
-
- if (worksheet.getName() !== unitRange.sheetName) {
- continue;
- }
-
- let primary = null;
- if (i === valueArray.length - 1) {
- const range = unitRange.range;
- const { startRow, startColumn, endRow, endColumn } = range;
- primary = getPrimaryForRange({
- startRow,
- startColumn,
- endRow,
- endColumn,
-
- }, worksheet);
- }
-
- selections.push({
- range: unitRange.range,
- style: getNormalSelectionStyle(this._themeService),
- primary,
- });
- }
-
- return selections;
- }
-
- private _getActiveViewport(evt: IPointerEvent | IMouseEvent) {
- const sheetObject = this._getSheetObject();
-
- return sheetObject?.scene.getActiveViewportByCoord(Vector2.FromArray([evt.offsetX, evt.offsetY]));
- }
-
- private _initSpreadsheetEvent(sheetObject: ISheetObjectParam) {
- const { spreadsheet } = sheetObject;
-
- this.disposeWithMe(
- toDisposable(
- spreadsheet?.onPointerDown$.subscribeEvent((evt: IPointerEvent | IMouseEvent, state) => {
- this._selectionRenderService.enableDetectMergedCell();
-
- this._selectionRenderService.eventTrigger(
- evt,
- spreadsheet.zIndex + 1,
- RANGE_TYPE.NORMAL,
- this._getActiveViewport(evt)
- );
-
- if (evt.button !== 2) {
- state.stopPropagation();
- }
- })
- )
- );
- }
-
- private _initThemeChangeListener() {
- this.disposeWithMe(
- toDisposable(
- this._themeService.currentTheme$.subscribe(() => {
- this._selectionRenderService.resetStyle();
- const param = this._selectionManagerService.getSelections();
- const current = this._selectionManagerService.getCurrent();
-
- if (param == null || current?.pluginName !== NORMAL_SELECTION_PLUGIN_NAME) {
- return;
- }
-
- this._refreshSelection(param);
- })
- )
- );
- }
-
- private _refreshSelection(params: readonly ISelectionWithStyle[]) {
- const selections = params.map((selectionWithStyle) => {
- const selectionData = this._selectionRenderService.attachSelectionWithCoord(selectionWithStyle);
- selectionData.style = getNormalSelectionStyle(this._themeService);
- return selectionData;
- });
-
- this._selectionRenderService.updateControlForCurrentByRangeData(selections);
- }
-
- private _initRowHeader(sheetObject: ISheetObjectParam) {
- const { spreadsheetRowHeader, spreadsheet } = sheetObject;
-
- this.disposeWithMe(
- spreadsheetRowHeader?.onPointerDown$.subscribeEvent((evt: IPointerEvent | IMouseEvent, state) => {
- this._selectionRenderService.disableDetectMergedCell();
- this._selectionRenderService.eventTrigger(
- evt,
- (spreadsheet?.zIndex || 1) + 1,
- RANGE_TYPE.ROW,
- this._getActiveViewport(evt),
- ScrollTimerType.Y
- );
-
- if (evt.button !== 2) {
- state.stopPropagation();
- }
- })
- );
-
- // spreadsheetRowHeader?.onPointerMoveObserver.add((evt: IPointerEvent | IMouseEvent, state) => {});
- }
-
- private _initColumnHeader(sheetObject: ISheetObjectParam) {
- const { spreadsheetColumnHeader, spreadsheet } = sheetObject;
-
- this.disposeWithMe(
- spreadsheetColumnHeader?.onPointerDown$.subscribeEvent((evt: IPointerEvent | IMouseEvent, state) => {
- this._selectionRenderService.disableDetectMergedCell();
-
- this._selectionRenderService.eventTrigger(
- evt,
- (spreadsheet?.zIndex || 1) + 1,
- RANGE_TYPE.COLUMN,
- this._getActiveViewport(evt),
- ScrollTimerType.X
- );
-
- if (evt.button !== 2) {
- state.stopPropagation();
- }
- })
- );
- }
-
- private _initLeftTop(sheetObject: ISheetObjectParam) {
- const { spreadsheetLeftTopPlaceholder } = sheetObject;
- this.disposeWithMe(
- spreadsheetLeftTopPlaceholder?.onPointerDown$.subscribeEvent((evt: IPointerEvent | IMouseEvent, state) => {
- const skeleton = this._sheetSkeletonManagerService.getCurrent()?.skeleton;
- if (skeleton == null) {
- return;
- }
-
- this._selectionRenderService.reset();
-
- const selectionWithStyle = this._getAllRange(skeleton);
-
- const selectionData = this._selectionRenderService.attachSelectionWithCoord(selectionWithStyle);
- this._selectionRenderService.addSelectionControlBySelectionData(selectionData);
-
- this._selectionRenderService.refreshSelectionMoveStart();
-
- // this._selectionManagerService.replace([selectionWithStyle]);
-
- if (evt.button !== 2) {
- state.stopPropagation();
- }
- })
- );
- }
-
- private _initSelectionChangeListener() {
- this.disposeWithMe(
- toDisposable(
- this._selectionManagerService.selectionMoveEndBefore$.subscribe((params) => {
- // clear selection controls
- this._selectionRenderService.reset();
- if (params == null) {
- return;
- }
-
- for (const selectionWithStyle of params) {
- if (selectionWithStyle == null) {
- continue;
- }
- const selectionData =
- this._selectionRenderService.attachSelectionWithCoord(selectionWithStyle);
-
- // then add a new selection control.
- this._selectionRenderService.addSelectionControlBySelectionData(selectionData);
- }
-
- this._syncDefinedNameRange(params);
- })
- )
- );
-
- this.disposeWithMe(
- toDisposable(
- this._selectionManagerService.selectionMoving$.subscribe((params) => {
- if (params == null) {
- return;
- }
-
- this._syncDefinedNameRange(params);
- })
- )
- );
-
- this.disposeWithMe(
- toDisposable(
- this._selectionManagerService.selectionMoveStart$.subscribe((params) => {
- if (params == null) {
- return;
- }
-
- this._syncDefinedNameRange(params);
- })
- )
- );
- }
-
- private _syncDefinedNameRange(params: ISelectionWithStyle[]) {
- if (params.length === 0) {
- return;
- }
- const lastSelection = params[params.length - 1];
-
- const workbook = this._context.unit;
- const worksheet = workbook.getActiveSheet();
- if (!worksheet) {
- return;
- }
-
- this._definedNamesService.setCurrentRange({
- range: lastSelection.range,
- unitId: workbook.getUnitId(),
- sheetId: worksheet.getSheetId(),
- });
- }
-
- private _initUserActionSyncListener() {
- this.disposeWithMe(this._selectionRenderService.selectionMoveStart$.subscribe((params) => {
- this._move(params, SelectionMoveType.MOVE_START);
- }));
-
- this.disposeWithMe(this._selectionRenderService.selectionMoving$.subscribe((params) => {
- this._move(params, SelectionMoveType.MOVING);
- }));
-
- this.disposeWithMe(this._selectionRenderService.selectionMoveEnd$.subscribe((params) => {
- this._move(params, SelectionMoveType.MOVE_END);
- }));
- }
-
- private _move(selectionDataWithStyleList: ISelectionWithCoordAndStyle[], type: SelectionMoveType) {
- const workbook = this._context.unit;
- if (!workbook) return;
-
- const unitId = workbook.getUnitId();
- const sheetId = workbook.getActiveSheet()?.getSheetId();
- if (!sheetId) return;
-
- const current = this._selectionManagerService.getCurrent();
-
- if (selectionDataWithStyleList == null || selectionDataWithStyleList.length === 0) {
- return;
- }
-
- this._commandService.executeCommand(SetSelectionsOperation.id, {
- unitId,
- subUnitId: sheetId,
- type,
- pluginName: current?.pluginName || NORMAL_SELECTION_PLUGIN_NAME,
- selections: selectionDataWithStyleList.map((selectionDataWithStyle) =>
- convertSelectionDataToRange(selectionDataWithStyle)
- ),
- });
- }
-
- private _getSheetObject() {
- return getSheetObject(this._context.unit, this._context)!;
- }
-
- private _initCommandListener() {
- const updateCommandList = [SetZoomRatioOperation.id];
-
- this.disposeWithMe(this._commandService.onCommandExecuted((command: ICommandInfo) => {
- if (updateCommandList.includes(command.id)) {
- const workbook = this._context.unit;
- const worksheet = workbook.getActiveSheet();
-
- const params = command.params as ISetZoomRatioOperationParams;
- const { unitId, subUnitId } = params;
- if (!(unitId === workbook.getUnitId() && subUnitId === worksheet?.getSheetId())) {
- return;
- }
-
- this._selectionManagerService.refreshSelection();
- }
- }));
- }
-
- private _initSkeletonChangeListener() {
- this.disposeWithMe(this._sheetSkeletonManagerService.currentSkeleton$.subscribe((param) => {
- if (param == null) {
- this._selectionRenderService.changeRuntime(null, null);
- return;
- }
-
- const unitId = this._context.unitId;
- const { sheetId, skeleton } = param;
- const { scene } = this._context;
-
- const viewportMain = scene.getViewport(SHEET_VIEWPORT_KEY.VIEW_MAIN);
-
- this._selectionRenderService.changeRuntime(skeleton, scene, viewportMain);
-
- /**
- * Features like formulas can select ranges across sub-tables.
- * If the current pluginName is not in a normal state,
- * the current selection will not be refreshed.
- */
- const current = this._selectionManagerService.getCurrent();
- const pluginName = current?.pluginName || NORMAL_SELECTION_PLUGIN_NAME;
-
- if (current?.unitId === unitId && current.sheetId === sheetId) {
- const currentSelections = this._selectionManagerService.getSelections();
- if (currentSelections != null) {
- this._refreshSelection(currentSelections);
- }
- } else {
- this._selectionManagerService.setCurrentSelection({
- pluginName,
- unitId,
- sheetId,
- });
- }
-
- if (pluginName === NORMAL_SELECTION_PLUGIN_NAME) {
- // If there is no initial selection, add one by default in the top left corner.
- const last = this._selectionManagerService.getLast();
- if (last == null) {
- this._selectionManagerService.add([this._getZeroRange(skeleton)]);
- }
- }
- }));
- }
-
- private _getAllRange(skeleton: SpreadsheetSkeleton): ISelectionWithStyle {
- return {
- range: {
- startRow: 0,
- startColumn: 0,
- endRow: skeleton.getRowCount() - 1,
- endColumn: skeleton.getColumnCount() - 1,
- rangeType: RANGE_TYPE.ALL,
- },
- primary: this._getZeroRange(skeleton).primary,
- style: null,
- };
- }
-
- private _getZeroRange(skeleton: SpreadsheetSkeleton) {
- const mergeData = skeleton.mergeData;
- return (
- transformCellDataToSelectionData(0, 0, mergeData) || {
- range: {
- startRow: 0,
- startColumn: 0,
- endRow: 0,
- endColumn: 0,
- },
- primary: {
- actualRow: 0,
- actualColumn: 0,
- startRow: 0,
- startColumn: 0,
- endRow: 0,
- endColumn: 0,
- isMerged: false,
- isMergedMainCell: false,
- },
- style: null,
- }
- );
- }
-}
diff --git a/packages/sheets-ui/src/controllers/shortcuts/operation.shortcut.ts b/packages/sheets-ui/src/controllers/shortcuts/operation.shortcut.ts
index 023f0278c9..778d4c7b4d 100644
--- a/packages/sheets-ui/src/controllers/shortcuts/operation.shortcut.ts
+++ b/packages/sheets-ui/src/controllers/shortcuts/operation.shortcut.ts
@@ -20,20 +20,6 @@ import { KeyCode, MetaKeys } from '@univerjs/ui';
import { whenSheetEditorFocused } from './utils';
-// export const SetUndoShortcutItem: IShortcutItem = {
-// id: UndoCommand.id,
-// // when focusing on any other input tag do not trigger this shortcut
-// preconditions: (contextService) => whenSheetEditorFocused(contextService),
-// binding: KeyCode.Z | MetaKeys.CTRL_COMMAND,
-// };
-
-// export const SetRedoShortcutItem: IShortcutItem = {
-// id: RedoCommand.id,
-// // when focusing on any other input tag do not trigger this shortcut
-// preconditions: (contextService) => whenSheetEditorFocused(contextService),
-// binding: KeyCode.Y | MetaKeys.CTRL_COMMAND,
-// };
-
export const SetRowHiddenShortcutItem: IShortcutItem = {
id: SetRowHiddenCommand.id,
// when focusing on any other input tag do not trigger this shortcut
diff --git a/packages/sheets-ui/src/controllers/status-bar.controller.ts b/packages/sheets-ui/src/controllers/status-bar.controller.ts
index c006251812..ad0e6ff21f 100644
--- a/packages/sheets-ui/src/controllers/status-bar.controller.ts
+++ b/packages/sheets-ui/src/controllers/status-bar.controller.ts
@@ -40,9 +40,8 @@ import type {
} from '@univerjs/sheets';
import {
INumfmtService,
- NORMAL_SELECTION_PLUGIN_NAME,
- SelectionManagerService,
SetRangeValuesMutation,
+ SheetsSelectionsService,
} from '@univerjs/sheets';
import { Inject } from '@wendellhu/redi';
@@ -59,7 +58,7 @@ export class StatusBarController extends Disposable {
constructor(
@IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService,
- @Inject(SelectionManagerService) private readonly _selectionManagerService: SelectionManagerService,
+ @Inject(SheetsSelectionsService) private readonly _selectionManagerService: SheetsSelectionsService,
@IFunctionService private readonly _functionService: IFunctionService,
@IStatusBarService private readonly _statusBarService: IStatusBarService,
@ICommandService private readonly _commandService: ICommandService,
@@ -87,9 +86,6 @@ export class StatusBarController extends Disposable {
this.disposeWithMe(
toDisposable(
this._selectionManagerService.selectionMoving$.subscribe((selections) => {
- if (this._selectionManagerService.getCurrent()?.pluginName !== NORMAL_SELECTION_PLUGIN_NAME) {
- return;
- }
if (selections) {
_statisticsHandler(selections);
}
@@ -100,9 +96,6 @@ export class StatusBarController extends Disposable {
this.disposeWithMe(
toDisposable(
this._selectionManagerService.selectionMoveEnd$.subscribe((selections) => {
- if (this._selectionManagerService.getCurrent()?.pluginName !== NORMAL_SELECTION_PLUGIN_NAME) {
- return;
- }
if (selections) {
_statisticsHandler(selections);
}
@@ -113,7 +106,7 @@ export class StatusBarController extends Disposable {
this.disposeWithMe(
this._commandService.onCommandExecuted((command: ICommandInfo) => {
if (command.id === SetRangeValuesMutation.id) {
- const selections = this._selectionManagerService.getSelections();
+ const selections = this._selectionManagerService.getCurrentSelections();
if (selections) {
_statisticsHandler(selections as ISelectionWithStyle[]);
}
diff --git a/packages/sheets-ui/src/controllers/utils/component-tools.ts b/packages/sheets-ui/src/controllers/utils/component-tools.ts
index e08d8792aa..f463c2a8fe 100644
--- a/packages/sheets-ui/src/controllers/utils/component-tools.ts
+++ b/packages/sheets-ui/src/controllers/utils/component-tools.ts
@@ -49,11 +49,7 @@ function isRenderManagerService(renderManagerService: IRenderManagerService | IR
}
/**
- * @deprecated
- *
- * @param univerInstanceService
- * @param renderManagerService
- * @returns
+ * Get render objects of a spreadsheet.
*/
export function getSheetObject(
univerInstanceService: IUniverInstanceService | Workbook,
@@ -112,11 +108,11 @@ export function getCoordByOffset(
viewport?: Viewport,
closeFirst?: boolean
) {
- const relativeCoords = scene.getRelativeCoord(Vector2.FromArray([evtOffsetX, evtOffsetY]));
+ const relativeCoords = scene.getRelativeToViewportCoord(Vector2.FromArray([evtOffsetX, evtOffsetY]));
const { x: newEvtOffsetX, y: newEvtOffsetY } = relativeCoords;
- const scrollXY = scene.getScrollXYByRelativeCoords(relativeCoords, viewport);
+ const scrollXY = scene.getVpScrollXYInfoByPosToVp(relativeCoords, viewport);
const { scaleX, scaleY } = scene.getAncestorScale();
@@ -146,11 +142,11 @@ export function getCoordByOffset(
}
export function getTransformCoord(evtOffsetX: number, evtOffsetY: number, scene: Scene, skeleton: SpreadsheetSkeleton) {
- const relativeCoords = scene.getRelativeCoord(Vector2.FromArray([evtOffsetX, evtOffsetY]));
+ const relativeCoords = scene.getRelativeToViewportCoord(Vector2.FromArray([evtOffsetX, evtOffsetY]));
const viewMain = scene.getViewport(SHEET_VIEWPORT_KEY.VIEW_MAIN);
- const scrollXY = scene.getScrollXYByRelativeCoords(relativeCoords, viewMain);
+ const scrollXY = scene.getVpScrollXYInfoByPosToVp(relativeCoords, viewMain);
const { scaleX, scaleY } = scene.getAncestorScale();
const { x: scrollX, y: scrollY } = scrollXY;
diff --git a/packages/sheets-ui/src/controllers/utils/selections-tools.ts b/packages/sheets-ui/src/controllers/utils/selections-tools.ts
index 960bb62916..87facb1499 100644
--- a/packages/sheets-ui/src/controllers/utils/selections-tools.ts
+++ b/packages/sheets-ui/src/controllers/utils/selections-tools.ts
@@ -15,13 +15,14 @@
*/
import type { Workbook } from '@univerjs/core';
-import { IUniverInstanceService, Rectangle, UniverInstanceType } from '@univerjs/core';
-import { RangeProtectionRuleModel, SelectionManagerService } from '@univerjs/sheets';
+import { IUniverInstanceService, RANGE_TYPE, Rectangle, UniverInstanceType } from '@univerjs/core';
+import type { ISelectionWithStyle } from '@univerjs/sheets';
+import { RangeProtectionRuleModel, SheetsSelectionsService } from '@univerjs/sheets';
import type { IAccessor } from '@wendellhu/redi';
import { combineLatest, map } from 'rxjs';
export function getSheetSelectionsDisabled$(accessor: IAccessor) {
- const selectionManagerService = accessor.get(SelectionManagerService);
+ const selectionManagerService = accessor.get(SheetsSelectionsService);
const rangeProtectionRuleModel = accessor.get(RangeProtectionRuleModel);
const univerInstanceService = accessor.get(IUniverInstanceService);
const workbook = univerInstanceService.getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET)!;
@@ -57,3 +58,24 @@ export function getSheetSelectionsDisabled$(accessor: IAccessor) {
})
);
}
+
+export function checkInHeaderRanges(
+ selections: Readonly<ISelectionWithStyle[]>,
+ num: number,
+ rType: RANGE_TYPE.ROW | RANGE_TYPE.COLUMN
+): false | ISelectionWithStyle {
+ const matchSelectionData = selections.find((sel) => {
+ const range = sel.range;
+ const { startRow, endRow, startColumn, endColumn, rangeType } = range;
+
+ if (rangeType === RANGE_TYPE.ALL || rangeType === RANGE_TYPE.NORMAL) return false;
+
+ if (rType === RANGE_TYPE.COLUMN && RANGE_TYPE.COLUMN === rangeType) {
+ return num >= startColumn && num <= endColumn;
+ }
+
+ return rangeType === RANGE_TYPE.ROW && num >= startRow && num <= endRow;
+ });
+
+ return matchSelectionData ?? false;
+}
diff --git a/packages/sheets-ui/src/index.ts b/packages/sheets-ui/src/index.ts
index 84dc1d29bc..92f512fa69 100644
--- a/packages/sheets-ui/src/index.ts
+++ b/packages/sheets-ui/src/index.ts
@@ -31,6 +31,7 @@ export {
getSheetObject,
getTransformCoord,
} from './controllers/utils/component-tools';
+export { checkInHeaderRanges } from './controllers/utils/selections-tools';
export { useActiveWorkbook, useActiveWorksheet } from './components/hook';
export { whenSheetEditorFocused } from './controllers/shortcuts/utils';
export type { IEditorBridgeServiceParam } from './services/editor-bridge.service';
@@ -56,11 +57,12 @@ export {
} from './services/editor-bridge.service';
export { MarkSelectionService } from './services/mark-selection/mark-selection.service';
export { IMarkSelectionService } from './services/mark-selection/mark-selection.service';
-export { ISelectionRenderService } from './services/selection/selection-render.service';
-export { SelectionRenderService } from './services/selection/selection-render.service';
+export { SheetSelectionRenderService } from './services/selection/selection-render.service';
+export { getAllSelection, getTopLeftSelection } from './services/selection/base-selection-render.service';
+export { BaseSelectionRenderService, ISheetSelectionRenderService } from './services/selection/base-selection-render.service';
export { SelectionControl as SelectionShape } from './services/selection/selection-shape';
export type { ISheetSkeletonManagerParam } from './services/sheet-skeleton-manager.service';
-export { SheetSkeletonManagerService } from './services/sheet-skeleton-manager.service';
+export { SheetSkeletonManagerService, attachRangeWithCoord } from './services/sheet-skeleton-manager.service';
export { UniverSheetsUIPlugin } from './sheets-ui-plugin';
export { SheetRenderController } from './controllers/render-controllers/sheet.render-controller';
export { HoverManagerService } from './services/hover-manager.service';
diff --git a/packages/sheets-ui/src/mobile-sheets-ui-plugin.ts b/packages/sheets-ui/src/mobile-sheets-ui-plugin.ts
index 274e9dd5b2..593cfcdfc2 100644
--- a/packages/sheets-ui/src/mobile-sheets-ui-plugin.ts
+++ b/packages/sheets-ui/src/mobile-sheets-ui-plugin.ts
@@ -39,7 +39,6 @@ import { ISheetClipboardService, SheetClipboardService } from './services/clipbo
import { FormatPainterService, IFormatPainterService } from './services/format-painter/format-painter.service';
import { IMarkSelectionService, MarkSelectionService } from './services/mark-selection/mark-selection.service';
import { ScrollManagerService } from './services/scroll-manager.service';
-import { ISelectionRenderService } from './services/selection/selection-render.service';
import { ISheetBarService, SheetBarService } from './services/sheet-bar/sheet-bar.service';
import { SheetSkeletonManagerService } from './services/sheet-skeleton-manager.service';
import { ShortcutExperienceService } from './services/shortcut-experience.service';
@@ -70,8 +69,8 @@ import { SheetPrintInterceptorService } from './services/print-interceptor.servi
import { SheetUIMobileController } from './controllers/mobile/mobile-sheet-ui.controller';
import { SheetContextMenuMobileRenderController } from './controllers/render-controllers/mobile/mobile-contextmenu.render-controller';
import { SheetRenderController } from './controllers/render-controllers/sheet.render-controller';
-import { MobileSelectionRenderService } from './services/selection/mobile-selection-render.service';
-import { MobileSelectionRenderController } from './controllers/render-controllers/mobile/mobile-selection.render-controller';
+import { MobileSheetsSelectionRenderService } from './services/selection/mobile-selection-render.service';
+import { ISheetSelectionRenderService } from './services/selection/base-selection-render.service';
/**
* @ignore
@@ -106,7 +105,7 @@ export class UniverSheetsMobileUIPlugin extends Plugin {
[ScrollManagerService],
// This would be removed from global injector and moved into RenderUnit provider.
// [SheetSkeletonManagerService],
- [ISelectionRenderService, { useClass: MobileSelectionRenderService }],
+ [ISheetSelectionRenderService, { useClass: MobileSheetsSelectionRenderService }],
[IStatusBarService, { useClass: StatusBarService }],
[IMarkSelectionService, { useClass: MarkSelectionService }],
[HoverManagerService],
@@ -162,10 +161,11 @@ export class UniverSheetsMobileUIPlugin extends Plugin {
private _registerRenderBasics(): void {
([
- SheetSkeletonManagerService,
- SheetRenderController,
- ]).forEach((controller) => {
- this.disposeWithMe(this._renderManagerService.registerRenderModule(UniverInstanceType.UNIVER_SHEET, controller));
+ [SheetSkeletonManagerService],
+ [SheetRenderController],
+ [ISheetSelectionRenderService, { useClass: MobileSheetsSelectionRenderService }],
+ ] as Dependency[]).forEach((renderDep) => {
+ this.disposeWithMe(this._renderManagerService.registerRenderModule(UniverInstanceType.UNIVER_SHEET, renderDep));
});
}
@@ -177,31 +177,28 @@ export class UniverSheetsMobileUIPlugin extends Plugin {
// HeaderMoveRenderController(HMRC) must be initialized before SelectionRenderController(SRC).
// Before HMRC expected selections remain unchanged when user clicks on the header. If we don't initialize HMRC before SRC,
// the selections will be changed by SRC first. Maybe we should merge row/col header related render controllers to one class.
- HeaderMoveRenderController,
- MobileSelectionRenderController,
- HeaderFreezeRenderController,
- // HeaderUnhideRenderController,
- // HeaderResizeRenderController,
+ [HeaderMoveRenderController],
+ [HeaderFreezeRenderController],
// Caution: ScrollRenderController should placed before ZoomRenderController
// because ZoomRenderController would change scrollInfo in currentSkeletonBefore$
// currentSkeletonBefore$ --> ZoomRenderController ---> viewport.resize --> setScrollInfo, but ScrollRenderController needs scrollInfo
- MobileSheetsScrollRenderController,
- SheetsZoomRenderController,
- FormatPainterRenderController,
- // HeaderMenuRenderController,
- CellAlertRenderController,
- ForceStringAlertRenderController,
- MarkSelectionRenderController,
- HoverRenderController,
- DragRenderController,
- ForceStringRenderController,
- CellCustomRenderController,
- SheetContextMenuMobileRenderController,
- SheetPermissionInterceptorCanvasRenderController,
- SheetPermissionInterceptorFormulaRenderController,
- SheetPermissionRenderController,
- ]).forEach((controller) => {
- this.disposeWithMe(this._renderManagerService.registerRenderModule(UniverInstanceType.UNIVER_SHEET, controller));
+ [MobileSheetsScrollRenderController],
+ [SheetsZoomRenderController],
+ [FormatPainterRenderController],
+ [CellAlertRenderController],
+ [ForceStringAlertRenderController],
+ [MarkSelectionRenderController],
+ [HoverRenderController],
+ [DragRenderController],
+ [ForceStringRenderController],
+ [CellCustomRenderController],
+ [SheetContextMenuMobileRenderController],
+
+ [SheetPermissionInterceptorCanvasRenderController],
+ [SheetPermissionInterceptorFormulaRenderController],
+ [SheetPermissionRenderController],
+ ] as Dependency[]).forEach((renderModule) => {
+ this.disposeWithMe(this._renderManagerService.registerRenderModule(UniverInstanceType.UNIVER_SHEET, renderModule));
});
}
diff --git a/packages/sheets-ui/src/services/auto-fill/auto-fill.service.ts b/packages/sheets-ui/src/services/auto-fill/auto-fill.service.ts
index 2c4003674a..8dbc57bc49 100644
--- a/packages/sheets-ui/src/services/auto-fill/auto-fill.service.ts
+++ b/packages/sheets-ui/src/services/auto-fill/auto-fill.service.ts
@@ -28,7 +28,7 @@ import {
toDisposable,
UniverInstanceType,
} from '@univerjs/core';
-import { SelectionManagerService, SetSelectionsOperation } from '@univerjs/sheets';
+import { SetSelectionsOperation, SheetsSelectionsService } from '@univerjs/sheets';
import type { IDisposable } from '@wendellhu/redi';
import { createIdentifier, Inject } from '@wendellhu/redi';
import type { Observable } from 'rxjs';
@@ -128,7 +128,7 @@ export class AutoFillService extends Disposable implements IAutoFillService {
readonly menu$ = this._menu$.asObservable();
constructor(
@Inject(IUniverInstanceService) private _univerInstanceService: IUniverInstanceService,
- @Inject(SelectionManagerService) private _selectionManagerService: SelectionManagerService,
+ @Inject(SheetsSelectionsService) private _selectionManagerService: SheetsSelectionsService,
@ICommandService private _commandService: ICommandService,
@IUndoRedoService private _undoRedoService: IUndoRedoService
) {
@@ -291,7 +291,7 @@ export class AutoFillService extends Disposable implements IAutoFillService {
this._commandService.syncExecuteCommand(SetSelectionsOperation.id, {
selections: [
{
- primary: { ...(this._selectionManagerService.getLast()?.primary ?? selection) },
+ primary: { ...(this._selectionManagerService.getCurrentLastSelection()?.primary ?? selection) },
range: {
...selection,
rangeType: RANGE_TYPE.NORMAL,
diff --git a/packages/sheets-ui/src/services/clipboard/__tests__/clipboard-paste-alignment.spec.ts b/packages/sheets-ui/src/services/clipboard/__tests__/clipboard-paste-alignment.spec.ts
index ddcb0edc09..7193f8ff75 100644
--- a/packages/sheets-ui/src/services/clipboard/__tests__/clipboard-paste-alignment.spec.ts
+++ b/packages/sheets-ui/src/services/clipboard/__tests__/clipboard-paste-alignment.spec.ts
@@ -18,13 +18,12 @@ import type { ICellData, IStyleData, Nullable, Univer } from '@univerjs/core';
import { ICommandService, IUniverInstanceService, LocaleType, RANGE_TYPE } from '@univerjs/core';
import {
AddWorksheetMergeMutation,
- NORMAL_SELECTION_PLUGIN_NAME,
RemoveWorksheetMergeMutation,
- SelectionManagerService,
SetRangeValuesMutation,
SetSelectionsOperation,
SetWorksheetColWidthMutation,
SetWorksheetRowHeightMutation,
+ SheetsSelectionsService,
} from '@univerjs/sheets';
import type { Injector } from '@wendellhu/redi';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
@@ -109,19 +108,14 @@ describe('Test clipboard', () => {
describe('Test paste from external ', () => {
beforeEach(() => {
- const selectionManager = get(SelectionManagerService);
+ const selectionManager = get(SheetsSelectionsService);
- selectionManager.setCurrentSelection({
- pluginName: NORMAL_SELECTION_PLUGIN_NAME,
- unitId: 'test',
- sheetId: 'sheet1',
- });
const startRow = 1;
const startColumn = 1;
const endRow = 1;
const endColumn = 1;
- selectionManager.add([
+ selectionManager.addSelections([
{
range: { startRow, startColumn, endRow, endColumn, rangeType: RANGE_TYPE.NORMAL },
primary: null,
diff --git a/packages/sheets-ui/src/services/clipboard/__tests__/clipboard-paste-border.spec.ts b/packages/sheets-ui/src/services/clipboard/__tests__/clipboard-paste-border.spec.ts
index 425bf2f00b..4010340b52 100644
--- a/packages/sheets-ui/src/services/clipboard/__tests__/clipboard-paste-border.spec.ts
+++ b/packages/sheets-ui/src/services/clipboard/__tests__/clipboard-paste-border.spec.ts
@@ -18,13 +18,12 @@ import type { IBorderData, ICellData, IStyleData, Nullable, Univer } from '@univ
import { ICommandService, IUniverInstanceService, LocaleType, RANGE_TYPE } from '@univerjs/core';
import {
AddWorksheetMergeMutation,
- NORMAL_SELECTION_PLUGIN_NAME,
RemoveWorksheetMergeMutation,
- SelectionManagerService,
SetRangeValuesMutation,
SetSelectionsOperation,
SetWorksheetColWidthMutation,
SetWorksheetRowHeightMutation,
+ SheetsSelectionsService,
} from '@univerjs/sheets';
import type { Injector } from '@wendellhu/redi';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
@@ -118,19 +117,14 @@ describe('Test clipboard', () => {
describe('Test paste from external ', () => {
beforeEach(() => {
- const selectionManager = get(SelectionManagerService);
+ const selectionManager = get(SheetsSelectionsService);
- selectionManager.setCurrentSelection({
- pluginName: NORMAL_SELECTION_PLUGIN_NAME,
- unitId: 'test',
- sheetId: 'sheet1',
- });
const startRow = 1;
const startColumn = 1;
const endRow = 1;
const endColumn = 1;
- selectionManager.add([
+ selectionManager.addSelections([
{
range: { startRow, startColumn, endRow, endColumn, rangeType: RANGE_TYPE.NORMAL },
primary: null,
diff --git a/packages/sheets-ui/src/services/clipboard/__tests__/clipboard-paste-font.spec.ts b/packages/sheets-ui/src/services/clipboard/__tests__/clipboard-paste-font.spec.ts
index fa56e4d579..8893b25132 100644
--- a/packages/sheets-ui/src/services/clipboard/__tests__/clipboard-paste-font.spec.ts
+++ b/packages/sheets-ui/src/services/clipboard/__tests__/clipboard-paste-font.spec.ts
@@ -18,13 +18,12 @@ import type { ICellData, IStyleData, Nullable, Univer } from '@univerjs/core';
import { ICommandService, IUniverInstanceService, LocaleType, RANGE_TYPE } from '@univerjs/core';
import {
AddWorksheetMergeMutation,
- NORMAL_SELECTION_PLUGIN_NAME,
RemoveWorksheetMergeMutation,
- SelectionManagerService,
SetRangeValuesMutation,
SetSelectionsOperation,
SetWorksheetColWidthMutation,
SetWorksheetRowHeightMutation,
+ SheetsSelectionsService,
} from '@univerjs/sheets';
import type { Injector } from '@wendellhu/redi';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
@@ -118,19 +117,14 @@ describe('Test clipboard', () => {
describe('Test paste from external ', () => {
beforeEach(() => {
- const selectionManager = get(SelectionManagerService);
+ const selectionManager = get(SheetsSelectionsService);
- selectionManager.setCurrentSelection({
- pluginName: NORMAL_SELECTION_PLUGIN_NAME,
- unitId: 'test',
- sheetId: 'sheet1',
- });
const startRow = 1;
const startColumn = 1;
const endRow = 1;
const endColumn = 1;
- selectionManager.add([
+ selectionManager.addSelections([
{
range: { startRow, startColumn, endRow, endColumn, rangeType: RANGE_TYPE.NORMAL },
primary: null,
diff --git a/packages/sheets-ui/src/services/clipboard/__tests__/clipboard-paste-form-excel.spec.ts b/packages/sheets-ui/src/services/clipboard/__tests__/clipboard-paste-form-excel.spec.ts
index 4992610856..52485a41a1 100644
--- a/packages/sheets-ui/src/services/clipboard/__tests__/clipboard-paste-form-excel.spec.ts
+++ b/packages/sheets-ui/src/services/clipboard/__tests__/clipboard-paste-form-excel.spec.ts
@@ -19,13 +19,12 @@ import { ICommandService, IUniverInstanceService, LocaleType, RANGE_TYPE } from
import {
AddWorksheetMergeMutation,
MoveRangeMutation,
- NORMAL_SELECTION_PLUGIN_NAME,
RemoveWorksheetMergeMutation,
- SelectionManagerService,
SetRangeValuesMutation,
SetSelectionsOperation,
SetWorksheetColWidthMutation,
SetWorksheetRowHeightMutation,
+ SheetsSelectionsService,
} from '@univerjs/sheets';
import type { Injector } from '@wendellhu/redi';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
@@ -124,19 +123,14 @@ describe('Test clipboard', () => {
describe('Test paste from excel ', () => {
beforeEach(() => {
- const selectionManager = get(SelectionManagerService);
+ const selectionManager = get(SheetsSelectionsService);
- selectionManager.setCurrentSelection({
- pluginName: NORMAL_SELECTION_PLUGIN_NAME,
- unitId: 'test',
- sheetId: 'sheet1',
- });
const startRow = 1;
const startColumn = 1;
const endRow = 1;
const endColumn = 1;
- selectionManager.add([
+ selectionManager.addSelections([
{
range: { startRow, startColumn, endRow, endColumn, rangeType: RANGE_TYPE.NORMAL },
primary: null,
diff --git a/packages/sheets-ui/src/services/clipboard/__tests__/clipboard-paste-from-google.spec.ts b/packages/sheets-ui/src/services/clipboard/__tests__/clipboard-paste-from-google.spec.ts
index ea1b8d8d84..d05f89ccf1 100644
--- a/packages/sheets-ui/src/services/clipboard/__tests__/clipboard-paste-from-google.spec.ts
+++ b/packages/sheets-ui/src/services/clipboard/__tests__/clipboard-paste-from-google.spec.ts
@@ -19,13 +19,12 @@ import { ICommandService, IUniverInstanceService, LocaleType, RANGE_TYPE } from
import {
AddWorksheetMergeMutation,
MoveRangeMutation,
- NORMAL_SELECTION_PLUGIN_NAME,
RemoveWorksheetMergeMutation,
- SelectionManagerService,
SetRangeValuesMutation,
SetSelectionsOperation,
SetWorksheetColWidthMutation,
SetWorksheetRowHeightMutation,
+ SheetsSelectionsService,
} from '@univerjs/sheets';
import type { Injector } from '@wendellhu/redi';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
@@ -125,19 +124,14 @@ describe('Test clipboard', () => {
describe('Test paste from Google Sheet ', () => {
beforeEach(() => {
- const selectionManager = get(SelectionManagerService);
+ const selectionManager = get(SheetsSelectionsService);
- selectionManager.setCurrentSelection({
- pluginName: NORMAL_SELECTION_PLUGIN_NAME,
- unitId: 'test',
- sheetId: 'sheet1',
- });
const startRow = 1;
const startColumn = 1;
const endRow = 1;
const endColumn = 1;
- selectionManager.add([
+ selectionManager.addSelections([
{
range: { startRow, startColumn, endRow, endColumn, rangeType: RANGE_TYPE.NORMAL },
primary: null,
diff --git a/packages/sheets-ui/src/services/clipboard/__tests__/clipboard-paste-from-notepad.spec.ts b/packages/sheets-ui/src/services/clipboard/__tests__/clipboard-paste-from-notepad.spec.ts
index 7574609b52..5a557a4a9e 100644
--- a/packages/sheets-ui/src/services/clipboard/__tests__/clipboard-paste-from-notepad.spec.ts
+++ b/packages/sheets-ui/src/services/clipboard/__tests__/clipboard-paste-from-notepad.spec.ts
@@ -19,13 +19,12 @@ import { ICommandService, IUniverInstanceService, LocaleType, RANGE_TYPE } from
import {
AddWorksheetMergeMutation,
MoveRangeMutation,
- NORMAL_SELECTION_PLUGIN_NAME,
RemoveWorksheetMergeMutation,
- SelectionManagerService,
SetRangeValuesMutation,
SetSelectionsOperation,
SetWorksheetColWidthMutation,
SetWorksheetRowHeightMutation,
+ SheetsSelectionsService,
} from '@univerjs/sheets';
import type { Injector } from '@wendellhu/redi';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
@@ -104,19 +103,19 @@ describe('Test clipboard', () => {
describe('Test paste from notepad ', () => {
beforeEach(() => {
- const selectionManager = get(SelectionManagerService);
+ const selectionManager: SheetsSelectionsService = get(SheetsSelectionsService);
- selectionManager.setCurrentSelection({
- pluginName: NORMAL_SELECTION_PLUGIN_NAME,
- unitId: 'test',
- sheetId: 'sheet1',
- });
+ // selectionManager.setSelections({
+ // // pluginName: NORMAL_SELECTION_PLUGIN_NAME,
+ // unitId: 'test',
+ // sheetId: 'sheet1',
+ // });
const startRow = 1;
const startColumn = 1;
const endRow = 1;
const endColumn = 1;
- selectionManager.add([
+ selectionManager.addSelections([
{
range: { startRow, startColumn, endRow, endColumn, rangeType: RANGE_TYPE.NORMAL },
primary: null,
diff --git a/packages/sheets-ui/src/services/clipboard/__tests__/clipboard-paste-rotate.spec.ts b/packages/sheets-ui/src/services/clipboard/__tests__/clipboard-paste-rotate.spec.ts
index 151093699b..9c7f092ac1 100644
--- a/packages/sheets-ui/src/services/clipboard/__tests__/clipboard-paste-rotate.spec.ts
+++ b/packages/sheets-ui/src/services/clipboard/__tests__/clipboard-paste-rotate.spec.ts
@@ -18,13 +18,12 @@ import type { ICellData, IStyleData, Nullable, Univer } from '@univerjs/core';
import { ICommandService, IUniverInstanceService, LocaleType, RANGE_TYPE } from '@univerjs/core';
import {
AddWorksheetMergeMutation,
- NORMAL_SELECTION_PLUGIN_NAME,
RemoveWorksheetMergeMutation,
- SelectionManagerService,
SetRangeValuesMutation,
SetSelectionsOperation,
SetWorksheetColWidthMutation,
SetWorksheetRowHeightMutation,
+ SheetsSelectionsService,
} from '@univerjs/sheets';
import type { Injector } from '@wendellhu/redi';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
@@ -118,19 +117,14 @@ describe('Test clipboard', () => {
describe('Test paste from univer ', () => {
beforeEach(() => {
- const selectionManager = get(SelectionManagerService);
+ const selectionManager = get(SheetsSelectionsService);
- selectionManager.setCurrentSelection({
- pluginName: NORMAL_SELECTION_PLUGIN_NAME,
- unitId: 'test',
- sheetId: 'sheet1',
- });
const startRow = 1;
const startColumn = 1;
const endRow = 1;
const endColumn = 1;
- selectionManager.add([
+ selectionManager.addSelections([
{
range: { startRow, startColumn, endRow, endColumn, rangeType: RANGE_TYPE.NORMAL },
primary: null,
diff --git a/packages/sheets-ui/src/services/clipboard/__tests__/clipboard-service.spec.ts b/packages/sheets-ui/src/services/clipboard/__tests__/clipboard-service.spec.ts
index 06a2d1daca..48290704f8 100644
--- a/packages/sheets-ui/src/services/clipboard/__tests__/clipboard-service.spec.ts
+++ b/packages/sheets-ui/src/services/clipboard/__tests__/clipboard-service.spec.ts
@@ -19,13 +19,12 @@ import { ICommandService, IUniverInstanceService, RANGE_TYPE, Rectangle, RedoCom
import {
AddWorksheetMergeMutation,
MoveRangeMutation,
- NORMAL_SELECTION_PLUGIN_NAME,
RemoveWorksheetMergeMutation,
- SelectionManagerService,
SetRangeValuesMutation,
SetSelectionsOperation,
SetWorksheetColWidthMutation,
SetWorksheetRowHeightMutation,
+ SheetsSelectionsService,
} from '@univerjs/sheets';
import type { Injector } from '@wendellhu/redi';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
@@ -134,13 +133,7 @@ describe('Test clipboard', () => {
describe('Test paste, the original data is a merged cell of 1 row and 2 columns, the current selection consists only of ordinary cells', () => {
it('The current selection is a single cell in 1 row and 1 column', async () => {
- const selectionManager = get(SelectionManagerService);
-
- selectionManager.setCurrentSelection({
- pluginName: NORMAL_SELECTION_PLUGIN_NAME,
- unitId: 'test',
- sheetId: 'sheet1',
- });
+ const selectionManager = get(SheetsSelectionsService);
// set selection to A1
const startRow = 0;
@@ -148,7 +141,7 @@ describe('Test clipboard', () => {
const endRow = 0;
const endColumn = 0;
- selectionManager.add([
+ selectionManager.addSelections([
{
range: { startRow, startColumn, endRow, endColumn, rangeType: RANGE_TYPE.NORMAL },
primary: null,
@@ -219,13 +212,7 @@ describe('Test clipboard', () => {
});
});
it('The current selection is a single cell in 1 row and 2 columns', async () => {
- const selectionManager = get(SelectionManagerService);
-
- selectionManager.setCurrentSelection({
- pluginName: NORMAL_SELECTION_PLUGIN_NAME,
- unitId: 'test',
- sheetId: 'sheet1',
- });
+ const selectionManager = get(SheetsSelectionsService);
// set selection to A2:B2
const startRow = 1;
@@ -233,7 +220,7 @@ describe('Test clipboard', () => {
const endRow = 1;
const endColumn = 1;
- selectionManager.add([
+ selectionManager.addSelections([
{
range: { startRow, startColumn, endRow, endColumn, rangeType: RANGE_TYPE.NORMAL },
primary: null,
@@ -298,13 +285,7 @@ describe('Test clipboard', () => {
});
});
it('The current selection is a single cell in 1 row and 3 columns', async () => {
- const selectionManager = get(SelectionManagerService);
-
- selectionManager.setCurrentSelection({
- pluginName: NORMAL_SELECTION_PLUGIN_NAME,
- unitId: 'test',
- sheetId: 'sheet1',
- });
+ const selectionManager = get(SheetsSelectionsService);
// set selection to A3:C3
const startRow = 2;
@@ -312,7 +293,7 @@ describe('Test clipboard', () => {
const endRow = 2;
const endColumn = 2;
- selectionManager.add([
+ selectionManager.addSelections([
{
range: { startRow, startColumn, endRow, endColumn, rangeType: RANGE_TYPE.NORMAL },
primary: null,
@@ -379,13 +360,7 @@ describe('Test clipboard', () => {
});
});
it('The current selection is a single cell in 2 rows and 2 columns', async () => {
- const selectionManager = get(SelectionManagerService);
-
- selectionManager.setCurrentSelection({
- pluginName: NORMAL_SELECTION_PLUGIN_NAME,
- unitId: 'test',
- sheetId: 'sheet1',
- });
+ const selectionManager = get(SheetsSelectionsService);
// set selection to A4:B5
const startRow = 3;
@@ -393,7 +368,7 @@ describe('Test clipboard', () => {
const endRow = 4;
const endColumn = 1;
- selectionManager.add([
+ selectionManager.addSelections([
{
range: { startRow, startColumn, endRow, endColumn, rangeType: RANGE_TYPE.NORMAL },
primary: null,
@@ -512,13 +487,7 @@ describe('Test clipboard', () => {
]);
});
it('The current selection is a single cell in 4 rows and 4 columns', async () => {
- const selectionManager = get(SelectionManagerService);
-
- selectionManager.setCurrentSelection({
- pluginName: NORMAL_SELECTION_PLUGIN_NAME,
- unitId: 'test',
- sheetId: 'sheet1',
- });
+ const selectionManager = get(SheetsSelectionsService);
// set selection to A6:D9
const startRow = 5;
@@ -526,7 +495,7 @@ describe('Test clipboard', () => {
const endRow = 8;
const endColumn = 3;
- selectionManager.add([
+ selectionManager.addSelections([
{
range: { startRow, startColumn, endRow, endColumn, rangeType: RANGE_TYPE.NORMAL },
primary: null,
@@ -686,13 +655,7 @@ describe('Test clipboard', () => {
describe('Test paste, the original data is a merged cell of 1 row and 2 columns, the current selection contains merged cells and no content', () => {
it('The current selection is a merged cell of 1 row and 2 columns.', async () => {
- const selectionManager = get(SelectionManagerService);
-
- selectionManager.setCurrentSelection({
- pluginName: NORMAL_SELECTION_PLUGIN_NAME,
- unitId: 'test',
- sheetId: 'sheet1',
- });
+ const selectionManager = get(SheetsSelectionsService);
// set selection to F1:G2
const startRow = 0;
@@ -700,7 +663,7 @@ describe('Test clipboard', () => {
const endRow = 0;
const endColumn = 6;
- selectionManager.add([
+ selectionManager.addSelections([
{
range: { startRow, startColumn, endRow, endColumn, rangeType: RANGE_TYPE.NORMAL },
primary: null,
@@ -767,13 +730,7 @@ describe('Test clipboard', () => {
});
it('The current selection is a merged cell of 1 row and 3 columns.', async () => {
- const selectionManager = get(SelectionManagerService);
-
- selectionManager.setCurrentSelection({
- pluginName: NORMAL_SELECTION_PLUGIN_NAME,
- unitId: 'test',
- sheetId: 'sheet1',
- });
+ const selectionManager = get(SheetsSelectionsService);
// set selection to F3:H3
const startRow = 2;
@@ -781,7 +738,7 @@ describe('Test clipboard', () => {
const endRow = 2;
const endColumn = 7;
- selectionManager.add([
+ selectionManager.addSelections([
{
range: { startRow, startColumn, endRow, endColumn, rangeType: RANGE_TYPE.NORMAL },
primary: null,
@@ -794,13 +751,7 @@ describe('Test clipboard', () => {
});
it('The current selection is a merged cell of 1 row and 4 columns.', async () => {
- const selectionManager = get(SelectionManagerService);
-
- selectionManager.setCurrentSelection({
- pluginName: NORMAL_SELECTION_PLUGIN_NAME,
- unitId: 'test',
- sheetId: 'sheet1',
- });
+ const selectionManager = get(SheetsSelectionsService);
// set selection to F5:I5
const startRow = 4;
@@ -808,7 +759,7 @@ describe('Test clipboard', () => {
const endRow = 4;
const endColumn = 8;
- selectionManager.add([
+ selectionManager.addSelections([
{
range: { startRow, startColumn, endRow, endColumn, rangeType: RANGE_TYPE.NORMAL },
primary: null,
@@ -821,13 +772,7 @@ describe('Test clipboard', () => {
});
it('The current selection is a merged cell of 2 rows and 2 columns.', async () => {
- const selectionManager = get(SelectionManagerService);
-
- selectionManager.setCurrentSelection({
- pluginName: NORMAL_SELECTION_PLUGIN_NAME,
- unitId: 'test',
- sheetId: 'sheet1',
- });
+ const selectionManager = get(SheetsSelectionsService);
// set selection to F7:G8
const startRow = 6;
@@ -835,7 +780,7 @@ describe('Test clipboard', () => {
const endRow = 7;
const endColumn = 6;
- selectionManager.add([
+ selectionManager.addSelections([
{
range: { startRow, startColumn, endRow, endColumn, rangeType: RANGE_TYPE.NORMAL },
primary: null,
@@ -848,13 +793,7 @@ describe('Test clipboard', () => {
});
it('The current selection is a merged cell of 1 row and 2 columns, with 1 ordinary cell', async () => {
- const selectionManager = get(SelectionManagerService);
-
- selectionManager.setCurrentSelection({
- pluginName: NORMAL_SELECTION_PLUGIN_NAME,
- unitId: 'test',
- sheetId: 'sheet1',
- });
+ const selectionManager = get(SheetsSelectionsService);
// set selection to F10:H10
const startRow = 9;
@@ -862,7 +801,7 @@ describe('Test clipboard', () => {
const endRow = 9;
const endColumn = 7;
- selectionManager.add([
+ selectionManager.addSelections([
{
range: { startRow, startColumn, endRow, endColumn, rangeType: RANGE_TYPE.NORMAL },
primary: null,
@@ -929,13 +868,7 @@ describe('Test clipboard', () => {
});
it('The current selection is a merged cell of 2 rows and 2 columns, with a merged cell of 2 rows and 1 column', async () => {
- const selectionManager = get(SelectionManagerService);
-
- selectionManager.setCurrentSelection({
- pluginName: NORMAL_SELECTION_PLUGIN_NAME,
- unitId: 'test',
- sheetId: 'sheet1',
- });
+ const selectionManager = get(SheetsSelectionsService);
// set selection to F12:H13
const startRow = 11;
@@ -943,7 +876,7 @@ describe('Test clipboard', () => {
const endRow = 12;
const endColumn = 7;
- selectionManager.add([
+ selectionManager.addSelections([
{
range: { startRow, startColumn, endRow, endColumn, rangeType: RANGE_TYPE.NORMAL },
primary: null,
@@ -965,13 +898,7 @@ describe('Test clipboard', () => {
describe('Test paste, the original data is a merged cell of 1 row and 2 columns, the current selection contains merged cells with content and style', () => {
it('The current selection is a merged cell of 1 row and 3 columns', async () => {
- const selectionManager = get(SelectionManagerService);
-
- selectionManager.setCurrentSelection({
- pluginName: NORMAL_SELECTION_PLUGIN_NAME,
- unitId: 'test',
- sheetId: 'sheet1',
- });
+ const selectionManager = get(SheetsSelectionsService);
// set selection to K4:M4
const startRow = 3;
@@ -979,7 +906,7 @@ describe('Test clipboard', () => {
const endRow = 3;
const endColumn = 12;
- selectionManager.add([
+ selectionManager.addSelections([
{
range: { startRow, startColumn, endRow, endColumn, rangeType: RANGE_TYPE.NORMAL },
primary: null,
@@ -991,13 +918,7 @@ describe('Test clipboard', () => {
expect(res).toBeFalsy();
});
it('The current selection is a merged cell of 1 row and 2 columns, with a merged cell of 2 rows and 2 columns', async () => {
- const selectionManager = get(SelectionManagerService);
-
- selectionManager.setCurrentSelection({
- pluginName: NORMAL_SELECTION_PLUGIN_NAME,
- unitId: 'test',
- sheetId: 'sheet1',
- });
+ const selectionManager = get(SheetsSelectionsService);
// set selection to K7:M10
const startRow = 6;
@@ -1005,7 +926,7 @@ describe('Test clipboard', () => {
const endRow = 9;
const endColumn = 12;
- selectionManager.add([
+ selectionManager.addSelections([
{
range: { startRow, startColumn, endRow, endColumn, rangeType: RANGE_TYPE.NORMAL },
primary: null,
@@ -1086,13 +1007,7 @@ describe('Test clipboard', () => {
]);
});
it('The current selection is a merged cell of 1 row and 3 columns, with a merged cell of 2 rows and 2 columns', async () => {
- const selectionManager = get(SelectionManagerService);
-
- selectionManager.setCurrentSelection({
- pluginName: NORMAL_SELECTION_PLUGIN_NAME,
- unitId: 'test',
- sheetId: 'sheet1',
- });
+ const selectionManager = get(SheetsSelectionsService);
// set selection to K12:M15
const startRow = 11;
@@ -1100,7 +1015,7 @@ describe('Test clipboard', () => {
const endRow = 14;
const endColumn = 12;
- selectionManager.add([
+ selectionManager.addSelections([
{
range: { startRow, startColumn, endRow, endColumn, rangeType: RANGE_TYPE.NORMAL },
primary: null,
@@ -1144,13 +1059,7 @@ describe('Test clipboard', () => {
]);
});
it('The current selection is a merged cell of 2 rows and 2 columns, with a merged cell of 1 row and 2 columns', async () => {
- const selectionManager = get(SelectionManagerService);
-
- selectionManager.setCurrentSelection({
- pluginName: NORMAL_SELECTION_PLUGIN_NAME,
- unitId: 'test',
- sheetId: 'sheet1',
- });
+ const selectionManager = get(SheetsSelectionsService);
// set selection to K22:M24
const startRow = 21;
@@ -1158,7 +1067,7 @@ describe('Test clipboard', () => {
const endRow = 23;
const endColumn = 12;
- selectionManager.add([
+ selectionManager.addSelections([
{
range: { startRow, startColumn, endRow, endColumn, rangeType: RANGE_TYPE.NORMAL },
primary: null,
@@ -1221,15 +1130,9 @@ describe('Test clipboard', () => {
copyType: COPY_TYPE.CUT,
});
- const selectionManager = get(SelectionManagerService);
-
- selectionManager.setCurrentSelection({
- pluginName: NORMAL_SELECTION_PLUGIN_NAME,
- unitId: 'test',
- sheetId: 'sheet1',
- });
+ const selectionManager = get(SheetsSelectionsService);
- selectionManager.add([
+ selectionManager.addSelections([
{
range: { ...toRange, rangeType: RANGE_TYPE.NORMAL },
primary: null,
diff --git a/packages/sheets-ui/src/services/clipboard/__tests__/clipboard-test-bed.ts b/packages/sheets-ui/src/services/clipboard/__tests__/clipboard-test-bed.ts
index e95728b8f1..e5351f908b 100644
--- a/packages/sheets-ui/src/services/clipboard/__tests__/clipboard-test-bed.ts
+++ b/packages/sheets-ui/src/services/clipboard/__tests__/clipboard-test-bed.ts
@@ -19,7 +19,7 @@
import type { IWorkbookData } from '@univerjs/core';
import { DisposableCollection, ILogService, IUniverInstanceService, LocaleService, LocaleType, LogLevel, Plugin, Univer, UniverInstanceType } from '@univerjs/core';
import { IRenderManagerService, RenderManagerService } from '@univerjs/engine-render';
-import { SelectionManagerService, SheetInterceptorService } from '@univerjs/sheets';
+import { SheetInterceptorService, SheetsSelectionsService } from '@univerjs/sheets';
import {
BrowserClipboardService,
DesktopMessageService,
@@ -34,9 +34,10 @@ import { Inject, Injector } from '@wendellhu/redi';
import { CalculateFormulaService, DefinedNamesService, FormulaCurrentConfigService, FormulaDataModel, FormulaRuntimeService, IDefinedNamesService, IFormulaCurrentConfigService, IFormulaRuntimeService, LexerTreeBuilder } from '@univerjs/engine-formula';
import { SheetClipboardController } from '../../../controllers/clipboard/clipboard.controller';
import { IMarkSelectionService } from '../../mark-selection/mark-selection.service';
-import { ISelectionRenderService, SelectionRenderService } from '../../selection/selection-render.service';
+import { SheetSelectionRenderService } from '../../selection/selection-render.service';
import { ISheetClipboardService, SheetClipboardService } from '../clipboard.service';
import { SheetSkeletonManagerService } from '../../sheet-skeleton-manager.service';
+import { ISheetSelectionRenderService } from '../../selection/base-selection-render.service';
const cellData = {
0: {
@@ -362,91 +363,91 @@ const mergeData = [
startColumn: 10,
endColumn: 11,
},
- // check
+ // check
{
startRow: 0,
startColumn: 5,
endRow: 0,
endColumn: 6,
},
- // check
+ // check
{
startRow: 2,
startColumn: 5,
endRow: 2,
endColumn: 7,
},
- // check
+ // check
{
startRow: 4,
startColumn: 5,
endRow: 4,
endColumn: 8,
},
- // check
+ // check
{
startRow: 6,
startColumn: 5,
endRow: 7,
endColumn: 6,
},
- // check
+ // check
{
startRow: 9,
startColumn: 5,
endRow: 9,
endColumn: 6,
},
- // check
+ // check
{
startRow: 11,
startColumn: 5,
endRow: 12,
endColumn: 6,
},
- // check
+ // check
{
startRow: 11,
startColumn: 7,
endRow: 12,
endColumn: 7,
},
- // check
+ // check
{
startRow: 0,
startColumn: 10,
endRow: 0,
endColumn: 11,
},
- // check
+ // check
{
startRow: 3,
startColumn: 10,
endRow: 3,
endColumn: 12,
},
- // check
+ // check
{
startRow: 6,
startColumn: 10,
endRow: 6,
endColumn: 11,
},
- // check
+ // check
{
startRow: 8,
startColumn: 11,
endRow: 9,
endColumn: 12,
},
- // check
+ // check
{
startRow: 11,
startColumn: 10,
endRow: 11,
endColumn: 12,
},
- // check
+ // check
{
startRow: 13,
startColumn: 11,
@@ -489,15 +490,15 @@ export class testMarkSelectionService {
}
removeShape(id: string): void {
- // empty
+ // empty
}
removeAllShapes(): void {
- // empty
+ // empty
}
refreshShapes(): void {
- // empty
+ // empty
}
getShapeMap(): Map<string, any> {
@@ -525,9 +526,9 @@ export function clipboardTestBed(workbookData?: IWorkbookData, dependencies?: De
const injector = univer.__getInjector();
const get = injector.get.bind(injector);
- /**
- * This plugin hooks into Sheet's DI system to expose API to test scripts
- */
+ /**
+ * This plugin hooks into Sheet's DI system to expose API to test scripts
+ */
class TestPlugin extends Plugin {
static override pluginName = 'test-plugin';
static override type = UniverInstanceType.UNIVER_SHEET;
@@ -540,7 +541,7 @@ export function clipboardTestBed(workbookData?: IWorkbookData, dependencies?: De
}
override onStarting(injector: Injector): void {
- injector.add([SelectionManagerService]);
+ injector.add([SheetsSelectionsService]);
injector.add([IClipboardInterfaceService, { useClass: BrowserClipboardService, lazy: true }]);
injector.add([ISheetClipboardService, { useClass: SheetClipboardService }]);
injector.add([IMessageService, { useClass: DesktopMessageService, lazy: true }]);
@@ -551,11 +552,11 @@ export function clipboardTestBed(workbookData?: IWorkbookData, dependencies?: De
},
]);
injector.add([IRenderManagerService, { useClass: RenderManagerService }]);
- injector.add([ISelectionRenderService, { useClass: SelectionRenderService }]);
+ injector.add([ISheetSelectionRenderService, { useClass: SheetSelectionRenderService }]);
injector.add([INotificationService, { useClass: testNotificationService }]);
injector.add([IPlatformService, { useClass: testPlatformService }]);
- // Because SheetClipboardController is initialized in the rendered life cycle, here we need to initialize it manually
+ // Because SheetClipboardController is initialized in the rendered life cycle, here we need to initialize it manually
const sheetClipboardController = injector.createInstance(SheetClipboardController);
injector.add([SheetClipboardController, { useValue: sheetClipboardController }]);
@@ -583,8 +584,8 @@ export function clipboardTestBed(workbookData?: IWorkbookData, dependencies?: De
const logService = get(ILogService);
logService.setLogLevel(LogLevel.SILENT); // change this to `LogLevel.VERBOSE` to debug tests via logs
- // NOTE: This is pretty hack for the test. But with these hacks we can avoid to create
- // real canvas-environment in univerjs/sheets-ui. If some we have to do that, this hack could be removed.
+ // NOTE: This is pretty hack for the test. But with these hacks we can avoid to create
+ // real canvas-environment in univerjs/sheets-ui. If some we have to do that, this hack could be removed.
const fakeSheetSkeletonManagerService = new SheetSkeletonManagerService({
unit: sheet,
unitId: 'test',
diff --git a/packages/sheets-ui/src/services/clipboard/clipboard.service.ts b/packages/sheets-ui/src/services/clipboard/clipboard.service.ts
index 34a34f0ac0..80586a51da 100644
--- a/packages/sheets-ui/src/services/clipboard/clipboard.service.ts
+++ b/packages/sheets-ui/src/services/clipboard/clipboard.service.ts
@@ -25,6 +25,7 @@ import {
IUniverInstanceService,
LocaleService,
ObjectMatrix,
+ ThemeService,
toDisposable,
Tools,
UniverInstanceType,
@@ -32,9 +33,8 @@ import {
import type { ISetSelectionsOperationParams } from '@univerjs/sheets';
import {
getPrimaryForRange,
- NORMAL_SELECTION_PLUGIN_NAME,
- SelectionManagerService,
SetSelectionsOperation,
+ SheetsSelectionsService,
} from '@univerjs/sheets';
import { HTML_CLIPBOARD_MIME_TYPE, IClipboardInterfaceService, INotificationService, IPlatformService, PLAIN_TEXT_CLIPBOARD_MIME_TYPE } from '@univerjs/ui';
import type { IDisposable } from '@wendellhu/redi';
@@ -47,6 +47,7 @@ import { IMarkSelectionService } from '../mark-selection/mark-selection.service'
import { SheetSkeletonManagerService } from '../sheet-skeleton-manager.service';
import type { IDiscreteRange } from '../../controllers/utils/range-tools';
import { rangeToDiscreteRange, virtualizeDiscreteRanges } from '../../controllers/utils/range-tools';
+import { createCopyPasteSelectionStyle } from '../utils/selection-util';
import { CopyContentCache, extractId, genId } from './copy-content-cache';
import { HtmlToUSMService } from './html-to-usm/converter';
@@ -117,7 +118,7 @@ export class SheetClipboardService extends Disposable implements ISheetClipboard
constructor(
@ILogService private readonly _logService: ILogService,
@IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService,
- @Inject(SelectionManagerService) private readonly _selectionManagerService: SelectionManagerService,
+ @Inject(SheetsSelectionsService) private readonly _selectionManagerService: SheetsSelectionsService,
@IClipboardInterfaceService private readonly _clipboardInterfaceService: IClipboardInterfaceService,
@IUndoRedoService private readonly _undoRedoService: IUndoRedoService,
@ICommandService private readonly _commandService: ICommandService,
@@ -125,6 +126,7 @@ export class SheetClipboardService extends Disposable implements ISheetClipboard
@INotificationService private readonly _notificationService: INotificationService,
@IPlatformService private readonly _platformService: IPlatformService,
@IRenderManagerService private readonly _renderManagerService: IRenderManagerService,
+ @Inject(ThemeService) private readonly _themeService: ThemeService,
@Inject(LocaleService) private readonly _localeService: LocaleService,
@Inject(ErrorService) private readonly _errorService: ErrorService,
@Inject(Injector) private readonly _injector: Injector
@@ -153,7 +155,7 @@ export class SheetClipboardService extends Disposable implements ISheetClipboard
}
async copy(copyType = COPY_TYPE.COPY): Promise<boolean> {
- const selection = this._selectionManagerService.getLast();
+ const selection = this._selectionManagerService.getCurrentLastSelection();
if (!selection) {
return false; // maybe we should notify user that there is no selection
}
@@ -187,7 +189,7 @@ export class SheetClipboardService extends Disposable implements ISheetClipboard
// 5. mark the copy range
this._markSelectionService.removeAllShapes();
- const style = this._selectionManagerService.createCopyPasteSelection();
+ const style = createCopyPasteSelectionStyle(this._themeService);
this._copyMarkId = this._markSelectionService.addShape({ ...selection, style });
return true;
@@ -727,7 +729,6 @@ export class SheetClipboardService extends Disposable implements ISheetClipboard
const setSelectionsParam: ISetSelectionsOperationParams = {
unitId,
subUnitId,
- pluginName: NORMAL_SELECTION_PLUGIN_NAME,
selections: [{
range: {
startRow,
@@ -746,7 +747,7 @@ export class SheetClipboardService extends Disposable implements ISheetClipboard
private _getPastingTarget() {
const workbook = this._univerInstanceService.getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET)!;
const worksheet = workbook.getActiveSheet();
- const selection = this._selectionManagerService.getLast();
+ const selection = this._selectionManagerService.getCurrentLastSelection();
return {
unitId: workbook.getUnitId(),
subUnitId: worksheet?.getSheetId(),
diff --git a/packages/sheets-ui/src/services/editor-bridge.service.ts b/packages/sheets-ui/src/services/editor-bridge.service.ts
index 8985d42dca..537eb32292 100644
--- a/packages/sheets-ui/src/services/editor-bridge.service.ts
+++ b/packages/sheets-ui/src/services/editor-bridge.service.ts
@@ -37,8 +37,9 @@ import { createIdentifier, Inject } from '@wendellhu/redi';
import type { Observable } from 'rxjs';
import { BehaviorSubject } from 'rxjs';
-import { ISelectionRenderService } from './selection/selection-render.service';
import { SheetSkeletonManagerService } from './sheet-skeleton-manager.service';
+import { ISheetSelectionRenderService } from './selection/base-selection-render.service';
+import { attachPrimaryWithCoord } from './selection/util';
export interface IEditorBridgeServiceVisibleParam {
visible: boolean;
@@ -127,7 +128,6 @@ export class EditorBridgeService extends Disposable implements IEditorBridgeServ
constructor(
@IRenderManagerService private readonly _renderManagerService: IRenderManagerService,
- @ISelectionRenderService private readonly _selectionRenderService: ISelectionRenderService,
@Inject(ThemeService) private readonly _themeService: ThemeService,
@IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService,
@IEditorService private readonly _editorService: IEditorService
@@ -182,30 +182,27 @@ export class EditorBridgeService extends Disposable implements IEditorBridgeServ
return;
}
- const skeleton = this._renderManagerService.withCurrentTypeOfUnit(UniverInstanceType.UNIVER_SHEET, SheetSkeletonManagerService)?.getCurrentSkeleton();
- if (skeleton == null) {
- return;
- }
+ const ru = this._renderManagerService.getCurrentTypeOfRenderer(UniverInstanceType.UNIVER_SHEET);
+ if (!ru) return;
+
+ const skeleton = ru.with(SheetSkeletonManagerService).getCurrentSkeleton();
+ const selectionRenderService = ru.with(ISheetSelectionRenderService);
const { primary, unitId, sheetId, scene, engine } = currentEditCell;
const { startRow, startColumn } = primary;
- const primaryWithCoord = this._selectionRenderService.attachPrimaryWithCoord(primary);
+ const primaryWithCoord = attachPrimaryWithCoord(primary, skeleton);
if (primaryWithCoord == null) {
return;
}
const actualRangeWithCoord = makeCellToSelection(primaryWithCoord);
- if (actualRangeWithCoord == null) {
- return;
- }
-
const canvasOffset = getCanvasOffsetByEngine(engine);
let { startX, startY, endX, endY } = actualRangeWithCoord;
const { scaleX, scaleY } = scene.getAncestorScale();
- const scrollXY = scene.getScrollXY(this._selectionRenderService.getViewPort());
+ const scrollXY = scene.getViewportScrollXY(selectionRenderService.getViewPort());
startX = skeleton.convertTransformToOffsetX(startX, scaleX, scrollXY);
startY = skeleton.convertTransformToOffsetY(startY, scaleY, scrollXY);
endX = skeleton.convertTransformToOffsetX(endX, scaleX, scrollXY);
diff --git a/packages/sheets-ui/src/services/format-painter/format-painter.service.ts b/packages/sheets-ui/src/services/format-painter/format-painter.service.ts
index a14be91b40..599b59ac6f 100644
--- a/packages/sheets-ui/src/services/format-painter/format-painter.service.ts
+++ b/packages/sheets-ui/src/services/format-painter/format-painter.service.ts
@@ -15,13 +15,14 @@
*/
import type { IMutationInfo, IRange, IStyleData } from '@univerjs/core';
-import { Disposable, ICommandService, ILogService, IUndoRedoService, IUniverInstanceService, ObjectMatrix } from '@univerjs/core';
-import { SelectionManagerService, SetRangeValuesMutation } from '@univerjs/sheets';
+import { Disposable, ICommandService, ILogService, IUndoRedoService, ObjectMatrix, ThemeService } from '@univerjs/core';
+import { SetRangeValuesMutation, SheetsSelectionsService } from '@univerjs/sheets';
import { createIdentifier, Inject } from '@wendellhu/redi';
import type { Observable } from 'rxjs';
import { BehaviorSubject } from 'rxjs';
import { IMarkSelectionService } from '../mark-selection/mark-selection.service';
+import { createCopyPasteSelectionStyle } from '../utils/selection-util';
export interface IFormatPainterService {
status$: Observable<FormatPainterStatus>;
@@ -70,8 +71,8 @@ export class FormatPainterService extends Disposable implements IFormatPainterSe
private _extendHooks: IFormatPainterHook[] = [];
constructor(
- @Inject(SelectionManagerService) private readonly _selectionManagerService: SelectionManagerService,
- @IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService,
+ @Inject(SheetsSelectionsService) private readonly _selectionManagerService: SheetsSelectionsService,
+ @Inject(ThemeService) private readonly _themeService: ThemeService,
@IMarkSelectionService private readonly _markSelectionService: IMarkSelectionService,
@ILogService private readonly _logService: ILogService,
@ICommandService private readonly _commandService: ICommandService,
@@ -157,9 +158,9 @@ export class FormatPainterService extends Disposable implements IFormatPainterSe
this._markSelectionService.removeAllShapes();
if (status !== FormatPainterStatus.OFF) {
- const selection = this._selectionManagerService.getLast();
+ const selection = this._selectionManagerService.getCurrentLastSelection();
if (selection) {
- const style = this._selectionManagerService.createCopyPasteSelection();
+ const style = createCopyPasteSelectionStyle(this._themeService);
if (status === FormatPainterStatus.INFINITE) {
this._markId = this._markSelectionService.addShape({ ...selection, style });
} else {
diff --git a/packages/sheets-ui/src/services/hover-manager.service.ts b/packages/sheets-ui/src/services/hover-manager.service.ts
index 38c6ed142e..7111dec89d 100644
--- a/packages/sheets-ui/src/services/hover-manager.service.ts
+++ b/packages/sheets-ui/src/services/hover-manager.service.ts
@@ -86,7 +86,7 @@ export class HoverManagerService extends Disposable {
}
const currentRender = this._renderManagerService.getRenderById(workbook.getUnitId());
- const skeletonParam = currentRender?.with(SheetSkeletonManagerService).getUnitSkeleton(workbook.getUnitId(), worksheet.getSheetId());
+ const skeletonParam = currentRender?.with(SheetSkeletonManagerService).getWorksheetSkeleton(worksheet.getSheetId());
const scrollInfo = this._scrollManagerService.getCurrentScrollInfo();
if (!skeletonParam || !scrollInfo || !currentRender) return;
diff --git a/packages/sheets-ui/src/services/mark-selection/mark-selection.service.ts b/packages/sheets-ui/src/services/mark-selection/mark-selection.service.ts
index 93f7162320..af067ce91d 100644
--- a/packages/sheets-ui/src/services/mark-selection/mark-selection.service.ts
+++ b/packages/sheets-ui/src/services/mark-selection/mark-selection.service.ts
@@ -15,14 +15,15 @@
*/
import type { Workbook } from '@univerjs/core';
-import { Disposable, IUniverInstanceService, ThemeService, toDisposable, Tools, UniverInstanceType } from '@univerjs/core';
+import { Disposable, IUniverInstanceService, ThemeService, Tools, UniverInstanceType } from '@univerjs/core';
import { IRenderManagerService } from '@univerjs/engine-render';
import type { ISelectionWithStyle } from '@univerjs/sheets';
import { createIdentifier, Inject } from '@wendellhu/redi';
-import { ISelectionRenderService } from '../selection/selection-render.service';
+// import { ISheetSelectionRenderService } from '../selection/base-selection-render.service';
import { SelectionControl } from '../selection/selection-shape';
import { SheetSkeletonManagerService } from '../sheet-skeleton-manager.service';
+import { ISheetSelectionRenderService } from '../selection/base-selection-render.service';
export interface IMarkSelectionService {
addShape(selection: ISelectionWithStyle, exits?: string[], zIndex?: number): string | null;
@@ -50,15 +51,9 @@ export class MarkSelectionService extends Disposable implements IMarkSelectionSe
constructor(
@IUniverInstanceService private readonly _currentService: IUniverInstanceService,
@IRenderManagerService private readonly _renderManagerService: IRenderManagerService,
- @ISelectionRenderService private readonly _selectionRenderService: ISelectionRenderService,
@Inject(ThemeService) private readonly _themeService: ThemeService
) {
super();
-
- const selectionMovingStartOb = this._selectionRenderService.selectionMoveStart$.subscribe(() => {
- this.removeAllShapes();
- });
- this.disposeWithMe(toDisposable(selectionMovingStartOb));
}
addShape(selection: ISelectionWithStyle, exits: string[] = [], zIndex: number = DEFAULT_Z_INDEX): string | null {
@@ -96,15 +91,15 @@ export class MarkSelectionService extends Disposable implements IMarkSelectionSe
const { style } = selection;
const renderUnit = this._renderManagerService.getRenderById(unitId);
- const scene = renderUnit?.scene;
- const { rangeWithCoord, primaryWithCoord } =
- this._selectionRenderService.attachSelectionWithCoord(selection);
+ if (!renderUnit) return;
const skeleton = this._renderManagerService.withCurrentTypeOfUnit(UniverInstanceType.UNIVER_SHEET, SheetSkeletonManagerService)?.getCurrentSkeleton();
- if (!scene || !skeleton) return;
+ if (!skeleton) return;
+ const { scene } = renderUnit;
const { rowHeaderWidth, columnHeaderHeight } = skeleton;
const control = new SelectionControl(scene, zIndex, false, this._themeService);
+ const { rangeWithCoord, primaryWithCoord } = renderUnit.with(ISheetSelectionRenderService).attachSelectionWithCoord(selection);
control.update(rangeWithCoord, rowHeaderWidth, columnHeaderHeight, style, primaryWithCoord);
shape.control = control;
});
diff --git a/packages/sheets-ui/src/services/selection/__test__/create-service-test-bed.ts b/packages/sheets-ui/src/services/selection/__test__/create-service-test-bed.ts
deleted file mode 100644
index 6d855a3e7d..0000000000
--- a/packages/sheets-ui/src/services/selection/__test__/create-service-test-bed.ts
+++ /dev/null
@@ -1,142 +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 { IWorkbookData, Workbook } from '@univerjs/core';
-import {
- BooleanNumber,
- ILogService,
- IUniverInstanceService,
- LogLevel,
- Plugin,
- Univer,
- UniverInstanceType,
-} from '@univerjs/core';
-import type { Dependency } from '@wendellhu/redi';
-import { Inject, Injector } from '@wendellhu/redi';
-
-const TEST_WORKBOOK_DATA_DEMO: () => IWorkbookData = () => ({
- id: 'workbook-01',
- sheetOrder: ['uE_mIgOi73GuLCvu577On'],
- name: 'UniverSheet Demo',
- appVersion: '3.0.0-alpha',
- locale: 'zhCN' as any,
- styles: {},
- sheets: {
- uE_mIgOi73GuLCvu577On: {
- type: 0,
- name: '工作表 11',
- id: 'uE_mIgOi73GuLCvu577On',
- tabColor: '',
- hidden: 0,
- rowCount: 1000,
- columnCount: 20,
- zoomRatio: 1,
- freeze: {
- xSplit: 0,
- ySplit: 0,
- startRow: -1,
- startColumn: -1,
- },
- scrollTop: 0,
- scrollLeft: 0,
- defaultColumnWidth: 73,
- defaultRowHeight: 19,
- mergeData: [],
- hideRow: [],
- hideColumn: [],
- cellData: {},
- rowData: {
- 3: {
- hd: 0,
- h: 96.328125,
- ia: BooleanNumber.FALSE,
- },
- },
- columnData: {
- 4: {
- w: 212.28515625,
- hd: 0,
- },
- },
- status: 0,
- showGridlines: 1,
- rowHeader: {
- width: 46,
- hidden: 0,
- },
- columnHeader: {
- height: 20,
- hidden: 0,
- },
- selections: ['A1'],
- rightToLeft: 0,
- },
- },
- resources: [
- {
- name: 'SHEET_NUMFMT_PLUGIN',
- data: '{"model":{},"refModel":[]}',
- },
- ],
- __env__: {
- gitHash: '3511862e4',
- gitBranch: 'dev',
- buildTime: '2024-01-06T02:45:20.103Z',
- },
-});
-
-export interface ITestBed {
- univer: Univer;
- get: Injector['get'];
- sheet: Workbook;
-}
-
-export function createCommandTestBed(workbookData?: IWorkbookData, dependencies?: Dependency[]): ITestBed {
- const univer = new Univer();
- const injector = univer.__getInjector();
-
- class TestPlugin extends Plugin {
- static override pluginName = 'test-plugin';
- static override type = UniverInstanceType.UNIVER_SHEET;
-
- constructor(
- _config: undefined,
- @Inject(Injector) override readonly _injector: Injector
- ) {
- super();
- this._injector = _injector;
- }
-
- override onStarting(injector: Injector): void {
- dependencies?.forEach((d) => injector.add(d));
- }
- }
-
- univer.registerPlugin(TestPlugin);
- const sheet = univer.createUniverSheet(workbookData || TEST_WORKBOOK_DATA_DEMO());
-
- const univerInstanceService = injector.get(IUniverInstanceService);
- univerInstanceService.focusUnit('test');
- const logService = injector.get(ILogService);
-
- logService.setLogLevel(LogLevel.SILENT); // change this to `LogLevel.VERBOSE` to debug tests via logs
-
- return {
- univer,
- get: injector.get.bind(injector),
- sheet,
- };
-}
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
deleted file mode 100644
index 364e0efb73..0000000000
--- a/packages/sheets-ui/src/services/selection/__test__/selection-render.test.ts
+++ /dev/null
@@ -1,282 +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 { IContextService, LocaleService, ThemeService } from '@univerjs/core';
-import type { CURSOR_TYPE, IMouseEvent } from '@univerjs/engine-render';
-import {
- DeviceType,
- IRenderManagerService,
- RenderManagerService,
- Scene,
- SpreadsheetSkeleton,
- ThinEngine,
-} from '@univerjs/engine-render';
-import type { ISelectionWithCoordAndStyle } from '@univerjs/sheets';
-import { IPlatformService, IShortcutService, PlatformService, ShortcutService } from '@univerjs/ui';
-import type { Injector } from '@wendellhu/redi';
-import { beforeEach, describe, expect, it } from 'vitest';
-
-import { SheetSkeletonManagerService } from '../../sheet-skeleton-manager.service';
-import { SelectionRenderService } from '../selection-render.service';
-import { createCommandTestBed } from './create-service-test-bed';
-
-const theme = {
- colorBlack: '#35322b',
-};
-
-const mockEvent: IMouseEvent = {
- altKey: false,
- button: 0,
- buttons: 1,
- clientX: 150,
- clientY: 200,
- layerX: 0,
- layerY: 0,
- ctrlKey: false,
- metaKey: false,
- movementX: 0,
- movementY: 0,
- mozMovementX: 0, // Optional, specific to Firefox, can be undefined
- mozMovementY: 0, // Optional, specific to Firefox, can be undefined
- msMovementX: 0, // Optional, specific to Microsoft browsers, can be undefined or any type
- msMovementY: 0, // Optional, specific to Microsoft browsers, can be undefined or any type
- offsetX: 75,
- offsetY: 100,
- shiftKey: false,
- webkitMovementX: 0, // Optional, specific to WebKit browsers, can be undefined or any type
- webkitMovementY: 0, // Optional, specific to WebKit browsers, can be undefined or any type
- x: 150, // Alias of clientX
- y: 200,
- deviceType: DeviceType.Generic,
- inputIndex: 0,
- previousState: undefined,
- currentState: undefined,
- bubbles: false,
- cancelBubble: false,
- cancelable: false,
- composed: false,
- currentTarget: null,
- defaultPrevented: false,
- eventPhase: 0,
- isTrusted: false,
- returnValue: false,
- srcElement: null,
- target: null,
- timeStamp: 0,
- type: '',
- composedPath(): EventTarget[] {
- throw new Error('Function not implemented.');
- },
- initEvent(type: string, bubbles?: boolean | undefined, cancelable?: boolean | undefined): void {
- throw new Error('Function not implemented.');
- },
- preventDefault(): void {
- throw new Error('Function not implemented.');
- },
- stopImmediatePropagation(): void {
- throw new Error('Function not implemented.');
- },
- stopPropagation(): void {
- throw new Error('Function not implemented.');
- },
- NONE: 0,
- CAPTURING_PHASE: 1,
- AT_TARGET: 2,
- BUBBLING_PHASE: 3,
- detail: 0,
- view: null,
- which: 0,
- initUIEvent(
- typeArg: string,
- bubblesArg?: boolean | undefined,
- cancelableArg?: boolean | undefined,
- viewArg?: Window | null | undefined,
- detailArg?: number | undefined
- ): void {
- throw new Error('Function not implemented.');
- },
- pageX: 0,
- pageY: 0,
- relatedTarget: null,
- screenX: 0,
- screenY: 0,
- getModifierState(keyArg: string): boolean {
- throw new Error('Function not implemented.');
- },
- initMouseEvent(
- typeArg: string,
- canBubbleArg: boolean,
- cancelableArg: boolean,
- viewArg: Window,
- detailArg: number,
- screenXArg: number,
- screenYArg: number,
- clientXArg: number,
- clientYArg: number,
- ctrlKeyArg: boolean,
- altKeyArg: boolean,
- shiftKeyArg: boolean,
- metaKeyArg: boolean,
- buttonArg: number,
- relatedTargetArg: EventTarget | null
- ): void {
- throw new Error('Function not implemented.');
- },
-};
-
-class MockEngine extends ThinEngine<Scene> {
- setRemainCapture(): void {
- // empty
- }
-
- clearCanvas() {
- // empty
- }
-
- getCanvas() {
- return 1 as any;
- }
-
- getCanvasElement() {
- return 1 as any;
- }
-
- setCanvasCursor(val: CURSOR_TYPE) {
- // empty
- }
-
- getPixelRatio() {
- return 1;
- }
-}
-
-describe('Test indirect', () => {
- let get: Injector['get'];
-
- let themeService: ThemeService;
- let selectionRenderService: SelectionRenderService;
-
- let selectionStartParam: ISelectionWithCoordAndStyle[];
-
- let selectionMovingParam: ISelectionWithCoordAndStyle[];
-
- let selectionEndParam: ISelectionWithCoordAndStyle[];
-
- let selectionServiceUsable: boolean;
-
- beforeEach(() => {
- const testBed = createCommandTestBed(undefined, [
- [IShortcutService, { useClass: ShortcutService }],
- [SheetSkeletonManagerService],
- [SelectionRenderService],
- [IPlatformService, { useClass: PlatformService }],
- [IRenderManagerService, { useClass: RenderManagerService }],
- ]);
-
- get = testBed.get;
-
- const localeService = get(LocaleService);
- const contextService = get(IContextService);
-
- themeService = get(ThemeService);
- themeService.setTheme(theme);
-
- selectionRenderService = get(SelectionRenderService);
-
- const workbook = testBed.sheet;
-
- const worksheet = workbook?.getActiveSheet()!;
-
- const config = worksheet.getConfig();
-
- const skeleton = new SpreadsheetSkeleton(
- worksheet,
- config,
- worksheet.getCellMatrix(),
- workbook.getStyles(),
- localeService,
- contextService
- );
-
- const scene = new Scene('', new MockEngine());
-
- selectionRenderService.changeRuntime(skeleton, scene);
-
- selectionRenderService.selectionMoveStart$.subscribe((param) => {
- selectionStartParam = param;
- });
-
- selectionRenderService.selectionMoving$.subscribe((param) => {
- selectionMovingParam = param;
- });
-
- selectionRenderService.selectionMoveEnd$.subscribe((param) => {
- selectionEndParam = param;
- });
-
- selectionRenderService.usable$.subscribe((param) => {
- selectionServiceUsable = param;
- });
-
- selectionRenderService.eventTrigger(mockEvent);
-
- scene.triggerPointerMove({ ...mockEvent, offsetX: 200 });
-
- scene.triggerPointerUp({ ...mockEvent, offsetX: 500 });
- });
-
- describe('normal', () => {
- it('Observer is valid', () => {
- expect(selectionServiceUsable).toBeTruthy();
-
- expect(selectionStartParam == null).toBeFalsy();
-
- expect(selectionMovingParam == null).toBeFalsy();
-
- expect(selectionEndParam == null).toBeFalsy();
- });
-
- it('selectionStart', () => {
- const { startRow, startColumn, endRow, endColumn } = selectionStartParam[0].rangeWithCoord;
- expect({ startRow, startColumn, endRow, endColumn }).toStrictEqual({
- startRow: 3,
- startColumn: 0,
- endRow: 3,
- endColumn: 0,
- });
- });
-
- it('selectionMoving', () => {
- const { startRow, startColumn, endRow, endColumn } = selectionMovingParam[0].rangeWithCoord;
- expect({ startRow, startColumn, endRow, endColumn }).toStrictEqual({
- startRow: 3,
- startColumn: 0,
- endRow: 3,
- endColumn: 2,
- });
- });
-
- it('selectionEnd', () => {
- const { startRow, startColumn, endRow, endColumn } = selectionEndParam[0].rangeWithCoord;
- expect({ startRow, startColumn, endRow, endColumn }).toStrictEqual({
- startRow: 3,
- startColumn: 0,
- endRow: 3,
- endColumn: 2,
- });
- });
- });
-});
diff --git a/packages/sheets-ui/src/services/selection/base-selection-render.service.ts b/packages/sheets-ui/src/services/selection/base-selection-render.service.ts
new file mode 100644
index 0000000000..43d5f21b7d
--- /dev/null
+++ b/packages/sheets-ui/src/services/selection/base-selection-render.service.ts
@@ -0,0 +1,1002 @@
+/**
+ * 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 {
+ IInterceptor,
+ IRange,
+ IRangeWithCoord,
+ ISelectionCell,
+ ISelectionCellWithMergeInfo,
+
+ ISelectionWithCoord,
+ Nullable,
+ ThemeService,
+} from '@univerjs/core';
+import { Disposable, InterceptorManager, makeCellToSelection, RANGE_TYPE, UniverInstanceType } from '@univerjs/core';
+import type { IMouseEvent, IPointerEvent, IRenderManagerService, IRenderModule, Scene, SpreadsheetSkeleton, Viewport } from '@univerjs/engine-render';
+import { ScrollTimer, ScrollTimerType, SHEET_VIEWPORT_KEY, Vector2 } from '@univerjs/engine-render';
+import type { ISelectionStyle, ISelectionWithCoordAndStyle, ISelectionWithStyle } from '@univerjs/sheets';
+import { getNormalSelectionStyle, transformCellDataToSelectionData } from '@univerjs/sheets';
+import type { IShortcutService } from '@univerjs/ui';
+import { createIdentifier, type Injector } from '@wendellhu/redi';
+import type { Observable, Subscription } from 'rxjs';
+import { BehaviorSubject, Subject } from 'rxjs';
+
+import { SheetSkeletonManagerService } from '../sheet-skeleton-manager.service';
+import { RANGE_FILL_PERMISSION_CHECK, RANGE_MOVE_PERMISSION_CHECK } from './const';
+import { SelectionControl } from './selection-shape';
+import { SelectionShapeExtension } from './selection-shape-extension';
+import { attachPrimaryWithCoord, attachSelectionWithCoord } from './util';
+
+export interface IControlFillConfig {
+ oldRange: IRange;
+ newRange: IRange;
+}
+
+export interface ISheetSelectionRenderService {
+ readonly selectionMoveEnd$: Observable<ISelectionWithCoordAndStyle[]>;
+ readonly controlFillConfig$: Observable<IControlFillConfig | null>;
+ readonly selectionMoving$: Observable<ISelectionWithCoordAndStyle[]>;
+ readonly selectionMoveStart$: Observable<ISelectionWithCoordAndStyle[]>;
+
+ interceptor: InterceptorManager<{
+ RANGE_MOVE_PERMISSION_CHECK: IInterceptor<boolean, null>;
+ RANGE_FILL_PERMISSION_CHECK: IInterceptor<boolean, { x: number; y: number; skeleton: SpreadsheetSkeleton; scene: Scene }>;
+ }>;
+
+ /** @deprecated This should not be provided by the selection render service. */
+ getViewPort(): Viewport; // AutoFill
+
+ getSkeleton(): SpreadsheetSkeleton;
+
+ getSelectionControls(): SelectionControl[]; // AutoFill
+
+ // The following methods are used to get range locations in a worksheet. Though `attachRangeWithCoord` should not happens here.
+ // And `attachPrimaryWithCoord` is redundant.
+
+ /** @deprecated Use the function `attachSelectionWithCoord` instead. */
+ attachSelectionWithCoord(selectionWithStyle: ISelectionWithStyle): ISelectionWithCoordAndStyle;
+ /** @deprecated Use the function `attachPrimaryWithCoord` instead`. */
+ attachPrimaryWithCoord(primary: Nullable<Partial<ISelectionCell>>): Nullable<ISelectionCellWithMergeInfo>;
+
+ getSelectionCellByPosition(x: number, y: number): Nullable<ISelectionCellWithMergeInfo>; // drawing
+}
+
+export const ISheetSelectionRenderService = createIdentifier<ISheetSelectionRenderService>('univer.sheet.selection-render-service');
+
+/**
+ * The basic implementation of selection rendering logics. It is designed to be reused for different purposes.
+ */
+export class BaseSelectionRenderService extends Disposable implements ISheetSelectionRenderService, IRenderModule {
+ private _downObserver: Nullable<Subscription>;
+ protected _scenePointerMoveSub: Nullable<Subscription>;
+ protected _scenePointerUpSub: Nullable<Subscription>;
+
+ private _controlFillConfig$: BehaviorSubject<IControlFillConfig | null> =
+ new BehaviorSubject<IControlFillConfig | null>(null);
+
+ readonly controlFillConfig$ = this._controlFillConfig$.asObservable();
+
+ protected _selectionControls: SelectionControl[] = []; // sheetID:Controls
+
+ protected _startRangeWhenPointerDown: IRangeWithCoord = {
+ startY: 0,
+ endY: 0,
+ startX: 0,
+ endX: 0,
+ startRow: -1,
+ endRow: -1,
+ startColumn: -1,
+ endColumn: -1,
+ };
+
+ /**
+ * the posX of viewport when the pointer down
+ */
+ protected _startViewportPosX: number = 0;
+
+ /**
+ * the posY of viewport when the pointer down
+ */
+ protected _startViewportPosY: number = 0;
+
+ protected _scrollTimer!: ScrollTimer;
+
+ private _cancelDownSubscription: Nullable<Subscription>;
+ private _cancelUpSubscription: Nullable<Subscription>;
+
+ protected _skeleton!: SpreadsheetSkeleton;
+ protected _scene!: Scene;
+
+ // The type of selector determines the type of data range and the highlighting style of the title bar
+ protected _isHeaderHighlight: boolean = true;
+
+ // If true, the selector will respond to the range of merged cells and automatically extend the selected range. If false, it will ignore the merged cells.
+ protected _shouldDetectMergedCells: boolean = true;
+
+ // The style of the selection area, including dashed lines, color, thickness, autofill, other points for modifying the range of the selection area, title highlighting, and so on, can all be customized.
+ protected _selectionStyle!: ISelectionStyle;
+
+ // #region ref range selection
+ // we put the properties here for simplicity
+ // Used in the formula selection feature, a new selection string is added by drawing a box with the mouse.
+ protected _remainLastEnabled: boolean = false;
+ protected _skipLastEnabled: boolean = false;
+ protected _singleSelectionEnabled: boolean = false;
+ // #endregion
+
+ protected readonly _selectionMoveEnd$ = new BehaviorSubject<ISelectionWithCoordAndStyle[]>([]);
+ readonly selectionMoveEnd$ = this._selectionMoveEnd$.asObservable();
+ protected readonly _selectionMoving$ = new Subject<ISelectionWithCoordAndStyle[]>();
+ readonly selectionMoving$ = this._selectionMoving$.asObservable();
+ protected readonly _selectionMoveStart$ = new Subject<ISelectionWithCoordAndStyle[]>();
+ readonly selectionMoveStart$ = this._selectionMoveStart$.asObservable();
+
+ protected _activeViewport: Nullable<Viewport>;
+
+ readonly interceptor = new InterceptorManager({ RANGE_MOVE_PERMISSION_CHECK, RANGE_FILL_PERMISSION_CHECK });
+
+ constructor(
+ protected readonly _injector: Injector,
+ protected readonly _themeService: ThemeService,
+ // WTF: why shortcutService is injected here?
+ protected readonly _shortcutService: IShortcutService,
+ protected readonly _renderManagerService: IRenderManagerService
+ ) {
+ super();
+ this._resetStyle();
+ // @ts-expect-error
+ if (!window.srs) window.srs = this;
+ }
+
+ protected _setStyle(style: ISelectionStyle) {
+ this._selectionStyle = style;
+ }
+
+ protected _resetStyle() {
+ this._setStyle(getNormalSelectionStyle(this._themeService));
+ }
+
+ /** @deprecated This should not be provided by the selection render service. */
+ getViewPort() {
+ return this._activeViewport!;
+ }
+
+ /**
+ * add a selection
+ *
+ * in PC:init & pointerup would call this function.
+ *
+ * init
+ * selectionController@_initSkeletonChangeListener --> selectionManagerService.add --> selectionManagerService._selectionMoveEnd$ --> this.addControlToCurrentByRangeData
+ *
+ * selectionMoveEnd$ --> this.addSelectionControlBySelectionData
+ *
+ *
+ *
+ * pointer
+ * engine@_pointerDownEvent --> spreadsheet?.onPointerDownObserve --> eventTrigger --> scene@disableEvent() --> then scene.input-manager currentObject is always scene until scene@enableEvent.
+ * engine@_pointerUpEvent --> scene.input-manager@_onPointerUp --> this._selectionMoveEnd$ --> _selectionManagerService.selectionMoveEnd$ --> this.addControlToCurrentByRangeData
+ *
+ * but in mobile, we do not call disableEvent() in eventTrigger,
+ * so pointerup --> scene.input-manager currentObject is spreadsheet --> this.eventTrigger
+ *
+ *
+ * columnHeader pointerup$ --> selectionMoveEnd$ --> selectionManagerService@setSelections -->
+ * selectionManagerService@_emitOnEnd -->
+ * _workbookSelections.selectionMoveEnd$ --> _addSelectionControlBySelectionData
+ *
+ *
+ * @param selectionData
+ */
+ protected _addSelectionControlBySelectionData(selection: ISelectionWithCoordAndStyle) {
+ const { rangeWithCoord, primaryWithCoord } = selection;
+ const { rangeType } = rangeWithCoord;
+ const skeleton = this._skeleton;
+ const style = selection.style ?? getNormalSelectionStyle(this._themeService);
+
+ const scene = this._scene;
+ if (!scene || !skeleton) {
+ return;
+ }
+
+ const control = this.newSelectionControl(scene, rangeType || RANGE_TYPE.NORMAL);
+
+ // TODO: memory leak? This extension seems never released.
+ // eslint-disable-next-line no-new
+ new SelectionShapeExtension(control, skeleton, scene, this._themeService, this._injector);
+
+ const { rowHeaderWidth, columnHeaderHeight } = skeleton;
+
+ // update control
+ control.update(rangeWithCoord, rowHeaderWidth, columnHeaderHeight, style, primaryWithCoord);
+ }
+
+ newSelectionControl(scene: Scene, _rangeType: RANGE_TYPE): SelectionControl {
+ const selectionControls = this.getSelectionControls();
+
+ const control = new SelectionControl(scene, selectionControls.length, this._isHeaderHighlight, this._themeService);//this._selectionStyle);
+ this._selectionControls.push(control);
+
+ return control;
+ }
+
+ updateControlForCurrentByRangeData(selections: ISelectionWithCoordAndStyle[]) {
+ const currentControls = this.getSelectionControls();
+ if (!currentControls) {
+ return;
+ }
+
+ const skeleton = this._skeleton;
+
+ if (skeleton == null) {
+ return;
+ }
+
+ const { rowHeaderWidth, columnHeaderHeight } = skeleton;
+
+ for (let i = 0, len = selections.length; i < len; i++) {
+ const { rangeWithCoord, primaryWithCoord, style } = selections[i];
+
+ const control = currentControls[i];
+
+ control.update(rangeWithCoord, rowHeaderWidth, columnHeaderHeight, style, primaryWithCoord);
+ }
+ }
+
+ refreshSelectionMoveStart() {
+ this._selectionMoveStart$.next(this.getSelectionDataWithStyle());
+ }
+
+ protected _changeRuntime(skeleton: SpreadsheetSkeleton, scene: Scene, viewport?: Viewport) {
+ this._skeleton = skeleton;
+ this._scene = scene;
+ this._activeViewport = viewport || scene?.getViewports()[0];
+ }
+
+ getSkeleton() {
+ return this._skeleton;
+ }
+
+ getSelectionDataWithStyle(): ISelectionWithCoordAndStyle[] {
+ const selectionControls = this._selectionControls;
+ return selectionControls.map((control) => control.getValue());
+ }
+
+ getSelectionControls() {
+ return this._selectionControls;
+ }
+
+ protected _clearSelectionControls() {
+ const allSelectionControls = this.getSelectionControls();
+ for (const control of allSelectionControls) {
+ control.dispose();
+ }
+
+ this._selectionControls.length = 0; // clear currentSelectionControls
+ }
+
+ protected _getFreeze() {
+ const freeze = this._renderManagerService.withCurrentTypeOfUnit(UniverInstanceType.UNIVER_SHEET, SheetSkeletonManagerService)
+ ?.getCurrent()?.skeleton.getWorksheetConfig().freeze;
+ return freeze;
+ }
+
+ protected _getViewportByCell(row?: number, column?: number) {
+ if (row === undefined || column === undefined) {
+ return null;
+ }
+ const freeze = this._getFreeze();
+ if (!freeze || (freeze.startRow <= 0 && freeze.startColumn <= 0)) {
+ return this._scene.getViewport(SHEET_VIEWPORT_KEY.VIEW_MAIN);
+ }
+
+ if (row > freeze.startRow && column > freeze.startColumn) {
+ return this._scene.getViewport(SHEET_VIEWPORT_KEY.VIEW_MAIN);
+ }
+
+ if (row <= freeze.startRow && column <= freeze.startColumn) {
+ return this._scene.getViewport(SHEET_VIEWPORT_KEY.VIEW_MAIN_LEFT_TOP);
+ }
+
+ if (row <= freeze.startRow && column > freeze.startColumn) {
+ return this._scene.getViewport(SHEET_VIEWPORT_KEY.VIEW_MAIN_TOP);
+ }
+
+ if (row > freeze.startRow && column <= freeze.startColumn) {
+ return this._scene.getViewport(SHEET_VIEWPORT_KEY.VIEW_MAIN_LEFT);
+ }
+ }
+
+ /**
+ * Returns the selected range in the active sheet, or null if there is no active range. If multiple ranges are selected this method returns only the last selected range.
+ */
+ getActiveRange(): Nullable<IRange> {
+ const controls = this.getSelectionControls();
+ const model = controls && controls[controls.length - 1].model;
+ return (
+ model && {
+ startRow: model.startRow,
+ startColumn: model.startColumn,
+ endRow: model.endRow,
+ endColumn: model.endColumn,
+ }
+ );
+ }
+
+ /**
+ * get active selection control
+ * @returns T extends SelectionControl
+ */
+ getActiveSelectionControl<T extends SelectionControl = SelectionControl>(): Nullable<T> {
+ const controls = this.getSelectionControls();
+ if (controls) {
+ return controls[controls.length - 1] as T;
+ }
+ }
+
+ endSelection() {
+ this._clearEndingListeners();
+
+ // ---> _updateSelections --> executeCommand(SetSelectionsOperation.id --> selectionManager.setSelections
+ // ---> _selectionMoveEnd$.next --> _initSelectionChangeListener _reset --> _clearSelectionControls
+
+ this._selectionMoveEnd$.next(this.getSelectionDataWithStyle());
+
+ // when selection mouse up, enable the short cut service
+ this._shortcutService.setDisable(false);
+ }
+
+ protected _reset() {
+ this._clearSelectionControls();
+ this._clearMove();
+
+ this._downObserver?.unsubscribe();
+ this._downObserver = null;
+ this._scenePointerUpSub?.unsubscribe();
+ this._scenePointerUpSub = null;
+ }
+
+ resetAndEndSelection() {
+ this.endSelection();
+ this._reset();
+ }
+
+ // TODO: @wzhudev: refactor the method to make it more readable
+
+ /**
+ *
+ * @param evt component point event
+ * @param style selection style, Styles for user-customized selectors
+ * @param _zIndex Stacking order of the selection object
+ * @param rangeType Determines whether the selection is made normally according to the range or by rows and columns
+ */
+ // eslint-disable-next-line max-lines-per-function, complexity
+ protected _onPointerDown(
+ evt: IPointerEvent | IMouseEvent,
+ _zIndex = 0,
+ rangeType: RANGE_TYPE = RANGE_TYPE.NORMAL,
+ viewport?: Viewport,
+ scrollTimerType: ScrollTimerType = ScrollTimerType.ALL
+ ) {
+ this._shouldDetectMergedCells = rangeType === RANGE_TYPE.NORMAL;
+
+ const skeleton = this._skeleton;
+ const scene = this._scene;
+ if (!scene || !skeleton) {
+ return;
+ }
+
+ if (viewport) {
+ this._activeViewport = viewport;
+ }
+
+ const { offsetX: evtOffsetX, offsetY: evtOffsetY } = evt;
+ const viewportMain = scene.getViewport(SHEET_VIEWPORT_KEY.VIEW_MAIN);
+ if (!viewportMain) return;
+ const relativeCoords = scene.getRelativeToViewportCoord(Vector2.FromArray([evtOffsetX, evtOffsetY]));
+
+ let { x: viewportPosX, y: viewportPosY } = relativeCoords;
+ this._startViewportPosX = viewportPosX;
+ this._startViewportPosY = viewportPosY;
+
+ const scrollXY = scene.getVpScrollXYInfoByPosToVp(relativeCoords);
+ const { scaleX, scaleY } = scene.getAncestorScale();
+ const cursorCellRangeInfo = this._getCellRangeByCursorPosition(viewportPosX, viewportPosY, scaleX, scaleY, scrollXY);
+ if (!cursorCellRangeInfo) return false;
+
+ const { rangeWithCoord: cursorCellRange, primaryWithCoord: primaryCursorCellRange } = cursorCellRangeInfo;
+ const cursorCellRangeWithRangeType: IRangeWithCoord = { ...cursorCellRange, rangeType };
+ this._startRangeWhenPointerDown = { ...cursorCellRange, rangeType };
+
+ let activeSelectionControl: Nullable<SelectionControl> = this.getActiveSelectionControl();
+ const curControls = this.getSelectionControls();
+ for (const control of curControls) {
+ // right click
+ if (evt.button === 2 && control.model.isInclude(cursorCellRangeWithRangeType)) {
+ activeSelectionControl = control;
+ return;
+ }
+ // Click to an existing selection
+ if (control.model.isEqual(cursorCellRangeWithRangeType)) {
+ activeSelectionControl = control;
+ break;
+ }
+
+ // There can only be one highlighted cell, so clear the highlighted cell of the existing selection
+ if (!evt.shiftKey) {
+ control.clearHighlight();
+ }
+ }
+
+ this._checkClearPreviousControls(evt);
+
+ const currentCell = activeSelectionControl?.model.currentCell;
+ const expandByShiftKey = evt.shiftKey && currentCell;
+ const remainLastEnable = this._remainLastEnabled &&
+ !evt.ctrlKey &&
+ !evt.shiftKey &&
+ !this._skipLastEnabled &&
+ !this._singleSelectionEnabled;
+
+ //#region update selection control
+ if (expandByShiftKey && currentCell) {
+ // Perform pointer down selection.
+ this._performSelectionByTwoCells(
+ currentCell,
+ cursorCellRangeWithRangeType,
+ skeleton,
+ rangeType,
+ activeSelectionControl! // Get updated in this method
+ );
+ } else if (remainLastEnable && activeSelectionControl) {
+ // Supports the formula ref text selection feature,
+ // under the condition of preserving all previous selections, it modifies the position of the latest selection.
+ this._updateSelectionControlRange(
+ activeSelectionControl,
+ cursorCellRangeWithRangeType,
+ primaryCursorCellRange
+ );
+ } else {
+ // Create new control as default
+ activeSelectionControl = this.newSelectionControl(scene, rangeType);
+ this._updateSelectionControlRange(
+ activeSelectionControl,
+ cursorCellRangeWithRangeType,
+ primaryCursorCellRange
+ );
+ }
+ //#endregion
+
+ this._selectionMoveStart$.next(this.getSelectionDataWithStyle());
+
+ scene.disableEvent();
+ this._clearEndingListeners();
+ this._addEndingListeners();
+
+ scene.getTransformer()?.clearSelectedObjects();
+
+ if (rangeType === RANGE_TYPE.ROW || rangeType === RANGE_TYPE.COLUMN) {
+ if (rangeType === RANGE_TYPE.ROW) {
+ viewportPosX = 0;
+ } else if (rangeType === RANGE_TYPE.COLUMN) {
+ viewportPosY = 0;
+ }
+ this._moving(viewportPosX, viewportPosY, activeSelectionControl, rangeType);
+ }
+ // #region setup moving
+ this._setupPointerMoveListener(viewportMain, activeSelectionControl!, rangeType, scrollTimerType, viewportPosX, viewportPosY);
+ // #endregion
+
+ this._shortcutService.setDisable(true);
+ this._scenePointerUpSub = scene.onPointerUp$.subscribeEvent(() => {
+ this._clearEndingListeners();
+ this._selectionMoveEnd$.next(this.getSelectionDataWithStyle());
+ this._shortcutService.setDisable(false);
+ });
+ }
+
+ // eslint-disable-next-line max-lines-per-function
+ protected _setupPointerMoveListener(
+ viewportMain: Nullable<Viewport>,
+ activeSelectionControl: SelectionControl,
+ rangeType: RANGE_TYPE,
+ scrollTimerType: ScrollTimerType = ScrollTimerType.ALL,
+ moveStartPosX: number,
+ moveStartPosY: number
+ ): void {
+ let xCrossTime = 0;
+ let yCrossTime = 0;
+ let lastX = moveStartPosX;
+ let lastY = moveStartPosY;
+ this._scrollTimer = ScrollTimer.create(this._scene, scrollTimerType);
+ this._scrollTimer.startScroll(viewportMain?.left ?? 0, viewportMain?.top ?? 0, viewportMain);
+
+ const scene = this._scene;
+ const startViewport = scene.getActiveViewportByCoord(Vector2.FromArray([moveStartPosX, moveStartPosY]));
+
+ // #region onPointerMove$
+ // eslint-disable-next-line max-lines-per-function, complexity
+ this._scenePointerMoveSub = scene.onPointerMove$.subscribeEvent((moveEvt: IPointerEvent | IMouseEvent) => {
+ const { offsetX: moveOffsetX, offsetY: moveOffsetY } = moveEvt;
+
+ const { x: newMoveOffsetX, y: newMoveOffsetY } = scene.getRelativeToViewportCoord(Vector2.FromArray([moveOffsetX, moveOffsetY]));
+
+ this._moving(newMoveOffsetX, newMoveOffsetY, activeSelectionControl, rangeType);
+
+ let scrollOffsetX = newMoveOffsetX;
+ let scrollOffsetY = newMoveOffsetY;
+
+ const currentSelection = this.getActiveSelectionControl();
+ const freeze = this._getFreeze();
+
+ const selection = currentSelection?.model;
+ const endViewport =
+ scene.getActiveViewportByCoord(Vector2.FromArray([moveOffsetX, moveOffsetY])) ??
+ this._getViewportByCell(selection?.endRow, selection?.endColumn);
+
+ if (startViewport && endViewport && viewportMain) {
+ const isCrossingX =
+ (lastX < viewportMain.left && newMoveOffsetX > viewportMain.left) ||
+ (lastX > viewportMain.left && newMoveOffsetX < viewportMain.left);
+ const isCrossingY =
+ (lastY < viewportMain.top && newMoveOffsetY > viewportMain.top) ||
+ (lastY > viewportMain.top && newMoveOffsetY < viewportMain.top);
+
+ if (isCrossingX) {
+ xCrossTime += 1;
+ }
+
+ if (isCrossingY) {
+ yCrossTime += 1;
+ }
+
+ const startKey = startViewport.viewportKey;
+ const endKey = endViewport.viewportKey;
+
+ if (startKey === SHEET_VIEWPORT_KEY.VIEW_ROW_TOP) {
+ if (moveOffsetY < viewportMain.top && (selection?.endRow ?? 0) < (freeze?.startRow ?? 0)) {
+ scrollOffsetY = viewportMain.top;
+ } else if (isCrossingY && yCrossTime % 2 === 1) {
+ viewportMain.scrollTo({
+ y: 0,
+ });
+ }
+ } else if (startKey === SHEET_VIEWPORT_KEY.VIEW_COLUMN_LEFT) {
+ if (moveOffsetX < viewportMain.left && (selection?.endColumn ?? 0) < (freeze?.startColumn ?? 0)) {
+ scrollOffsetX = viewportMain.left;
+ } else if (isCrossingX && xCrossTime % 2 === 1) {
+ viewportMain.scrollTo({
+ x: 0,
+ });
+ }
+ } else if (startKey === endKey) {
+ let disableX = false;
+ let disableY = false;
+ if (startKey === SHEET_VIEWPORT_KEY.VIEW_MAIN_LEFT_TOP) {
+ disableX = true;
+ disableY = true;
+ } else if (startKey === SHEET_VIEWPORT_KEY.VIEW_MAIN_TOP) {
+ disableY = true;
+ } else if (startKey === SHEET_VIEWPORT_KEY.VIEW_MAIN_LEFT) {
+ disableX = true;
+ }
+
+ if ((selection?.endRow ?? 0) > (freeze?.startRow ?? 0)) {
+ disableY = false;
+ }
+
+ if ((selection?.endColumn ?? 0) > (freeze?.startColumn ?? 0)) {
+ disableX = false;
+ }
+ if (disableX) {
+ scrollOffsetX = viewportMain.left;
+ }
+
+ if (disableY) {
+ scrollOffsetY = viewportMain.top;
+ }
+ } else {
+ const startXY = {
+ x: startViewport.scrollX,
+ y: startViewport.scrollY,
+ };
+ const endXY = {
+ x: endViewport.scrollX,
+ y: endViewport.scrollY,
+ };
+ const shouldResetX = startXY.x !== endXY.x && isCrossingX && xCrossTime % 2 === 1;
+ const shouldResetY = startXY.y !== endXY.y && isCrossingY && yCrossTime % 2 === 1;
+
+ if (shouldResetX || shouldResetY) {
+ viewportMain.scrollTo({
+ x: shouldResetX ? startXY.x : undefined,
+ y: shouldResetY ? startXY.y : undefined,
+ });
+
+ if (!shouldResetX) {
+ scrollOffsetX = viewportMain.left;
+ }
+
+ if (!shouldResetY) {
+ scrollOffsetY = viewportMain.top;
+ }
+ }
+
+ if (
+ (startKey === SHEET_VIEWPORT_KEY.VIEW_MAIN_LEFT_TOP && endKey === SHEET_VIEWPORT_KEY.VIEW_MAIN_LEFT) ||
+ (endKey === SHEET_VIEWPORT_KEY.VIEW_MAIN_LEFT_TOP && startKey === SHEET_VIEWPORT_KEY.VIEW_MAIN_LEFT)
+ ) {
+ scrollOffsetX = viewportMain.left;
+ }
+
+ if (
+ (startKey === SHEET_VIEWPORT_KEY.VIEW_MAIN_LEFT_TOP && endKey === SHEET_VIEWPORT_KEY.VIEW_MAIN_TOP) ||
+ (endKey === SHEET_VIEWPORT_KEY.VIEW_MAIN_LEFT_TOP && startKey === SHEET_VIEWPORT_KEY.VIEW_MAIN_TOP)
+ ) {
+ scrollOffsetY = viewportMain.top;
+ }
+ }
+
+ lastX = newMoveOffsetX;
+ lastY = newMoveOffsetY;
+ }
+
+ this._scrollTimer.scrolling(scrollOffsetX, scrollOffsetY, () => {
+ this._moving(newMoveOffsetX, newMoveOffsetY, activeSelectionControl, rangeType);
+ });
+ });
+ // #endregion
+ }
+
+ /** @deprecated Use the function `attachSelectionWithCoord` instead`. */
+ attachSelectionWithCoord(selectionWithStyle: ISelectionWithStyle): ISelectionWithCoordAndStyle {
+ return attachSelectionWithCoord(selectionWithStyle, this._skeleton);
+ }
+
+ /** @deprecated Use the function `attachPrimaryWithCoord` instead`. */
+ attachPrimaryWithCoord(primary: ISelectionCell): ISelectionCellWithMergeInfo {
+ return attachPrimaryWithCoord(primary, this._skeleton) as unknown as ISelectionCellWithMergeInfo;
+ }
+
+ getSelectionCellByPosition(x: number, y: number) {
+ const scene = this._scene;
+ const skeleton = this._skeleton;
+ const scrollXY = scene.getViewportScrollXY(scene.getViewport(SHEET_VIEWPORT_KEY.VIEW_MAIN)!);
+ const { scaleX, scaleY } = scene.getAncestorScale();
+
+ return skeleton.calculateCellIndexByPosition(
+ x,
+ y,
+ scaleX,
+ scaleY,
+ scrollXY
+ ) as Nullable<ISelectionCellWithMergeInfo>;
+ }
+
+ /**
+ * When mousedown and mouseup need to go to the coordination and undo stack, when mousemove does not need to go to the coordination and undo stack
+ */
+ // eslint-disable-next-line max-lines-per-function
+ protected _moving(
+ offsetX: number,
+ offsetY: number,
+ activeSelectionControl: Nullable<SelectionControl>,
+ rangeType: RANGE_TYPE
+ ) {
+ const skeleton = this._skeleton;
+ const scene = this._scene;
+
+ const currSelectionRange: IRange = {
+ startRow: activeSelectionControl?.model.startRow ?? -1,
+ endRow: activeSelectionControl?.model.endRow ?? -1,
+ startColumn: activeSelectionControl?.model.startColumn ?? -1,
+ endColumn: activeSelectionControl?.model.endColumn ?? -1,
+ };
+
+ const viewportMain = scene.getViewport(SHEET_VIEWPORT_KEY.VIEW_MAIN)!;
+
+ const targetViewport = this._getViewportByCell(currSelectionRange.endRow, currSelectionRange.endColumn) ?? viewportMain;
+
+ const scrollXY = scene.getVpScrollXYInfoByPosToVp(
+ Vector2.FromArray([this._startViewportPosX, this._startViewportPosY]),
+ targetViewport
+ );
+
+ const { scaleX, scaleY } = scene.getAncestorScale();
+
+ if (rangeType === RANGE_TYPE.ROW) {
+ offsetX = Number.POSITIVE_INFINITY;
+ } else if (rangeType === RANGE_TYPE.COLUMN) {
+ offsetY = Number.POSITIVE_INFINITY;
+ }
+
+ const cursorCellRangeInfo = this._getCellRangeByCursorPosition(offsetX, offsetY, scaleX, scaleY, scrollXY);
+ if (!cursorCellRangeInfo) {
+ return false;
+ }
+
+ const { rangeWithCoord: cursorCellRange } = cursorCellRangeInfo;
+ const activeCellRange = this._startRangeWhenPointerDown;
+
+ let newSelectionRange: IRange = {
+ startRow: Math.min(cursorCellRange.startRow, activeCellRange.startRow),
+ startColumn: Math.min(cursorCellRange.startColumn, activeCellRange.startColumn),
+ endRow: Math.max(cursorCellRange.endRow, activeCellRange.endRow),
+ endColumn: Math.max(cursorCellRange.endColumn, activeCellRange.endColumn),
+ };
+
+ if (this._shouldDetectMergedCells) {
+ newSelectionRange = skeleton.getSelectionMergeBounding(newSelectionRange.startRow, newSelectionRange.startColumn, newSelectionRange.endRow, newSelectionRange.endColumn);
+ }
+
+ if (!newSelectionRange) {
+ return false;
+ }
+
+ const startCellXY = skeleton.getNoMergeCellPositionByIndex(newSelectionRange.startRow, newSelectionRange.startColumn);
+ const endCellXY = skeleton.getNoMergeCellPositionByIndex(newSelectionRange.endRow, newSelectionRange.endColumn);
+
+ const newSelectionRangeWithCoord: IRangeWithCoord = {
+ startRow: newSelectionRange.startRow,
+ startColumn: newSelectionRange.startColumn,
+ endRow: newSelectionRange.endRow,
+ endColumn: newSelectionRange.endColumn,
+ startY: startCellXY?.startY || 0,
+ endY: endCellXY?.endY || 0,
+ startX: startCellXY?.startX || 0,
+ endX: endCellXY?.endX || 0,
+ };
+ // Only notify when the selection changes
+
+ const rangeChanged =
+ currSelectionRange.startRow !== newSelectionRange.startRow ||
+ currSelectionRange.startColumn !== newSelectionRange.startColumn ||
+ currSelectionRange.endRow !== newSelectionRange.endRow ||
+ currSelectionRange.endColumn !== newSelectionRange.endColumn;
+ if (activeSelectionControl != null && rangeChanged) {
+ // selectionControl.update(newSelectionRange, rowHeaderWidth, columnHeaderHeight);
+ this._updateSelectionControlRange(activeSelectionControl, newSelectionRangeWithCoord);
+ this._selectionMoving$.next(this.getSelectionDataWithStyle());
+ }
+ }
+
+ protected _updateSelectionControlRange(control: SelectionControl, newSelectionRange: IRangeWithCoord, highlight: Nullable<ISelectionCellWithMergeInfo>) {
+ const skeleton = this._skeleton;
+ const { rowHeaderWidth, columnHeaderHeight } = skeleton;
+ control.update(newSelectionRange, rowHeaderWidth, columnHeaderHeight, this._selectionStyle, !highlight ? null : highlight);
+ }
+
+ private _clearMove(): void {
+ this._scenePointerMoveSub?.unsubscribe();
+ this._scenePointerMoveSub = null;
+ }
+
+ protected _clearEndingListeners() {
+ const scene = this._scene;
+ scene.enableEvent();
+
+ this._clearMove();
+ this._scenePointerUpSub?.unsubscribe();
+ this._scenePointerUpSub = null;
+
+ this._scrollTimer?.dispose();
+
+ this._cancelDownSubscription?.unsubscribe();
+ this._cancelDownSubscription = null;
+ this._cancelUpSubscription?.unsubscribe();
+ this._cancelUpSubscription = null;
+ }
+
+ protected _addEndingListeners() {
+ const scene = this._scene!;
+ const mainScene = scene.getEngine()?.activeScene;
+ if (!mainScene || mainScene === scene) {
+ return;
+ }
+
+ this._cancelDownSubscription?.unsubscribe();
+ this._cancelDownSubscription = null;
+ this._cancelUpSubscription?.unsubscribe();
+ this._cancelUpSubscription = null;
+
+ this._cancelDownSubscription = mainScene.onPointerDown$.subscribeEvent(() => this._clearEndingListeners());
+ this._cancelUpSubscription = mainScene.onPointerUp$.subscribeEvent(() => this._clearEndingListeners());
+ }
+
+ protected _getCellRangeByCursorPosition(
+ offsetX: number,
+ offsetY: number,
+ scaleX: number,
+ scaleY: number,
+ scrollXY: { x: number; y: number }
+ ): Nullable<ISelectionWithCoord> {
+ if (this._shouldDetectMergedCells) {
+ const primaryWithCoord = this._skeleton?.calculateCellIndexByPosition(
+ offsetX,
+ offsetY,
+ scaleX,
+ scaleY,
+ scrollXY
+ );
+
+ if (!primaryWithCoord) return;
+
+ const rangeWithCoord = makeCellToSelection(primaryWithCoord);
+ return {
+ primaryWithCoord,
+ rangeWithCoord,
+ };
+ }
+
+ const skeleton = this._skeleton;
+
+ if (skeleton == null) {
+ return;
+ }
+
+ const moveActualSelection = skeleton.getCellPositionByOffset(offsetX, offsetY, scaleX, scaleY, scrollXY);
+
+ const { row, column } = moveActualSelection;
+
+ const startCell = skeleton.getNoMergeCellPositionByIndex(row, column);
+
+ const { startX, startY, endX, endY } = startCell;
+
+ const rangeWithCoord = {
+ startY,
+ endY,
+ startX,
+ endX,
+ startRow: row,
+ endRow: row,
+ startColumn: column,
+ endColumn: column,
+ };
+
+ const primaryWithCoord = {
+ actualRow: row,
+ actualColumn: column,
+
+ isMerged: false,
+
+ isMergedMainCell: false,
+
+ startY,
+ endY,
+ startX,
+ endX,
+
+ mergeInfo: rangeWithCoord,
+ };
+
+ return {
+ primaryWithCoord,
+ rangeWithCoord,
+ };
+ }
+
+ protected _checkClearPreviousControls(evt: IPointerEvent | IMouseEvent) {
+ const curControls = this.getSelectionControls();
+ if (curControls.length === 0) return;
+
+ // In addition to pressing the ctrl or shift key, we must clear the previous selection.
+ if (
+ (!evt.ctrlKey && !evt.shiftKey && !this._remainLastEnabled) ||
+ (this._singleSelectionEnabled && !evt.shiftKey)
+ ) {
+ this._clearSelectionControls();
+ }
+ }
+
+ private _performSelectionByTwoCells(
+ currentCell: ISelectionCellWithMergeInfo,
+ startSelectionRange: IRangeWithCoord,
+ skeleton: SpreadsheetSkeleton,
+ rangeType: RANGE_TYPE,
+ activeControl: SelectionControl
+ ): void {
+ const { actualRow, actualColumn, mergeInfo: actualMergeInfo } = currentCell;
+
+ // Get the maximum range selected based on the two cells selected with Shift key.
+ const newStartRow = Math.min(actualRow, startSelectionRange.startRow, actualMergeInfo.startRow);
+ const newEndRow = Math.max(actualRow, startSelectionRange.endRow, actualMergeInfo.endRow);
+ const newStartColumn = Math.min(actualColumn, startSelectionRange.startColumn, actualMergeInfo.startColumn);
+ const newEndColumn = Math.max(actualColumn, startSelectionRange.endColumn, actualMergeInfo.endColumn);
+
+ /**
+ * Calculate whether there are merged cells within the range. If there are, recursively expand the selection again.
+ */
+ const bounding = skeleton.getMergeBounding(newStartRow, newStartColumn, newEndRow, newEndColumn);
+
+ const startCell = skeleton.getNoMergeCellPositionByIndex(bounding.startRow, bounding.startColumn);
+
+ const endCell = skeleton.getNoMergeCellPositionByIndex(bounding.endRow, bounding.endColumn);
+
+ const newSelectionRange = {
+ startColumn: bounding.startColumn,
+ startRow: bounding.startRow,
+ endColumn: bounding.endColumn,
+ endRow: bounding.endRow,
+
+ startY: startCell.startY,
+ endY: endCell.endY,
+ startX: startCell.startX,
+ endX: endCell.endX,
+
+ rangeType,
+ };
+
+ /**
+ * When expanding the selection with the Shift key,
+ * the original highlighted cell should remain unchanged.
+ * If the highlighted cell is a merged cell, the selection needs to be expanded.
+ */
+ const activeCell = skeleton.getCellByIndex(actualRow, actualColumn);
+
+ this._startRangeWhenPointerDown = {
+ startColumn: activeCell.mergeInfo.startColumn,
+ startRow: activeCell.mergeInfo.startRow,
+ endColumn: activeCell.mergeInfo.endColumn,
+ endRow: activeCell.mergeInfo.endRow,
+ startY: activeCell.mergeInfo.startY || 0,
+ endY: activeCell.mergeInfo.endY || 0,
+ startX: activeCell.mergeInfo.startX || 0,
+ endX: activeCell.mergeInfo.endX || 0,
+ rangeType,
+ };
+ this._updateSelectionControlRange(activeControl, newSelectionRange, currentCell);
+ }
+}
+
+export function getAllSelection(skeleton: SpreadsheetSkeleton): ISelectionWithStyle {
+ return {
+ range: {
+ startRow: 0,
+ startColumn: 0,
+ endRow: skeleton.getRowCount() - 1,
+ endColumn: skeleton.getColumnCount() - 1,
+ rangeType: RANGE_TYPE.ALL,
+ },
+ primary: getTopLeftSelection(skeleton).primary,
+ style: null,
+ };
+}
+
+export function getTopLeftSelection(skeleton: SpreadsheetSkeleton) {
+ const mergeData = skeleton.mergeData;
+ return (
+ transformCellDataToSelectionData(0, 0, mergeData) || {
+ range: {
+ startRow: 0,
+ startColumn: 0,
+ endRow: 0,
+ endColumn: 0,
+ },
+ primary: {
+ actualRow: 0,
+ actualColumn: 0,
+ startRow: 0,
+ startColumn: 0,
+ endRow: 0,
+ endColumn: 0,
+ isMerged: false,
+ isMergedMainCell: false,
+ },
+ style: null,
+ }
+ );
+}
diff --git a/packages/sheets-ui/src/services/selection/const.ts b/packages/sheets-ui/src/services/selection/const.ts
new file mode 100644
index 0000000000..c6923c1304
--- /dev/null
+++ b/packages/sheets-ui/src/services/selection/const.ts
@@ -0,0 +1,21 @@
+/**
+ * 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 { createInterceptorKey } from '@univerjs/core';
+import type { Scene, SpreadsheetSkeleton } from '@univerjs/engine-render';
+
+export const RANGE_MOVE_PERMISSION_CHECK = createInterceptorKey<boolean, null>('rangeMovePermissionCheck');
+export const RANGE_FILL_PERMISSION_CHECK = createInterceptorKey<boolean, { x: number; y: number; skeleton: SpreadsheetSkeleton; scene: Scene }>('rangeFillPermissionCheck');
diff --git a/packages/sheets-ui/src/services/selection/mobile-selection-render.service.ts b/packages/sheets-ui/src/services/selection/mobile-selection-render.service.ts
index 9fc19fe0dc..bfcba57236 100644
--- a/packages/sheets-ui/src/services/selection/mobile-selection-render.service.ts
+++ b/packages/sheets-ui/src/services/selection/mobile-selection-render.service.ts
@@ -17,30 +17,35 @@
/* eslint-disable complexity */
/* eslint-disable max-lines-per-function */
import type {
+ EventState,
IRange,
IRangeWithCoord,
- ISelection,
- ISelectionCell,
ISelectionCellWithMergeInfo,
- ISelectionWithCoord,
Nullable,
+ Workbook,
} from '@univerjs/core';
-import { InterceptorManager, makeCellToSelection, RANGE_TYPE, ThemeService, UniverInstanceType } from '@univerjs/core';
-import type { IMouseEvent, IPointerEvent, Scene, SpreadsheetSkeleton, Viewport } from '@univerjs/engine-render';
+import {
+ ICommandService,
+ IContextService,
+ ILogService, RANGE_TYPE, ThemeService,
+ toDisposable,
+} from '@univerjs/core';
+import type { IMouseEvent, IPointerEvent, IRenderContext, IRenderModule, Scene, Viewport } from '@univerjs/engine-render';
import { IRenderManagerService, ScrollTimer, ScrollTimerType, SHEET_VIEWPORT_KEY, Vector2 } from '@univerjs/engine-render';
-import type { ISelectionStyle, ISelectionWithCoordAndStyle, ISelectionWithStyle } from '@univerjs/sheets';
-import { getNormalSelectionStyle } from '@univerjs/sheets';
+import type { ISelectionWithCoordAndStyle, ISetSelectionsOperationParams, WorkbookSelections } from '@univerjs/sheets';
+import { convertSelectionDataToRange, DISABLE_NORMAL_SELECTIONS, SelectionMoveType, SetSelectionsOperation, SheetsSelectionsService } from '@univerjs/sheets';
import { IShortcutService } from '@univerjs/ui';
+import type { IDisposable } from '@wendellhu/redi';
import { Inject, Injector } from '@wendellhu/redi';
-import type { Subscription } from 'rxjs';
-import { BehaviorSubject, Subject } from 'rxjs';
-
+import { distinctUntilChanged, startWith } from 'rxjs';
+import type { ISheetObjectParam } from '../../controllers/utils/component-tools';
+import { getCoordByOffset, getSheetObject } from '../../controllers/utils/component-tools';
+import { checkInHeaderRanges } from '../../controllers/utils/selections-tools';
+import { ScrollManagerService } from '../scroll-manager.service';
import { SheetSkeletonManagerService } from '../sheet-skeleton-manager.service';
-import type { SelectionRenderModel } from './selection-render-model';
-import type { SelectionControl } from './selection-shape';
-import { type IControlFillConfig, type ISelectionRenderService, RANGE_FILL_PERMISSION_CHECK, RANGE_MOVE_PERMISSION_CHECK } from './selection-render.service';
+import { BaseSelectionRenderService, getAllSelection, getTopLeftSelection } from './base-selection-render.service';
import { MobileSelectionControl } from './mobile-selection-shape';
-import { SelectionShapeExtension } from './selection-shape-extension';
+import { attachSelectionWithCoord } from './util';
enum ExpandingControl {
BOTTOM_RIGHT = 'bottom-right',
@@ -50,238 +55,337 @@ enum ExpandingControl {
TOP = 'top',
BOTTOM = 'bottom',
}
-export class MobileSelectionRenderService implements ISelectionRenderService {
- hasSelection: boolean = false;
-
- private _pointerdownSub: Nullable<Subscription>;
-
- private _mainScenePointerUpSub: Nullable<Subscription>;
-
- private _scenePointerMoveSub: Nullable<Subscription>;
-
- private _scenePointerUpSub: Nullable<Subscription>;
-
- private _controlFillConfig$: BehaviorSubject<IControlFillConfig | null> =
- new BehaviorSubject<IControlFillConfig | null>(null);
-
- readonly controlFillConfig$ = this._controlFillConfig$.asObservable();
-
- private _selectionControls: SelectionControl[] = []; // sheetID:Controls
-
- private _activeCellRangeOfCurrSelection: IRangeWithCoord = {
- startY: 0,
- endY: 0,
- startX: 0,
- endX: 0,
- startRow: -1,
- endRow: -1,
- startColumn: -1,
- endColumn: -1,
- };
-
- private _startOffsetX: number = 0;
-
- private _startOffsetY: number = 0;
-
- private _scrollTimer!: ScrollTimer;
-
- private _skeleton: Nullable<SpreadsheetSkeleton>;
-
- private _scene: Nullable<Scene>;
+export class MobileSheetsSelectionRenderService extends BaseSelectionRenderService implements IRenderModule {
+ private readonly _workbookSelections: WorkbookSelections;
+ private _renderDisposable: Nullable<IDisposable> = null;
- // The type of selector determines the type of data range and the highlighting style of the title bar
- private _isHeaderHighlight: boolean = true;
+ _expandingSelection: boolean = false;
- // If true, the selector will respond to the range of merged cells and automatically extend the selected range. If false, it will ignore the merged cells.
- private _isDetectMergedCell: boolean = true;
+ protected override _selectionControls: MobileSelectionControl[] = []; // sheetID:Controls
- // The style of the selection area, including dashed lines, color, thickness, autofill, other points for modifying the range of the selection area, title highlighting, and so on, can all be customized.
- private _selectionStyle!: ISelectionStyle;
+ expandingControlMode: ExpandingControl = ExpandingControl.BOTTOM_RIGHT;
- // Whether to enable the selection area. If set to false, the user cannot draw a selection area in the content area by clicking with the mouse.
- private _isSelectionEnabled: boolean = true;
+ constructor(
+ private readonly _context: IRenderContext<Workbook>,
+ @Inject(Injector) injector: Injector,
+ @Inject(ThemeService) themeService: ThemeService,
+ @IShortcutService shortcutService: IShortcutService,
+ @IRenderManagerService renderManagerService: IRenderManagerService,
+ @Inject(SheetsSelectionsService) selectionManagerService: SheetsSelectionsService,
+ @ILogService private readonly _logService: ILogService,
+ @ICommandService private readonly _commandService: ICommandService,
+ @IContextService private readonly _contextService: IContextService,
+ @Inject(SheetSkeletonManagerService) private readonly _sheetSkeletonManagerService: SheetSkeletonManagerService,
+ @Inject(ScrollManagerService) private readonly _scrollManagerService: ScrollManagerService
+ ) {
+ super(
+ injector,
+ themeService,
+ shortcutService,
+ renderManagerService
+ );
+ this._workbookSelections = selectionManagerService.getWorkbookSelections(this._context.unitId);
+ this._init();
+ }
- // Used in the format painter feature, similar to ctrl, it can retain the previous selection.
- private _isShowPreviousEnable: boolean | number = 0;
+ private _init() {
+ const sheetObject = this._getSheetObject();
- //Used in the formula selection feature, a new selection string is added by drawing a box with the mouse.
- private _isRemainLastEnable: boolean = true;
+ this._initEventListeners(sheetObject);
+ this._initSelectionChangeListener();
+ // this._initThemeChangeListener();
+ this._initSkeletonChangeListener();
+ this._initUserActionSyncListener();
+ this._updateControlPointWhenScrolling();
+ }
- private _isSkipRemainLastEnable: boolean = false;
+ private _initSkeletonChangeListener() {
+ this.disposeWithMe(this._sheetSkeletonManagerService.currentSkeleton$.subscribe((param) => {
+ if (param == null) {
+ this._logService.error('[SelectionRenderService]: should not receive null!');
+ return;
+ }
- private _isSingleSelection: boolean = false; // Multiple selections are prohibited
+ const unitId = this._context.unitId;
+ const { sheetId, skeleton } = param;
+ const { scene } = this._context;
+ const viewportMain = scene.getViewport(SHEET_VIEWPORT_KEY.VIEW_MAIN);
+ this._changeRuntime(skeleton, scene, viewportMain);
+
+ // If there is no initial selection, add one by default in the top left corner.
+ const firstSelection = this._workbookSelections.getCurrentLastSelection();
+ if (!firstSelection) {
+ this._commandService.syncExecuteCommand(SetSelectionsOperation.id, {
+ unitId,
+ subUnitId: sheetId,
+ selections: [getTopLeftSelection(skeleton)],
+ } as ISetSelectionsOperationParams);
+ }
+ }));
+ }
- private readonly _selectionMoveEnd$ = new BehaviorSubject<ISelectionWithCoordAndStyle[]>([]);
+ private _initSelectionChangeListener() {
+ // When selection completes, we need to update the selections' rendering and clear event handlers.
+ this.disposeWithMe(this._workbookSelections.selectionMoveEnd$.subscribe((params) => {
+ this._reset();
+ for (const selectionWithStyle of params) {
+ const selectionData = attachSelectionWithCoord(selectionWithStyle, this._skeleton);
+ this._addSelectionControlBySelectionData(selectionData);
+ }
+ }));
+ }
- // When the user draws a selection area in the canvas content area, this event is broadcasted when the drawing ends.
- readonly selectionMoveEnd$ = this._selectionMoveEnd$.asObservable();
+ private _initEventListeners(sheetObject: ISheetObjectParam): void {
+ const { spreadsheetRowHeader, spreadsheetColumnHeader, spreadsheet, spreadsheetLeftTopPlaceholder } = sheetObject;
+ const { scene } = this._context;
+ this._initSpreadsheetEvent(sheetObject);
- private readonly _selectionMoving$ = new Subject<ISelectionWithCoordAndStyle[]>();
+ this.disposeWithMe(
+ spreadsheetRowHeader?.onPointerUp$.subscribeEvent((evt: IPointerEvent | IMouseEvent, _state: EventState) => {
+ if (this._normalSelectionDisabled()) return;
- /**
- * Triggered during the drawing of the selection area.
- */
- readonly selectionMoving$ = this._selectionMoving$.asObservable();
+ const skeleton = this._sheetSkeletonManagerService.getCurrent()!.skeleton;
+ const { row } = getCoordByOffset(evt.offsetX, evt.offsetY, scene, skeleton);
+ const matchSelectionData = checkInHeaderRanges(this._workbookSelections.getCurrentSelections(), row, RANGE_TYPE.ROW);
+ if (matchSelectionData) return;
- private readonly _selectionMoveStart$ = new Subject<ISelectionWithCoordAndStyle[]>();
+ this.createNewSelection(evt, (spreadsheet.zIndex || 1) + 1, RANGE_TYPE.ROW, this._getActiveViewport(evt));
+ this._selectionMoveEnd$.next(this.getSelectionDataWithStyle());
+ })
+ );
- /**
- * Triggered during the start draw the selection area.
- */
- readonly selectionMoveStart$ = this._selectionMoveStart$.asObservable();
+ this.disposeWithMe(
+ spreadsheetColumnHeader?.onPointerUp$.subscribeEvent((evt: IPointerEvent | IMouseEvent, _state: EventState) => {
+ if (this._normalSelectionDisabled()) return;
+
+ const skeleton = this._sheetSkeletonManagerService.getCurrent()!.skeleton;
+ const { column } = getCoordByOffset(evt.offsetX, evt.offsetY, scene, skeleton);
+ const matchSelectionData = checkInHeaderRanges(this._workbookSelections.getCurrentSelections(), column, RANGE_TYPE.COLUMN);
+ if (matchSelectionData) return;
+ this.createNewSelection(evt, (spreadsheet.zIndex || 1) + 1, RANGE_TYPE.COLUMN, this._getActiveViewport(evt));
+ this._selectionMoveEnd$.next(this.getSelectionDataWithStyle());
+ })
+ );
- private _activeViewport: Nullable<Viewport>;
+ // do not use onPointerDown$, pointerDown would close popup
+ // see packages/ui/src/views/components/context-menu/ContextMenu.tsx
+ this.disposeWithMe(spreadsheetLeftTopPlaceholder?.onPointerUp$.subscribeEvent((_evt: IPointerEvent | IMouseEvent, state: EventState) => {
+ if (this._normalSelectionDisabled()) return;
- /**
- * This service relies on the scene and skeleton to work
- * Use usable$ to check if this service works
- */
- private readonly _usable$ = new BehaviorSubject<boolean>(false);
+ this._reset(); // remove all other selections
- readonly usable$ = this._usable$.asObservable();
- public interceptor = new InterceptorManager({ RANGE_MOVE_PERMISSION_CHECK, RANGE_FILL_PERMISSION_CHECK });
- expandingControlMode: ExpandingControl = ExpandingControl.BOTTOM_RIGHT;
+ const skeleton = this._sheetSkeletonManagerService.getCurrent()!.skeleton;
+ const selectionWithStyle = getAllSelection(skeleton);
+ const selectionData = attachSelectionWithCoord(selectionWithStyle, skeleton);
+ this._addSelectionControlBySelectionData(selectionData);
+ this.refreshSelectionMoveStart();
- constructor(
- @Inject(ThemeService) private readonly _themeService: ThemeService,
- @IShortcutService private readonly _shortcutService: IShortcutService,
- @IRenderManagerService private readonly _renderManagerService: IRenderManagerService,
- @Inject(Injector) private readonly _injector: Injector
- ) {
- this._selectionStyle = getNormalSelectionStyle(this._themeService);
+ state.stopPropagation();
+ this._selectionMoveEnd$.next(this.getSelectionDataWithStyle());
+ }));
}
- enableHeaderHighlight() {
- this._isHeaderHighlight = true;
- }
+ private _initSpreadsheetEvent(sheetObject: ISheetObjectParam): void {
+ const { spreadsheet } = sheetObject;
+ let longPressTimer: ReturnType<typeof setTimeout>;
+ const longPressDuration = 500; // Longpress duration in milliseconds
+ const pointerDownPos = { x: 0, y: 0 };
- disableHeaderHighlight() {
- this._isHeaderHighlight = false;
- }
+ const clearLongPressTimer = () => {
+ // Clear the timer if pointer is moved or released
+ clearTimeout(longPressTimer);
+ };
- enableDetectMergedCell() {
- this._isDetectMergedCell = true;
- }
+ const createNewSelection = (evt: IPointerEvent | IMouseEvent, showContextMenu: boolean) => {
+ // TODO @lumixraku
+ this.createNewSelection(
+ evt,
+ spreadsheet.zIndex + 1,
+ RANGE_TYPE.NORMAL,
+ this._getActiveViewport(evt)
+ );
- disableDetectMergedCell() {
- this._isDetectMergedCell = false;
- }
+ // show contextmenu when longpress and change selection area
+ // do not show contextmenu when click a cell
+ if (showContextMenu) {
+ this._selectionMoveEnd$.next(this.getSelectionDataWithStyle());
+ }
+ };
+ spreadsheet?.onPointerMove$.subscribeEvent((evt: IPointerEvent | IMouseEvent, _state) => {
+ const edge = 10;
+ if (Math.abs(evt.offsetX - pointerDownPos.x) > edge ||
+ Math.abs(evt.offsetY - pointerDownPos.y) > edge) {
+ clearLongPressTimer();
+ }
+ });
+ const spreadsheetPointerDownSub = spreadsheet?.onPointerDown$.subscribeEvent((evt: IPointerEvent | IMouseEvent, state) => {
+ pointerDownPos.x = evt.offsetX;
+ pointerDownPos.y = evt.offsetY;
+ longPressTimer = setTimeout(() => {
+ createNewSelection(evt, true);
+ }, longPressDuration);
+
+ state.stopPropagation();
+ });
+ const spreadsheetPointerUpSub = spreadsheet?.onPointerUp$.subscribeEvent((evt: IPointerEvent | IMouseEvent, state) => {
+ if (this._normalSelectionDisabled()) return;
- setStyle(style: ISelectionStyle) {
- this._selectionStyle = style;
- }
+ clearTimeout(longPressTimer);
+ const edge = 10;
+ if (Math.abs(evt.offsetX - pointerDownPos.x) > edge ||
+ Math.abs(evt.offsetY - pointerDownPos.y) > edge) {
+ return;
+ }
+ createNewSelection(evt, false);
+ state.stopPropagation();
+ });
- resetStyle() {
- this.setStyle(getNormalSelectionStyle(this._themeService));
+ this.disposeWithMe(toDisposable(spreadsheetPointerDownSub));
+ this.disposeWithMe(toDisposable(spreadsheetPointerUpSub));
}
- enableSelection() {
- this._isSelectionEnabled = true;
- }
+ private _initUserActionSyncListener() {
+ this.disposeWithMe(this.selectionMoveStart$.subscribe((params) => this._updateSelections(params, SelectionMoveType.MOVE_START)));
+ this.disposeWithMe(this.selectionMoving$.subscribe((params) => this._updateSelections(params, SelectionMoveType.MOVING)));
- disableSelection() {
- this._isSelectionEnabled = false;
+ this.disposeWithMe(this._contextService.subscribeContextValue$(DISABLE_NORMAL_SELECTIONS)
+ .pipe(startWith(false), distinctUntilChanged())
+ .subscribe((disabled) => {
+ if (disabled) {
+ this._renderDisposable?.dispose();
+ this._renderDisposable = null;
+ this._reset();
+ } else {
+ this._renderDisposable = toDisposable(
+ this.selectionMoveEnd$.subscribe((params) => this._updateSelections(params, SelectionMoveType.MOVE_END))
+ );
+ }
+ }));
}
- enableShowPrevious() {
- this._isShowPreviousEnable = true;
- }
+ private _updateSelections(selectionDataWithStyleList: ISelectionWithCoordAndStyle[], type: SelectionMoveType) {
+ const workbook = this._context.unit;
+ const unitId = workbook.getUnitId();
+ const sheetId = workbook.getActiveSheet().getSheetId();
- disableShowPrevious() {
- this._isShowPreviousEnable = false;
- }
+ if (selectionDataWithStyleList.length === 0) {
+ return;
+ }
- enableRemainLast() {
- this._isRemainLastEnable = true;
+ this._commandService.executeCommand(SetSelectionsOperation.id, {
+ unitId,
+ subUnitId: sheetId,
+ type,
+ selections: selectionDataWithStyleList.map((selectionDataWithStyle) =>
+ convertSelectionDataToRange(selectionDataWithStyle)
+ ),
+ });
}
- disableRemainLast() {
- this._isRemainLastEnable = false;
- }
+ /**
+ * invoked when pointerup or longpress on spreadsheet, or pointerdown on row&col
+ * then move curr selection to cell at cursor
+ * Main perpose to create a new selection, or update curr selection to a new range.
+ * @param evt
+ * @param _zIndex
+ * @param rangeType
+ * @param viewport
+ */
+ createNewSelection(
+ evt: IPointerEvent | IMouseEvent,
+ _zIndex = 0,
+ rangeType: RANGE_TYPE = RANGE_TYPE.NORMAL,
+ viewport?: Viewport
+ ) {
+ this._shouldDetectMergedCells = rangeType === RANGE_TYPE.NORMAL;
- enableSkipRemainLast() {
- this._isSkipRemainLastEnable = true;
- }
+ const skeleton = this._skeleton;
+ const scene = this._scene;
+ if (!scene || !skeleton) {
+ return;
+ }
- disableSkipRemainLast() {
- this._isSkipRemainLastEnable = false;
- }
+ if (viewport) {
+ this._activeViewport = viewport;
+ }
- enableSingleSelection() {
- this._isSingleSelection = true;
- }
+ const { offsetX: evtOffsetX, offsetY: evtOffsetY } = evt;
+ const relativeCoords = scene.getRelativeToViewportCoord(Vector2.FromArray([evtOffsetX, evtOffsetY]));
- disableSingleSelection() {
- this._isSingleSelection = false;
- }
+ let { x: viewportPosX, y: viewportPosY } = relativeCoords;
+ // this._startViewportPosX = viewportPosX;
+ // this._startViewportPosY = viewportPosY;
+ const scrollXY = scene.getVpScrollXYInfoByPosToVp(relativeCoords);
+ const { scaleX, scaleY } = scene.getAncestorScale();
+ const cursorCellRangeInfo = this._getCellRangeByCursorPosition(viewportPosX, viewportPosY, scaleX, scaleY, scrollXY);
+ if (!cursorCellRangeInfo) return false;
- getViewPort() {
- return this._activeViewport!;
- }
+ const { rangeWithCoord: cursorCellRange, primaryWithCoord: primaryCursorCellRange } = cursorCellRangeInfo;
+ const cursorCellRangeWithRangeType = { ...cursorCellRange, rangeType };
+ this._startRangeWhenPointerDown = { ...cursorCellRange, rangeType };
- /**
- * add a selection
- *
- * in PC:init & pointerup would call this function.
- *
- * init
- * selectionController@_initSkeletonChangeListener --> selectionManagerService.add --> selectionManagerService._selectionMoveEnd$ --> this.addControlToCurrentByRangeData
- *
- * selectionMoveEnd$ --> this.addSelectionControlBySelectionData
- *
- *
- *
- * pointer
- * engine@_pointerDownEvent --> spreadsheet?.onPointerDownObserve --> eventTrigger --> scene@disableEvent() --> then scene.input-manager currentObject is always scene until scene@enableEvent.
- * engine@_pointerUpEvent --> scene.input-manager@_onPointerUp --> this._selectionMoveEnd$ --> _selectionManagerService.selectionMoveEnd$ --> this.addControlToCurrentByRangeData
- *
- * but in mobile, we do not call disableEvent() in eventTrigger,
- * so pointerup --> scene.input-manager currentObject is spreadsheet --> this.eventTrigger
- *
- *
- *
- * @param selectionData
- */
- addSelectionControlBySelectionData(selectionData: ISelectionWithCoordAndStyle) {
- // const selectionControls = this.getSelectionControls();
-
- // if (!selectionControls) {
- // return;
- // }
- const { rangeWithCoord, primaryWithCoord } = selectionData;
- const { rangeType } = rangeWithCoord;
- const skeleton = this._skeleton;
+ let activeSelectionControl = this.getActiveSelectionControl<MobileSelectionControl>();
- let { style } = selectionData;
+ for (const control of this.getSelectionControls()) {
+ // in curr selection
+ // if (control.model.isInclude(cursorCellRangeWithRangeType)) {
+ // activeSelectionControl = control;
+ // return;
+ // }
+ // Click to an existing selection
+ if (control.model.isEqual(cursorCellRangeWithRangeType)) {
+ activeSelectionControl = control;
+ break;
+ }
- if (style == null) {
- style = getNormalSelectionStyle(this._themeService);
+ // There can only be one highlighted cell, so clear the highlighted cell of the existing selection
+ // if (!expandingMode) {
+ // control.clearHighlight();
+ // }
}
- const scene = this._scene;
+ // In addition to pressing the ctrl or shift key, we must clear the previous selection
+ // this._checkClearPreviousControls(evt);
- if (scene == null || skeleton == null) {
- return;
+ // TODO merge to _checkClearPreviousControls
+ if (activeSelectionControl?.model.rangeType !== rangeType) {
+ this._clearSelectionControls();
+ activeSelectionControl = this.newSelectionControl(scene, rangeType);
}
- const control = this.newSelectionControl(scene, rangeType || RANGE_TYPE.NORMAL);
- // eslint-disable-next-line no-new
- new SelectionShapeExtension(control, skeleton, scene, this._themeService, this._injector);
+ this._updateSelectionControlRange(
+ activeSelectionControl,
+ cursorCellRangeWithRangeType,
+ primaryCursorCellRange
+ );
- const { rowHeaderWidth, columnHeaderHeight } = skeleton;
+ this._selectionMoveStart$.next(this.getSelectionDataWithStyle());
+ this._clearEndingListeners();
+ // this._addEndingListeners();
+ this._expandingSelection = false;
- // update control
- control.update(rangeWithCoord, rowHeaderWidth, columnHeaderHeight, style, primaryWithCoord);
+ // this function call is exist in prev version
+ if (rangeType === RANGE_TYPE.ROW || rangeType === RANGE_TYPE.COLUMN) {
+ if (rangeType === RANGE_TYPE.ROW) {
+ viewportPosX = 0;
+ } else if (rangeType === RANGE_TYPE.COLUMN) {
+ viewportPosY = 0;
+ }
- const viewportMain = scene.getViewport(SHEET_VIEWPORT_KEY.VIEW_MAIN);
- if (!viewportMain) return;
- const { viewportScrollX, viewportScrollY } = viewportMain;
- const selectionEndY = rangeWithCoord.endY;
- const selectionEndX = rangeWithCoord.endX;
- control.transformControlPoint(viewportScrollX, viewportScrollY, selectionEndX, selectionEndY);
+ // _moving would update activeSelectionControl range when row & col
+ // this update logic should split from _moving!!!
+ this._moving(viewportPosX, viewportPosY, activeSelectionControl, rangeType);
+ }
}
- newSelectionControl(scene: Scene, rangeType: RANGE_TYPE) {
+ /**
+ * Not same as PC version,
+ * new selection control for mobile do one more thing: bind event for two control points.
+ * @param scene
+ * @param rangeType
+ * @returns
+ */
+ override newSelectionControl(scene: Scene, rangeType: RANGE_TYPE) {
const selectionControls = this.getSelectionControls();
const control = new MobileSelectionControl(scene, selectionControls.length, this._isHeaderHighlight, this._themeService, rangeType);
@@ -318,7 +422,7 @@ export class MobileSelectionRenderService implements ISelectionRenderService {
})();
control.fillControlTopLeft!.onPointerDown$.subscribeEvent((evt: IPointerEvent | IMouseEvent) => {
- this.expandingSelection = true;
+ this._expandingSelection = true;
this.expandingControlMode = expandingModeForTopLeft;
this._selectionMoveStart$.next(this.getSelectionDataWithStyle());
this._fillControlPointerDownHandler(
@@ -328,7 +432,7 @@ export class MobileSelectionRenderService implements ISelectionRenderService {
);
});
control.fillControlBottomRight!.onPointerDown$.subscribeEvent((evt: IPointerEvent | IMouseEvent) => {
- this.expandingSelection = true;
+ this._expandingSelection = true;
this.expandingControlMode = expandingModeForBottomRight;
this._selectionMoveStart$.next(this.getSelectionDataWithStyle());
this._fillControlPointerDownHandler(
@@ -340,668 +444,74 @@ export class MobileSelectionRenderService implements ISelectionRenderService {
if (rangeType === RANGE_TYPE.ROW || rangeType === RANGE_TYPE.COLUMN) {
const viewportMain = scene.getViewport(SHEET_VIEWPORT_KEY.VIEW_MAIN);
if (!viewportMain) return control;
-
- // const skeleton = this._sheetSkeletonManagerService.getCurrent()?.skeleton;
- // const sheetContentHeight = skeleton?.rowTotalHeight;
- // const sheetContentWidth = skeleton?.columnTotalWidth;
-
- // const scrollX = viewportMain.viewportScrollX;
- // const scrollY = viewportMain.viewportScrollY;
-
- // control.transformControlPoint(scrollX, scrollY, sheetContentWidth, sheetContentHeight);
}
return control;
}
- // in dev branch
- updateControlForCurrentByRangeData(selections: ISelectionWithCoordAndStyle[]) {
- const currentControls = this.getSelectionControls();
- if (!currentControls) {
- return;
- }
-
- const skeleton = this._skeleton;
-
- if (skeleton == null) {
- return;
- }
-
- const { rowHeaderWidth, columnHeaderHeight } = skeleton;
-
- for (let i = 0, len = selections.length; i < len; i++) {
- const { rangeWithCoord, primaryWithCoord, style } = selections[i];
-
- const control = currentControls[i];
-
- control.update(rangeWithCoord, rowHeaderWidth, columnHeaderHeight, style, primaryWithCoord);
- }
- }
-
- refreshSelectionMoveStart() {
- this._selectionMoveStart$.next(this.getSelectionDataWithStyle());
+ // same as PC
+ private _getActiveViewport(evt: IPointerEvent | IMouseEvent) {
+ const sheetObject = this._getSheetObject();
+ return sheetObject?.scene.getActiveViewportByCoord(Vector2.FromArray([evt.offsetX, evt.offsetY]));
}
- changeRuntime(skeleton: Nullable<SpreadsheetSkeleton>, scene: Nullable<Scene>, viewport?: Viewport) {
- this._skeleton = skeleton;
- this._scene = scene;
- this._activeViewport = viewport || scene?.getViewports()[0];
- this._usable$.next(Boolean(skeleton && scene));
+ // same as PC
+ private _getSheetObject() {
+ return getSheetObject(this._context.unit, this._context)!;
}
- getSelectionDataWithStyle(): ISelectionWithCoordAndStyle[] {
- const selectionControls = this._selectionControls;
- return selectionControls.map((control) => control.getValue());
+ // same as PC
+ private _normalSelectionDisabled(): boolean {
+ return this._contextService.getContextValue(DISABLE_NORMAL_SELECTIONS);
}
- getSelectionControls() {
+ override getSelectionControls() {
return this._selectionControls;
}
- private _clearSelectionControls() {
- const allSelectionControls = this.getSelectionControls();
- for (const control of allSelectionControls) {
- control.dispose();
- }
-
- allSelectionControls.length = 0; // clear currentSelectionControls
- }
-
- private _getFreeze() {
- const freeze = this._renderManagerService.withCurrentTypeOfUnit(UniverInstanceType.UNIVER_SHEET, SheetSkeletonManagerService)
- ?.getCurrent()?.skeleton.getWorksheetConfig().freeze;
- return freeze;
- }
-
- private _getViewportByCell(row?: number, column?: number) {
- if (!this._scene || row === undefined || column === undefined) {
- return null;
- }
- const freeze = this._getFreeze();
- if (!freeze || (freeze.startRow <= 0 && freeze.startColumn <= 0)) {
- return this._scene.getViewport(SHEET_VIEWPORT_KEY.VIEW_MAIN);
- }
-
- if (row > freeze.startRow && column > freeze.startColumn) {
- return this._scene.getViewport(SHEET_VIEWPORT_KEY.VIEW_MAIN);
- }
-
- if (row <= freeze.startRow && column <= freeze.startColumn) {
- return this._scene.getViewport(SHEET_VIEWPORT_KEY.VIEW_MAIN_LEFT_TOP);
- }
-
- if (row <= freeze.startRow && column > freeze.startColumn) {
- return this._scene.getViewport(SHEET_VIEWPORT_KEY.VIEW_MAIN_TOP);
- }
-
- if (row > freeze.startRow && column <= freeze.startColumn) {
- return this._scene.getViewport(SHEET_VIEWPORT_KEY.VIEW_MAIN_LEFT);
- }
- }
-
- /**
- * Returns the list of active ranges in the active sheet or null if there are no active ranges.
- * If there is a single range selected, this method behaves like a getActiveRange() call.
- */
- getActiveSelections(): Nullable<ISelection[]> {
- const controls = this.getSelectionControls();
- if (controls && controls.length > 0) {
- const selections = controls?.map((control: SelectionControl) => {
- const model: SelectionRenderModel = control.model;
- const currentCell = model.currentCell;
- let primary: Nullable<ISelectionCell> = null;
- if (currentCell) {
- primary = {
- actualRow: currentCell.actualRow,
- actualColumn: currentCell.actualColumn,
- isMerged: currentCell.isMerged,
- isMergedMainCell: currentCell.isMergedMainCell,
- startRow: currentCell.mergeInfo.startRow,
- startColumn: currentCell.mergeInfo.startColumn,
- endRow: currentCell.mergeInfo.endRow,
- endColumn: currentCell.mergeInfo.endColumn,
- };
- }
- return {
- range: {
- startRow: model.startRow,
- startColumn: model.startColumn,
- endRow: model.endRow,
- endColumn: model.endColumn,
- },
- primary,
- };
- });
- return selections;
- }
- }
-
- /**
- * Returns the selected range in the active sheet, or null if there is no active range. If multiple ranges are selected this method returns only the last selected range.
- */
- getActiveRange(): Nullable<IRange> {
- const control = this.getActiveSelectionControl();
- const model = control?.model;
- return (
- model && {
- startRow: model.startRow,
- startColumn: model.startColumn,
- endRow: model.endRow,
- endColumn: model.endColumn,
- }
- );
- }
-
- /**
- * get last selection control
- */
- getActiveSelectionControl(): Nullable<SelectionControl> {
- const controls = this.getSelectionControls();
- return controls && controls[controls.length - 1];
- }
-
- endSelection() {
- this._endSelection();
- this._selectionMoveEnd$.next(this.getSelectionDataWithStyle());
-
- // when selection mouse up, enable the short cut service
- this._shortcutService.setDisable(false);
- }
-
- reset() {
- this._clearSelectionControls();
-
- this._scenePointerMoveSub?.unsubscribe();
- this._scenePointerUpSub?.unsubscribe();
-
- this._scenePointerMoveSub = null;
- this._scenePointerUpSub = null;
- }
-
- resetAndEndSelection() {
- this.endSelection();
- this.reset();
- }
-
- expandingSelection: boolean = false;
-
- /**
- * invoked when pointerup or longpress on spreadsheet, or pointerdown on row&col
- * then move curr selection to cell at cursor
- * Main perpose to create a new selection, or update curr selection to a new range.
- * @param evt
- * @param _zIndex
- * @param rangeType
- * @param viewport
- */
- eventTrigger(
- evt: IPointerEvent | IMouseEvent,
- _zIndex = 0,
- rangeType: RANGE_TYPE = RANGE_TYPE.NORMAL,
- viewport?: Viewport
- ) {
- if (this._isSelectionEnabled === false) {
- return;
- }
-
- const skeleton = this._skeleton;
-
- const { offsetX: evtOffsetX, offsetY: evtOffsetY } = evt;
-
- const scene = this._scene;
-
- if (scene == null || skeleton == null) {
- return;
- }
-
- if (viewport != null) {
- this._activeViewport = viewport;
- }
-
- // const viewportMain = scene.getViewport(SHEET_VIEWPORT_KEY.VIEW_MAIN);
- const relativeCoords = scene.getRelativeCoord(Vector2.FromArray([evtOffsetX, evtOffsetY]));
-
- let { x: newEvtOffsetX, y: newEvtOffsetY } = relativeCoords;
-
- this._startOffsetX = newEvtOffsetX;
- this._startOffsetY = newEvtOffsetY;
-
- const scrollXY = scene.getScrollXYByRelativeCoords(relativeCoords);
-
- const { scaleX, scaleY } = scene.getAncestorScale();
-
- if (rangeType === RANGE_TYPE.ROW) {
- newEvtOffsetX = 0;
- } else if (rangeType === RANGE_TYPE.COLUMN) {
- newEvtOffsetY = 0;
- }
-
- const cursorCellRangeInfo = this._getCellRangeByCursorPosition(newEvtOffsetX, newEvtOffsetY, scaleX, scaleY, scrollXY);
-
- if (!cursorCellRangeInfo) {
- return false;
- }
-
- const { rangeWithCoord: cursorCellRange, primaryWithCoord: primaryCursorCellRange } = cursorCellRangeInfo;
-
- // const { startRow, startColumn, endColumn, endRow, startY, endY, startX, endX } = cursorCellRange;
-
- const { rowHeaderWidth, columnHeaderHeight } = skeleton;
-
- const cursorCellRangeWithRangeType = this._activeCellRangeOfCurrSelection = { ...cursorCellRange, rangeType };
-
- // let selectionControl: Nullable<SelectionShape> = this.getActiveSelection();
- let activeSelectionControl: Nullable<SelectionControl> = this.getActiveSelectionControl();
-
- const curControls = this.getSelectionControls();
- const expandingMode = this.expandingSelection || evt.shiftKey;
-
- if (!curControls) {
- return false;
- }
-
- for (const control of curControls) {
- // right click
- if (evt.button === 2 && control.model.isInclude(cursorCellRangeWithRangeType)) {
- activeSelectionControl = control;
- return;
- }
- // Click to an existing selection
- if (control.model.isEqual(cursorCellRangeWithRangeType)) {
- activeSelectionControl = control;
- break;
- }
-
- // There can only be one highlighted cell, so clear the highlighted cell of the existing selection
- if (!expandingMode) {
- control.clearHighlight();
- }
- }
-
- // In addition to pressing the ctrl or shift key, we must clear the previous selection
- if (curControls.length > 0 && !expandingMode) {
- const remainPrev = !evt.ctrlKey &&
- !this._isShowPreviousEnable &&
- !this._isRemainLastEnable;
- const isSingle = this._isSingleSelection;
-
- if (remainPrev || isSingle) {
- this._clearSelectionControls();
- }
- }
-
- if (activeSelectionControl?.model.rangeType !== rangeType) {
- this._clearSelectionControls();
- activeSelectionControl = this.newSelectionControl(scene, rangeType);
- }
-
- // const activeCellOfCurrSelection = activeSelectionControl && activeSelectionControl.model.currentCell;
-
- if (
- activeSelectionControl &&
- this._isRemainLastEnable &&
- !evt.ctrlKey &&
- !expandingMode &&
- !this._isSkipRemainLastEnable &&
- !this._isSingleSelection
- ) {
- /**
- * Supports the formula ref text selection feature,
- * under the condition of preserving all previous selections, it modifies the position of the latest selection.
- */
- // console.log('selectionControl', startSelectionRange);
-
- this._selectionMoveStart$.next(this.getSelectionDataWithStyle());
-
- // eslint-disable-next-line no-new
- new SelectionShapeExtension(activeSelectionControl, skeleton, scene, this._themeService, this._injector);
-
- activeSelectionControl.update(
- cursorCellRangeWithRangeType,
- rowHeaderWidth,
- columnHeaderHeight,
- this._selectionStyle,
- primaryCursorCellRange
- );
- }
-
- this._selectionMoveStart$.next(this.getSelectionDataWithStyle()); // old function call
- this.hasSelection = true;
- this._endSelection();
- this.expandingSelection = false;
-
- // old function call
- if (rangeType === RANGE_TYPE.ROW || rangeType === RANGE_TYPE.COLUMN) {
- // _movingHandler would update activeSelectionControl range
- // this update logic should split from _movingHandler!!!
- this._movingHandler(newEvtOffsetX, newEvtOffsetY, activeSelectionControl, rangeType);
- }
- }
-
- /**
- *
- * @param evt component point event
- * @param style selection style, Styles for user-customized selectors
- * @param zIndex Stacking order of the selection object
- * @param rangeType Determines whether the selection is made normally according to the range or by rows and columns
- *
- * invoked by selection.render-controller@pointerDownObserver
- *
- * derived from eventTrigger
- */
private _fillControlPointerDownHandler(
evt: IPointerEvent | IMouseEvent,
rangeType: RANGE_TYPE = RANGE_TYPE.NORMAL,
viewport?: Viewport,
scrollTimerType: ScrollTimerType = ScrollTimerType.ALL
) {
- if (this._isSelectionEnabled === false) {
- return;
- }
-
const skeleton = this._skeleton;
-
- const { offsetX: evtOffsetX, offsetY: evtOffsetY } = evt;
-
const scene = this._scene;
-
- if (scene == null || skeleton == null) {
+ if (!scene || !skeleton) {
return;
}
- if (viewport != null) {
+ if (viewport) {
this._activeViewport = viewport;
}
const viewportMain = scene.getViewport(SHEET_VIEWPORT_KEY.VIEW_MAIN);
- const relativeCoords = scene.getRelativeCoord(Vector2.FromArray([evtOffsetX, evtOffsetY]));
-
- let { x: newEvtOffsetX, y: newEvtOffsetY } = relativeCoords;
-
- this._startOffsetX = newEvtOffsetX;
- this._startOffsetY = newEvtOffsetY;
-
- const scrollXY = scene.getScrollXYByRelativeCoords(relativeCoords);
-
- const { scaleX, scaleY } = scene.getAncestorScale();
- if (rangeType === RANGE_TYPE.ROW) {
- newEvtOffsetX = 0;
- } else if (rangeType === RANGE_TYPE.COLUMN) {
- newEvtOffsetY = 0;
- }
-
- const cursorCellRangeInfo = this._getCellRangeByCursorPosition(newEvtOffsetX, newEvtOffsetY, scaleX, scaleY, scrollXY);
-
- if (!cursorCellRangeInfo) {
- return false;
- }
-
- // rangeByCursor: cursor active cell selection range (range may more than one cell if cursor is at a merged cell)
- // primaryCellRangeByCursor: the primary cell of range (only one cell)
- const { rangeWithCoord: cursorCellRange, primaryWithCoord: _primaryCursorCellRange } = cursorCellRangeInfo;
-
- // const { rowHeaderWidth, columnHeaderHeight } = skeleton;
-
- const cursorCellRangeWithRangeType = this._activeCellRangeOfCurrSelection = { ...cursorCellRange, rangeType };
-
- let activeSelectionControl: Nullable<SelectionControl> = this.getActiveSelectionControl();
-
- const selectionControls = this.getSelectionControls();
- const expandingMode = this.expandingSelection || evt.shiftKey;
+ const activeSelectionControl = this.getActiveSelectionControl<MobileSelectionControl>();
- if (!selectionControls) {
- return false;
- }
-
- for (const control of selectionControls) {
- // right click
- if (evt.button === 2 && control.model.isInclude(cursorCellRangeWithRangeType)) {
- activeSelectionControl = control;
- return;
- }
- // Click to an existing selection
- if (control.model.isEqual(cursorCellRangeWithRangeType)) {
- activeSelectionControl = control;
- break;
- }
-
- // There can only be one highlighted cell, so clear the highlighted cell of the existing selection
- if (!expandingMode) {
- control.clearHighlight();
- }
- }
-
- // In addition to pressing the ctrl or shift key, we must clear the previous selection
- if (selectionControls.length > 0) {
- const remainPrev = !evt.ctrlKey &&
- !this._isShowPreviousEnable &&
- !this._isRemainLastEnable;
- const isSingle = this._isSingleSelection;
-
- if (remainPrev || isSingle) {
- this._clearSelectionControls();
- }
- }
if (!activeSelectionControl) return;
- /**
- * getActiveSelectionControl() --> activeSelectionControl.model.currentCell
- */
-
- // switch active cell when expanding selection!!
- if (activeSelectionControl && expandingMode) {
- const activeCellOfCurrSelectCtrl = activeSelectionControl.model.currentCell;
- if (!activeCellOfCurrSelectCtrl) return;
- let primaryCursorCellRangeByControlShape: ISelectionCellWithMergeInfo;
-
- const { startRow, startColumn, endRow, endColumn } = activeSelectionControl.model;
- switch (this.expandingControlMode) {
- case ExpandingControl.TOP_LEFT:
- primaryCursorCellRangeByControlShape = skeleton.getCellByIndex(endRow, endColumn);
- break;
- case ExpandingControl.BOTTOM_RIGHT:
- primaryCursorCellRangeByControlShape =
- skeleton.getCellByIndex(startRow, startColumn);
- break;
- case ExpandingControl.LEFT:
- primaryCursorCellRangeByControlShape =
- skeleton.getCellByIndex(startRow, endColumn);
- break;
- case ExpandingControl.RIGHT:
- primaryCursorCellRangeByControlShape =
- skeleton.getCellByIndex(startRow, startColumn);
- break;
- case ExpandingControl.TOP:
- primaryCursorCellRangeByControlShape =
- skeleton.getCellByIndex(endRow, startColumn);
- break;
- case ExpandingControl.BOTTOM:
- primaryCursorCellRangeByControlShape =
- skeleton.getCellByIndex(startRow, startColumn);
- break;
- default:
- primaryCursorCellRangeByControlShape =
- skeleton.getCellByIndex(startRow, startColumn);
- }
- activeSelectionControl.updateCurrCell(
- primaryCursorCellRangeByControlShape
- );
- }
+ this._changeCurrCellWhenControlPointerDown();
this._selectionMoveStart$.next(this.getSelectionDataWithStyle());
- this.hasSelection = true;
-
- // scene.onPointerUp & scene.onPointerMoveObserver called this method
- // this._endSelection();
+ this._clearEndingListeners();
+ this._addEndingListeners();
- // scene.disableEvent();
-
- const startViewport = scene.getActiveViewportByCoord(Vector2.FromArray([newEvtOffsetX, newEvtOffsetY]));
-
- const scrollTimer = ScrollTimer.create(this._scene, scrollTimerType);
- scrollTimer.startScroll(viewportMain?.left ?? 0, viewportMain?.top ?? 0, viewportMain);
-
- this._scrollTimer = scrollTimer;
-
- this._addCancelObserver();
+ this._scrollTimer = ScrollTimer.create(this._scene, scrollTimerType);
+ this._scrollTimer.startScroll(viewportMain?.left ?? 0, viewportMain?.top ?? 0, viewportMain);
scene.getTransformer()?.clearSelectedObjects();
- // if (rangeType === RANGE_TYPE.ROW || rangeType === RANGE_TYPE.COLUMN) {
- // this._movingHandler(newEvtOffsetX, newEvtOffsetY, activeSelectionControl, rangeType);
- // }
-
- let xCrossTime = 0;
- let yCrossTime = 0;
- let lastX = newEvtOffsetX;
- let lastY = newEvtOffsetY;
-
- //#region handle pointermove after control pointer has clicked
- this._scenePointerMoveSub = scene.onPointerMove$.subscribeEvent((moveEvt: IPointerEvent | IMouseEvent) => {
- if (!this.expandingSelection) return;
-
- const { offsetX: moveOffsetX, offsetY: moveOffsetY } = moveEvt;
-
- const { x: newMoveOffsetX, y: newMoveOffsetY } = scene.getRelativeCoord(
- Vector2.FromArray([moveOffsetX, moveOffsetY])
- );
-
- this._movingHandler(newMoveOffsetX, newMoveOffsetY, activeSelectionControl, rangeType);
-
- let scrollOffsetX = newMoveOffsetX;
- let scrollOffsetY = newMoveOffsetY;
-
- const currentSelection = this.getActiveSelectionControl();
- const freeze = this._getFreeze();
-
- const selection = currentSelection?.model;
- const endViewport =
- scene.getActiveViewportByCoord(Vector2.FromArray([moveOffsetX, moveOffsetY])) ??
- this._getViewportByCell(selection?.endRow, selection?.endColumn);
-
- if (startViewport && endViewport && viewportMain) {
- const isCrossingX =
- (lastX < viewportMain.left && newMoveOffsetX > viewportMain.left) ||
- (lastX > viewportMain.left && newMoveOffsetX < viewportMain.left);
- const isCrossingY =
- (lastY < viewportMain.top && newMoveOffsetY > viewportMain.top) ||
- (lastY > viewportMain.top && newMoveOffsetY < viewportMain.top);
-
- if (isCrossingX) {
- xCrossTime += 1;
- }
-
- if (isCrossingY) {
- yCrossTime += 1;
- }
-
- const startKey = startViewport.viewportKey;
- const endKey = endViewport.viewportKey;
-
- if (startKey === SHEET_VIEWPORT_KEY.VIEW_ROW_TOP) {
- if (moveOffsetY < viewportMain.top && (selection?.endRow ?? 0) < (freeze?.startRow ?? 0)) {
- scrollOffsetY = viewportMain.top;
- } else if (isCrossingY && yCrossTime % 2 === 1) {
- viewportMain.scrollTo({
- y: 0,
- });
- }
- } else if (startKey === SHEET_VIEWPORT_KEY.VIEW_COLUMN_LEFT) {
- if (moveOffsetX < viewportMain.left && (selection?.endColumn ?? 0) < (freeze?.startColumn ?? 0)) {
- scrollOffsetX = viewportMain.left;
- } else if (isCrossingX && xCrossTime % 2 === 1) {
- viewportMain.scrollTo({
- x: 0,
- });
- }
- } else if (startKey === endKey) {
- let disableX = false;
- let disableY = false;
- if (startKey === SHEET_VIEWPORT_KEY.VIEW_MAIN_LEFT_TOP) {
- disableX = true;
- disableY = true;
- } else if (startKey === SHEET_VIEWPORT_KEY.VIEW_MAIN_TOP) {
- disableY = true;
- } else if (startKey === SHEET_VIEWPORT_KEY.VIEW_MAIN_LEFT) {
- disableX = true;
- }
-
- if ((selection?.endRow ?? 0) > (freeze?.startRow ?? 0)) {
- disableY = false;
- }
-
- if ((selection?.endColumn ?? 0) > (freeze?.startColumn ?? 0)) {
- disableX = false;
- }
- if (disableX) {
- scrollOffsetX = viewportMain.left;
- }
-
- if (disableY) {
- scrollOffsetY = viewportMain.top;
- }
- } else {
- const startXY = {
- x: startViewport.scrollX,
- y: startViewport.scrollY,
- };
- const endXY = {
- x: endViewport.scrollX,
- y: endViewport.scrollY,
- };
- const checkStartViewportType = [
- SHEET_VIEWPORT_KEY.VIEW_MAIN_LEFT_TOP,
- SHEET_VIEWPORT_KEY.VIEW_MAIN_TOP,
- SHEET_VIEWPORT_KEY.VIEW_MAIN_LEFT,
- ].includes(startViewport.viewportKey as SHEET_VIEWPORT_KEY);
- const shouldResetX = checkStartViewportType && startXY.x !== endXY.x && isCrossingX && xCrossTime % 2 === 1;
- const shouldResetY = checkStartViewportType && startXY.y !== endXY.y && isCrossingY && yCrossTime % 2 === 1;
-
- if (shouldResetX || shouldResetY) {
- viewportMain.scrollTo({
- x: shouldResetX ? startXY.x : undefined,
- y: shouldResetY ? startXY.y : undefined,
- });
-
- if (!shouldResetX) {
- scrollOffsetX = viewportMain.left;
- }
-
- if (!shouldResetY) {
- scrollOffsetY = viewportMain.top;
- }
- }
-
- if (
- (startKey === SHEET_VIEWPORT_KEY.VIEW_MAIN_LEFT_TOP && endKey === SHEET_VIEWPORT_KEY.VIEW_MAIN_LEFT) ||
- (endKey === SHEET_VIEWPORT_KEY.VIEW_MAIN_LEFT_TOP && startKey === SHEET_VIEWPORT_KEY.VIEW_MAIN_LEFT)
- ) {
- scrollOffsetX = viewportMain.left;
- }
-
- if (
- (startKey === SHEET_VIEWPORT_KEY.VIEW_MAIN_LEFT_TOP && endKey === SHEET_VIEWPORT_KEY.VIEW_MAIN_TOP) ||
- (endKey === SHEET_VIEWPORT_KEY.VIEW_MAIN_LEFT_TOP && startKey === SHEET_VIEWPORT_KEY.VIEW_MAIN_TOP)
- ) {
- scrollOffsetY = viewportMain.top;
- }
- }
-
- lastX = newMoveOffsetX;
- lastY = newMoveOffsetY;
- }
- scrollTimer.scrolling(scrollOffsetX, scrollOffsetY, () => {
- this._movingHandler(newMoveOffsetX, newMoveOffsetY, activeSelectionControl, rangeType);
- });
- });
+ //#region pointermove
+ const relativeCoords = scene.getRelativeToViewportCoord(Vector2.FromArray([evt.offsetX, evt.offsetY]));
+ this._setupPointerMoveListener(viewportMain, activeSelectionControl!, rangeType, scrollTimerType, relativeCoords.x, relativeCoords.y);
//#endregion
- //#region handle pointerup after control pointer has clicked
+ //#region pointerup
this._scenePointerUpSub = scene.onPointerUp$.subscribeEvent((_evt: IPointerEvent | IMouseEvent) => {
- this._endSelection();
- this.expandingSelection = false;
+ this.endSelection();
+ this._expandingSelection = false;
this.expandingControlMode = ExpandingControl.BOTTOM_RIGHT;
this._selectionMoveEnd$.next(this.getSelectionDataWithStyle());
@@ -1014,197 +524,134 @@ export class MobileSelectionRenderService implements ISelectionRenderService {
this._shortcutService.setDisable(true);
}
- attachSelectionWithCoord(selectionWithStyle: ISelectionWithStyle): ISelectionWithCoordAndStyle {
- const { range, primary, style } = selectionWithStyle;
- let rangeWithCoord = this.attachRangeWithCoord(range);
- if (rangeWithCoord == null) {
- rangeWithCoord = {
- startRow: -1,
- startColumn: -1,
- endRow: -1,
- endColumn: -1,
- startY: 0,
- endY: 0,
- startX: 0,
- endX: 0,
- rangeType: RANGE_TYPE.NORMAL,
- };
- }
- return {
- rangeWithCoord,
- primaryWithCoord: this.attachPrimaryWithCoord(primary),
- style,
- };
- }
-
- attachRangeWithCoord(range: IRange): Nullable<IRangeWithCoord> {
- const { startRow, startColumn, endRow, endColumn, rangeType } = range;
- const scene = this._scene;
+ private _changeCurrCellWhenControlPointerDown(): ISelectionCellWithMergeInfo {
+ const activeSelectionControl = this.getActiveSelectionControl<MobileSelectionControl>()!;
const skeleton = this._skeleton;
- if (scene == null || skeleton == null) {
- return;
- }
- const { scaleX, scaleY } = scene.getAncestorScale();
- const startCell = skeleton.getNoMergeCellPositionByIndex(startRow, startColumn);
- const endCell = skeleton.getNoMergeCellPositionByIndex(endRow, endColumn);
-
- return {
- startRow,
- startColumn,
- endRow,
- endColumn,
- rangeType,
- startY: startCell?.startY || 0,
- endY: endCell?.endY || 0,
- startX: startCell?.startX || 0,
- endX: endCell?.endX || 0,
- };
- }
- attachPrimaryWithCoord(primary: Nullable<ISelectionCell>): Nullable<ISelectionCellWithMergeInfo> {
- if (primary == null) {
- return;
- }
+ let currCellRange: ISelectionCellWithMergeInfo;
- const scene = this._scene;
- const skeleton = this._skeleton;
- if (scene == null || skeleton == null) {
- return;
- }
- const { actualRow, actualColumn, isMerged, isMergedMainCell, startRow, startColumn, endRow, endColumn } =
- primary;
-
- const cellPosition = skeleton.getNoMergeCellPositionByIndex(actualRow, actualColumn);
-
- const startCell = skeleton.getNoMergeCellPositionByIndex(startRow, startColumn);
- const endCell = skeleton.getNoMergeCellPositionByIndex(endRow, endColumn);
-
- return {
- actualRow,
- actualColumn,
- isMerged,
- isMergedMainCell,
- startX: cellPosition.startX,
- startY: cellPosition.startY,
- endX: cellPosition.endX,
- endY: cellPosition.endY,
- mergeInfo: {
- startRow,
- startColumn,
- endRow,
- endColumn,
- startY: startCell?.startY || 0,
- endY: endCell?.endY || 0,
- startX: startCell?.startX || 0,
- endX: endCell?.endX || 0,
- },
- };
- }
-
- getSelectionCellByPosition(x: number, y: number) {
- const scene = this._scene;
-
- if (scene == null) {
- return;
- }
-
- const skeleton = this._renderManagerService.withCurrentTypeOfUnit(UniverInstanceType.UNIVER_SHEET, SheetSkeletonManagerService)?.getCurrent()?.skeleton;
- if (skeleton == null) {
- return;
+ const { startRow, startColumn, endRow, endColumn } = activeSelectionControl.model;
+ switch (this.expandingControlMode) {
+ case ExpandingControl.TOP_LEFT:
+ currCellRange = skeleton.getCellByIndex(endRow, endColumn);
+ break;
+ case ExpandingControl.BOTTOM_RIGHT:
+ currCellRange =
+ skeleton.getCellByIndex(startRow, startColumn);
+ break;
+ case ExpandingControl.LEFT:
+ currCellRange =
+ skeleton.getCellByIndex(startRow, endColumn);
+ currCellRange.isMerged = false;
+ currCellRange.isMergedMainCell = false;
+ break;
+ case ExpandingControl.RIGHT:
+ currCellRange =
+ skeleton.getCellByIndex(startRow, startColumn);
+ currCellRange.isMerged = false;
+ currCellRange.isMergedMainCell = false;
+ break;
+ case ExpandingControl.TOP:
+ currCellRange =
+ skeleton.getCellByIndex(endRow, startColumn);
+ currCellRange.isMerged = false;
+ currCellRange.isMergedMainCell = false;
+ break;
+ case ExpandingControl.BOTTOM:
+ currCellRange =
+ skeleton.getCellByIndex(startRow, startColumn);
+ currCellRange.isMerged = false;
+ currCellRange.isMergedMainCell = false;
+ break;
+ default:
+ currCellRange =
+ skeleton.getCellByIndex(startRow, startColumn);
}
-
- // const scrollXY = scene.getScrollXYByRelativeCoords(Vector2.FromArray([this._startOffsetX, this._startOffsetY]));
- const scrollXY = scene.getScrollXY(scene.getViewport(SHEET_VIEWPORT_KEY.VIEW_MAIN)!);
- const { scaleX, scaleY } = scene.getAncestorScale();
-
- return skeleton.calculateCellIndexByPosition(
- x,
- y,
- scaleX,
- scaleY,
- scrollXY
- );
+ activeSelectionControl.updateCurrCell(currCellRange);
+ return currCellRange;
}
/**
- * When mousedown and mouseup need to go to the coordination and undo stack, when mousemove does not need to go to the coordination and undo stack
+ * Not same as _moving in base selection render service
+ * The diff is
+ * In base version, new selection is determined by the cursor cell and _startRangeWhenPointerDown
+ *
+ * In Mobile version, new selection is determined by cursor cell and current of activeSelectionControl.model
*/
- private _movingHandler(
- moveOffsetX: number,
- moveOffsetY: number,
- activeSelectionControl: Nullable<SelectionControl>,
+ protected override _moving(
+ offsetX: number,
+ offsetY: number,
+ activeSelectionControl: MobileSelectionControl,
rangeType: RANGE_TYPE
) {
+ this._shouldDetectMergedCells = rangeType === RANGE_TYPE.NORMAL;
const skeleton = this._skeleton;
-
const scene = this._scene;
- if (scene == null || skeleton == null) {
- return false;
- }
-
- const activeSelectionRange: IRange = {
- startRow: activeSelectionControl?.model.startRow ?? -1,
- endRow: activeSelectionControl?.model.endRow ?? -1,
- startColumn: activeSelectionControl?.model.startColumn ?? -1,
- endColumn: activeSelectionControl?.model.endColumn ?? -1,
+ const currSelectionRange: IRange = {
+ startRow: activeSelectionControl.model.startRow,
+ endRow: activeSelectionControl.model.endRow,
+ startColumn: activeSelectionControl.model.startColumn,
+ endColumn: activeSelectionControl.model.endColumn,
};
const viewportMain = scene.getViewport(SHEET_VIEWPORT_KEY.VIEW_MAIN)!;
- const targetViewport = this._getViewportByCell(activeSelectionRange.endRow, activeSelectionRange.endColumn) ?? viewportMain;
+ const targetViewport = this._getViewportByCell(currSelectionRange.endRow, currSelectionRange.endColumn) ?? viewportMain;
- const scrollXY = scene.getScrollXYByRelativeCoords(
- Vector2.FromArray([this._startOffsetX, this._startOffsetY]),
+ const scrollXY = scene.getVpScrollXYInfoByPosToVp(
+ Vector2.FromArray([this._startViewportPosX, this._startViewportPosY]),
targetViewport
);
const { scaleX, scaleY } = scene.getAncestorScale();
- const { rowHeaderWidth, columnHeaderHeight } = skeleton;
+ // const { rowHeaderWidth, columnHeaderHeight } = skeleton;
if (rangeType === RANGE_TYPE.ROW) {
- moveOffsetX = Number.POSITIVE_INFINITY;
+ offsetX = Number.POSITIVE_INFINITY;
} else if (rangeType === RANGE_TYPE.COLUMN) {
- moveOffsetY = Number.POSITIVE_INFINITY;
+ offsetY = Number.POSITIVE_INFINITY;
}
- const cursorCellRangeInfo = this._getCellRangeByCursorPosition(moveOffsetX, moveOffsetY, scaleX, scaleY, scrollXY);
+ const cursorCellRangeInfo = this._getCellRangeByCursorPosition(offsetX, offsetY, scaleX, scaleY, scrollXY);
if (!cursorCellRangeInfo) {
return false;
}
const { rangeWithCoord: cursorCellRange } = cursorCellRangeInfo;
- const {
- startRow: cursorStartRow,
- startColumn: cursorStartColumn,
- endColumn: cursorEndColumn,
- endRow: cursorEndRow,
- } = cursorCellRange;
-
- const currCellOfActiveSelctionControl = activeSelectionControl?.model.currentCell;
- const startRowOfActiveCell = currCellOfActiveSelctionControl?.mergeInfo.startRow ?? -1;
- const endRowOfActiveCell = currCellOfActiveSelctionControl?.mergeInfo.endRow ?? -1;
- const startColumnOfActiveCell = currCellOfActiveSelctionControl?.mergeInfo.startColumn ?? -1;
- const endColOfActiveCell = currCellOfActiveSelctionControl?.mergeInfo.endColumn ?? -1;
-
- // startRowCol endRowCol from _activeCellRangeOfCurrSelection
- const expandStartRow = Math.min(cursorStartRow, startRowOfActiveCell);
- const expandStartColumn = Math.min(cursorStartColumn, startColumnOfActiveCell);
- const expandEndRow = Math.max(cursorEndRow, endRowOfActiveCell);
- const expandEndColumn = Math.max(cursorEndColumn, endColOfActiveCell);
-
- // console.log(this.expandingControlMode, 'end col', cursorEndColumn, endColOfActiveCell, currSelCtrlEndRow, cursorEndRow);
+ const currCellRange = activeSelectionControl.model.currentCell;
+ const startRowOfActiveCell = currCellRange?.mergeInfo.startRow ?? -1;
+ const endRowOfActiveCell = currCellRange?.mergeInfo.endRow ?? -1;
+ const startColumnOfActiveCell = currCellRange?.mergeInfo.startColumn ?? -1;
+ const endColOfActiveCell = currCellRange?.mergeInfo.endColumn ?? -1;
+
let newSelectionRange: IRange = {
- startRow: expandStartRow,
- startColumn: expandStartColumn,
- endRow: expandEndRow,
- endColumn: expandEndColumn,
+ startRow: Math.min(cursorCellRange.startRow, startRowOfActiveCell),
+ startColumn: Math.min(cursorCellRange.startColumn, startColumnOfActiveCell),
+ endRow: Math.max(cursorCellRange.endRow, endRowOfActiveCell),
+ endColumn: Math.max(cursorCellRange.endColumn, endColOfActiveCell),
};
- if (this._isDetectMergedCell) {
- newSelectionRange = skeleton.getSelectionBounding(expandStartRow, expandStartColumn, expandEndRow, expandEndColumn);
+ if (rangeType === RANGE_TYPE.NORMAL) {
+ newSelectionRange = skeleton.getSelectionMergeBounding(newSelectionRange.startRow, newSelectionRange.startColumn, newSelectionRange.endRow, newSelectionRange.endColumn);
+ } else if (rangeType === RANGE_TYPE.COLUMN) {
+ newSelectionRange = {
+ startRow: Math.min(cursorCellRange.startRow, currCellRange?.actualRow ?? -1),
+ startColumn: Math.min(cursorCellRange.startColumn, currCellRange?.actualColumn ?? -1),
+ endRow: Math.max(cursorCellRange.endRow, currCellRange?.actualRow ?? -1),
+ endColumn: Math.max(cursorCellRange.endColumn, currCellRange?.actualColumn ?? -1),
+
+ };
+ } else if (rangeType === RANGE_TYPE.ROW) {
+ newSelectionRange = {
+ startRow: Math.min(cursorCellRange.startRow, currCellRange?.actualRow ?? -1),
+ startColumn: Math.min(cursorCellRange.startColumn, currCellRange?.actualColumn ?? -1),
+ endRow: Math.max(cursorCellRange.endRow, currCellRange?.actualRow ?? -1),
+ endColumn: Math.max(cursorCellRange.endColumn, currCellRange?.actualColumn ?? -1),
+
+ };
}
if (!newSelectionRange) {
@@ -1225,133 +672,45 @@ export class MobileSelectionRenderService implements ISelectionRenderService {
endX: endCellXY?.endX || 0,
};
- if (
- activeSelectionRange.startRow !== newSelectionRange.startRow ||
- activeSelectionRange.startColumn !== newSelectionRange.startColumn ||
- activeSelectionRange.endRow !== newSelectionRange.endRow ||
- activeSelectionRange.endColumn !== newSelectionRange.endColumn
- ) {
+ const rangeChanged =
+ currSelectionRange.startRow !== newSelectionRange.startRow ||
+ currSelectionRange.startColumn !== newSelectionRange.startColumn ||
+ currSelectionRange.endRow !== newSelectionRange.endRow ||
+ currSelectionRange.endColumn !== newSelectionRange.endColumn;
+ if (rangeChanged) {
if (activeSelectionControl) {
- // activeSelectionControl.update(newSelectionRangeWithCoord, rowHeaderWidth, columnHeaderHeight, null, null, activeSelectionControl.model.rangeType);
- activeSelectionControl.updateRange(newSelectionRangeWithCoord);
+ this._updateSelectionControlRange(activeSelectionControl, newSelectionRangeWithCoord);
this._selectionMoving$.next(this.getSelectionDataWithStyle());
}
}
}
- /**
- * rm pointerUp & pointerMove Observer on scene
- */
- private _endSelection() {
- const scene = this._scene;
- if (scene == null) {
- return;
- }
-
- // scene.onPointerMove$.remove(this._scenePointerMoveSub);
- // scene.onPointerUp$.remove(this._scenePointerUpSub);
- this._scenePointerMoveSub?.unsubscribe();
- this._scenePointerUpSub?.unsubscribe();
- scene.enableEvent();
-
- this._scrollTimer?.dispose();
-
- // const mainScene = scene.getEngine()?.activeScene;
- // mainScene?.onPointerUp$.remove(this._mainScenePointerUpSub);
- this._mainScenePointerUpSub?.unsubscribe();
-
- this._pointerdownSub?.unsubscribe();
- this._pointerdownSub = null;
- }
-
- private _addCancelObserver() {
- const scene = this._scene;
- if (scene == null) {
- return;
- }
-
- const mainScene = scene.getEngine()?.activeScene;
- if (mainScene == null || mainScene === scene) {
- return;
- }
-
- // mainScene.onPointerUp$.remove(this._mainScenePointerUpSub);
- this._mainScenePointerUpSub?.unsubscribe();
- this._mainScenePointerUpSub = mainScene.onPointerUp$.subscribeEvent(() => this._endSelection());
-
- this._pointerdownSub?.unsubscribe();
- this._pointerdownSub = mainScene.onPointerDown$.subscribeEvent(() => this._endSelection());
- }
-
- private _getCellRangeByCursorPosition(
- offsetX: number,
- offsetY: number,
- scaleX: number,
- scaleY: number,
- scrollXY: { x: number; y: number }
- ): Nullable<ISelectionWithCoord> {
- if (this._isDetectMergedCell) {
- const primaryWithCoord = this._skeleton?.calculateCellIndexByPosition(
- offsetX,
- offsetY,
- scaleX,
- scaleY,
- scrollXY
- );
- const rangeWithCoord = makeCellToSelection(primaryWithCoord);
- if (rangeWithCoord == null) {
+ private _updateControlPointWhenScrolling() {
+ const { scene } = this._context;
+ const viewportMain = scene.getViewport(SHEET_VIEWPORT_KEY.VIEW_MAIN);
+ if (!viewportMain) return;
+ // const sub = this._scrollManagerService.scrollInfo$.subscribe((param) => {
+ // const sub = viewportMain.onScrollAfter$.subscribeEvent((param) => {
+ const sub = this._scrollManagerService.validViewportScrollInfo$.subscribe((param) => {
+ if (param == null) {
return;
}
- return {
- primaryWithCoord,
- rangeWithCoord,
- };
- }
-
- const skeleton = this._skeleton;
-
- if (skeleton == null) {
- return;
- }
-
- const moveActualSelection = skeleton.getCellPositionByOffset(offsetX, offsetY, scaleX, scaleY, scrollXY);
-
- const { row, column } = moveActualSelection;
-
- const startCell = skeleton.getNoMergeCellPositionByIndex(row, column);
+ const { viewportScrollX, viewportScrollY } = param!;
- const { startX, startY, endX, endY } = startCell;
-
- const rangeWithCoord = {
- startY,
- endY,
- startX,
- endX,
- startRow: row,
- endRow: row,
- startColumn: column,
- endColumn: column,
- };
-
- const primaryWithCoord = {
- actualRow: row,
- actualColumn: column,
-
- isMerged: false,
-
- isMergedMainCell: false,
-
- startY,
- endY,
- startX,
- endX,
-
- mergeInfo: rangeWithCoord,
- };
-
- return {
- primaryWithCoord,
- rangeWithCoord,
- };
+ const activeControl = this.getActiveSelectionControl<MobileSelectionControl>();
+ if (activeControl == null) {
+ return;
+ }
+ const skeleton = this._sheetSkeletonManagerService.getCurrent()?.skeleton;
+ const sheetContentHeight = skeleton?.rowTotalHeight;
+ const sheetContentWidth = skeleton?.columnTotalWidth;
+ const rangeType = activeControl.rangeType;
+ if (rangeType === RANGE_TYPE.COLUMN) {
+ activeControl.transformControlPoint(0, viewportScrollY, sheetContentWidth, sheetContentHeight);
+ } else if (rangeType === RANGE_TYPE.ROW) {
+ activeControl.transformControlPoint(viewportScrollX, 0, sheetContentWidth, sheetContentHeight);
+ }
+ });
+ this.disposeWithMe(toDisposable(sub));
}
}
diff --git a/packages/sheets-ui/src/services/selection/selection-render-model.ts b/packages/sheets-ui/src/services/selection/selection-render-model.ts
index 027ca7e20a..ddcf4d6003 100644
--- a/packages/sheets-ui/src/services/selection/selection-render-model.ts
+++ b/packages/sheets-ui/src/services/selection/selection-render-model.ts
@@ -145,6 +145,7 @@ export class SelectionRenderModel implements IRangeWithCoord {
}
highlightToSelection() {
+ if (!this._currentCell) return;
return makeCellToSelection(this._currentCell);
}
diff --git a/packages/sheets-ui/src/services/selection/selection-render.service.ts b/packages/sheets-ui/src/services/selection/selection-render.service.ts
index 4ba3090a89..5f282183c2 100644
--- a/packages/sheets-ui/src/services/selection/selection-render.service.ts
+++ b/packages/sheets-ui/src/services/selection/selection-render.service.ts
@@ -14,1254 +14,236 @@
* limitations under the License.
*/
-/* eslint-disable complexity */
-/* eslint-disable max-lines-per-function */
-
-import type {
- IInterceptor,
- IRange,
- IRangeWithCoord,
- ISelection,
- ISelectionCell,
- ISelectionCellWithMergeInfo,
- ISelectionWithCoord,
- Nullable,
-} from '@univerjs/core';
-import { createInterceptorKey, InterceptorManager, makeCellToSelection, RANGE_TYPE, ThemeService, UniverInstanceType } from '@univerjs/core';
-import type { IMouseEvent, IPointerEvent, Scene, SpreadsheetSkeleton, Viewport } from '@univerjs/engine-render';
-import { IRenderManagerService, ScrollTimer, ScrollTimerType, SHEET_VIEWPORT_KEY, Vector2 } from '@univerjs/engine-render';
-import type { ISelectionStyle, ISelectionWithCoordAndStyle, ISelectionWithStyle } from '@univerjs/sheets';
-import { getNormalSelectionStyle } from '@univerjs/sheets';
+import type { Nullable, Workbook } from '@univerjs/core';
+import { ICommandService, IContextService, ILogService, RANGE_TYPE, ThemeService, toDisposable } from '@univerjs/core';
+import type { IMouseEvent, IPointerEvent, IRenderContext, IRenderModule } from '@univerjs/engine-render';
+import { IRenderManagerService, ScrollTimerType, SHEET_VIEWPORT_KEY, Vector2 } from '@univerjs/engine-render';
+import type { ISelectionWithCoordAndStyle, ISelectionWithStyle, ISetSelectionsOperationParams, WorkbookSelections } from '@univerjs/sheets';
+import { convertSelectionDataToRange, DISABLE_NORMAL_SELECTIONS, getNormalSelectionStyle, SelectionMoveType, SetSelectionsOperation, SheetsSelectionsService } from '@univerjs/sheets';
import { IShortcutService } from '@univerjs/ui';
-import { createIdentifier, Inject, Injector } from '@wendellhu/redi';
-import type { Observable, Subscription } from 'rxjs';
-import { BehaviorSubject, Subject } from 'rxjs';
-
-// import { SHEET_VIEWPORT_KEY } from '../../common/keys';
+import type { IDisposable } from '@wendellhu/redi';
+import { Inject, Injector } from '@wendellhu/redi';
+import { distinctUntilChanged, startWith } from 'rxjs';
import { SheetSkeletonManagerService } from '../sheet-skeleton-manager.service';
-import type { SelectionRenderModel } from './selection-render-model';
-import { SelectionControl as SelectionShape } from './selection-shape';
-import { SelectionShapeExtension } from './selection-shape-extension';
-
-export interface IControlFillConfig {
- oldRange: IRange;
- newRange: IRange;
-}
-
-export interface ISelectionRenderService {
- readonly selectionMoveEnd$: Observable<ISelectionWithCoordAndStyle[]>;
- readonly controlFillConfig$: Observable<IControlFillConfig | null>;
- readonly selectionMoving$: Observable<ISelectionWithCoordAndStyle[]>;
- readonly selectionMoveStart$: Observable<ISelectionWithCoordAndStyle[]>;
- readonly usable$: Observable<boolean>;
-
- interceptor: InterceptorManager<{
- RANGE_MOVE_PERMISSION_CHECK: IInterceptor<boolean, null>;
- RANGE_FILL_PERMISSION_CHECK: IInterceptor<boolean, { x: number; y: number; skeleton: SpreadsheetSkeleton; scene: Scene }>;
- }>;
+import type { ISheetObjectParam } from '../../controllers/utils/component-tools';
+import { getCoordByOffset, getSheetObject } from '../../controllers/utils/component-tools';
+import { checkInHeaderRanges } from '../../controllers/utils/selections-tools';
+import { attachSelectionWithCoord } from './util';
- enableHeaderHighlight(): void;
- disableHeaderHighlight(): void;
- enableDetectMergedCell(): void;
- disableDetectMergedCell(): void;
- setStyle(style: ISelectionStyle): void;
- resetStyle(): void;
- enableSelection(): void;
- disableSelection(): void;
- enableShowPrevious(): void;
- disableShowPrevious(): void;
- enableRemainLast(): void;
- disableRemainLast(): void;
- enableSkipRemainLast(): void;
- disableSkipRemainLast(): void;
-
- addSelectionControlBySelectionData(data: ISelectionWithCoordAndStyle): void;
- updateControlForCurrentByRangeData(selections: ISelectionWithCoordAndStyle[]): void;
- changeRuntime(skeleton: Nullable<SpreadsheetSkeleton>, scene: Nullable<Scene>, viewport?: Viewport): void;
-
- /** @deprecated This should not be provided by the selection render service. */
- getViewPort(): Viewport;
- getSelectionControls(): SelectionShape[];
- getActiveSelections(): Nullable<ISelection[]>;
- getActiveRange(): Nullable<IRange>;
- getActiveSelectionControl(): Nullable<SelectionShape>;
- getSelectionDataWithStyle(): ISelectionWithCoordAndStyle[];
- attachSelectionWithCoord(selectionWithStyle: ISelectionWithStyle): ISelectionWithCoordAndStyle;
- attachRangeWithCoord(range: IRange): Nullable<IRangeWithCoord>;
- attachPrimaryWithCoord(primary: Nullable<ISelectionCell>): Nullable<ISelectionCellWithMergeInfo>;
- getSelectionCellByPosition(x: number, y: number): Nullable<ISelectionCellWithMergeInfo>;
- eventTrigger(
- evt: IPointerEvent | IMouseEvent,
- zIndex: number,
- rangeType: RANGE_TYPE,
- viewport?: Viewport,
- scrollTimerType?: ScrollTimerType
- ): void;
- // getMoveCellInfo(direction: Direction, selectionData: Nullable<ISelectionWithCoord>): Nullable<ISelectionWithCoord>;
- // transformCellDataToSelectionData(row: number, column: number): Nullable<ISelectionWithCoord>;
- reset(): void;
-
- refreshSelectionMoveStart(): void;
-
- enableSingleSelection(): void;
- disableSingleSelection(): void;
-}
+import { BaseSelectionRenderService, getAllSelection, getTopLeftSelection } from './base-selection-render.service';
/**
- * TODO 注册 selection 拦截,可能在有公式 ArrayObject 时,fx 公式栏显示不同
- *
- * SelectionRenderService 维护 viewModel 数据 list,action 也是修改这一层数据,obs 监听到数据变动后,自动刷新(control 仍然可以持有数据)
- *
- * This service is related to the drawing of the selection.
- * By modifying the properties of the service,
- * you can adjust the style and performance of each selection area.
- * This service is used in conjunction with the SelectionManagerService
- * to implement functions related to the selection area in univer.
- *
- * @todo Refactor it to RenderController.
+ * This services controls rendering of normal selections in a render unit.
+ * The normal selections would also be used by Auto Fill and Copy features.
*/
+export class SheetSelectionRenderService extends BaseSelectionRenderService implements IRenderModule {
+ private readonly _workbookSelections: WorkbookSelections;
-export const RANGE_MOVE_PERMISSION_CHECK = createInterceptorKey<boolean, null>('rangeMovePermissionCheck');
-export const RANGE_FILL_PERMISSION_CHECK = createInterceptorKey<boolean, { x: number; y: number; skeleton: SpreadsheetSkeleton; scene: Scene }>('rangeFillPermissionCheck');
-
-export class SelectionRenderService implements ISelectionRenderService {
- hasSelection: boolean = false;
-
- private _pointerdownSub: Nullable<Subscription>;
-
- private _mainScenePointerUpSub: Nullable<Subscription>;
-
- private _scenePointerMoveSub: Nullable<Subscription>;
-
- private _scenePointerUpSub: Nullable<Subscription>;
-
- private _controlFillConfig$: BehaviorSubject<IControlFillConfig | null> =
- new BehaviorSubject<IControlFillConfig | null>(null);
-
- readonly controlFillConfig$ = this._controlFillConfig$.asObservable();
-
- private _selectionControls: SelectionShape[] = []; // sheetID:Controls
-
- private _startSelectionRange: IRangeWithCoord = {
- startY: 0,
- endY: 0,
- startX: 0,
- endX: 0,
- startRow: -1,
- endRow: -1,
- startColumn: -1,
- endColumn: -1,
- };
-
- private _startOffsetX: number = 0;
-
- private _startOffsetY: number = 0;
-
- private _scrollTimer!: ScrollTimer;
-
- private _skeleton: Nullable<SpreadsheetSkeleton>;
-
- private _scene: Nullable<Scene>;
-
- // The type of selector determines the type of data range and the highlighting style of the title bar
- private _isHeaderHighlight: boolean = true;
-
- // If true, the selector will respond to the range of merged cells and automatically extend the selected range. If false, it will ignore the merged cells.
- private _isDetectMergedCell: boolean = true;
-
- // The style of the selection area, including dashed lines, color, thickness, autofill, other points for modifying the range of the selection area, title highlighting, and so on, can all be customized.
- private _selectionStyle!: ISelectionStyle;
-
- // Whether to enable the selection area. If set to false, the user cannot draw a selection area in the content area by clicking with the mouse.
- private _isSelectionEnabled: boolean = true;
-
- // Used in the format painter feature, similar to ctrl, it can retain the previous selection.
- private _isShowPreviousEnable: boolean | number = 0;
-
- //Used in the formula selection feature, a new selection string is added by drawing a box with the mouse.
- private _isRemainLastEnable: boolean = true;
-
- private _isSkipRemainLastEnable: boolean = false;
-
- private _isSingleSelection: boolean = false; // Multiple selections are prohibited
-
- private readonly _selectionMoveEnd$ = new BehaviorSubject<ISelectionWithCoordAndStyle[]>([]);
-
- // When the user draws a selection area in the canvas content area, this event is broadcasted when the drawing ends.
- readonly selectionMoveEnd$ = this._selectionMoveEnd$.asObservable();
-
- private readonly _selectionMoving$ = new Subject<ISelectionWithCoordAndStyle[]>();
-
- /**
- * Triggered during the drawing of the selection area.
- */
- readonly selectionMoving$ = this._selectionMoving$.asObservable();
-
- private readonly _selectionMoveStart$ = new Subject<ISelectionWithCoordAndStyle[]>();
-
- /**
- * Triggered during the start draw the selection area.
- */
- readonly selectionMoveStart$ = this._selectionMoveStart$.asObservable();
-
- private _activeViewport: Nullable<Viewport>;
-
- /**
- * This service relies on the scene and skeleton to work
- * Use usable$ to check if this service works
- */
- private readonly _usable$ = new BehaviorSubject<boolean>(false);
-
- readonly usable$ = this._usable$.asObservable();
- public interceptor = new InterceptorManager({ RANGE_MOVE_PERMISSION_CHECK, RANGE_FILL_PERMISSION_CHECK });
+ private _renderDisposable: Nullable<IDisposable> = null;
constructor(
- @Inject(ThemeService) private readonly _themeService: ThemeService,
- @IShortcutService private readonly _shortcutService: IShortcutService,
- @IRenderManagerService private readonly _renderManagerService: IRenderManagerService,
- @Inject(Injector) private readonly _injector: Injector
+ private readonly _context: IRenderContext<Workbook>,
+ @Inject(Injector) injector: Injector,
+ @Inject(ThemeService) themeService: ThemeService,
+ @IShortcutService shortcutService: IShortcutService,
+ @IRenderManagerService renderManagerService: IRenderManagerService,
+ @Inject(SheetsSelectionsService) selectionManagerService: SheetsSelectionsService,
+ @ILogService private readonly _logService: ILogService,
+ @ICommandService private readonly _commandService: ICommandService,
+ @IContextService private readonly _contextService: IContextService,
+ @Inject(SheetSkeletonManagerService) private readonly _sheetSkeletonManagerService: SheetSkeletonManagerService
) {
- this._selectionStyle = getNormalSelectionStyle(this._themeService);
- }
-
- enableHeaderHighlight() {
- this._isHeaderHighlight = true;
- }
-
- disableHeaderHighlight() {
- this._isHeaderHighlight = false;
- }
-
- enableDetectMergedCell() {
- this._isDetectMergedCell = true;
- }
-
- disableDetectMergedCell() {
- this._isDetectMergedCell = false;
- }
-
- setStyle(style: ISelectionStyle) {
- this._selectionStyle = style;
- }
-
- resetStyle() {
- this.setStyle(getNormalSelectionStyle(this._themeService));
- }
-
- enableSelection() {
- this._isSelectionEnabled = true;
- }
-
- disableSelection() {
- this._isSelectionEnabled = false;
- }
-
- enableShowPrevious() {
- this._isShowPreviousEnable = true;
- }
-
- disableShowPrevious() {
- this._isShowPreviousEnable = false;
- }
-
- enableRemainLast() {
- this._isRemainLastEnable = true;
- }
-
- disableRemainLast() {
- this._isRemainLastEnable = false;
- }
-
- enableSkipRemainLast() {
- this._isSkipRemainLastEnable = true;
- }
-
- disableSkipRemainLast() {
- this._isSkipRemainLastEnable = false;
- }
-
- enableSingleSelection() {
- this._isSingleSelection = true;
- }
-
- disableSingleSelection() {
- this._isSingleSelection = false;
- }
-
- getViewPort() {
- return this._activeViewport!;
- }
-
- /**
- * add a selection
- * @param data
- */
- addSelectionControlBySelectionData(data: ISelectionWithCoordAndStyle) {
- const currentControls = this.getSelectionControls();
-
- if (!currentControls) {
- return;
- }
- const { rangeWithCoord, primaryWithCoord } = data;
-
- const skeleton = this._skeleton;
-
- let { style } = data;
-
- if (style == null) {
- style = getNormalSelectionStyle(this._themeService);
- }
-
- const scene = this._scene;
-
- if (scene == null || skeleton == null) {
- return;
- }
-
- const control = new SelectionShape(scene, currentControls.length, this._isHeaderHighlight, this._themeService);
-
- // eslint-disable-next-line no-new
- new SelectionShapeExtension(control, skeleton, scene, this._themeService, this._injector);
-
- const { rowHeaderWidth, columnHeaderHeight } = skeleton;
-
- // update control
- control.update(rangeWithCoord, rowHeaderWidth, columnHeaderHeight, style, primaryWithCoord);
-
- if (this._isHeaderHighlight) {
- control.enableHeaderHighlight();
- } else {
- control.disableHeaderHighlight();
- }
- currentControls.push(control);
- }
-
- updateControlForCurrentByRangeData(selections: ISelectionWithCoordAndStyle[]) {
- const currentControls = this.getSelectionControls();
- if (!currentControls) {
- return;
- }
-
- const skeleton = this._skeleton;
-
- if (skeleton == null) {
- return;
- }
-
- const { rowHeaderWidth, columnHeaderHeight } = skeleton;
-
- for (let i = 0, len = selections.length; i < len; i++) {
- const { rangeWithCoord, primaryWithCoord, style } = selections[i];
-
- const control = currentControls[i];
-
- control.update(rangeWithCoord, rowHeaderWidth, columnHeaderHeight, style, primaryWithCoord);
- }
- }
-
- refreshSelectionMoveStart() {
- this._selectionMoveStart$.next(this.getSelectionDataWithStyle());
- }
-
- changeRuntime(skeleton: Nullable<SpreadsheetSkeleton>, scene: Nullable<Scene>, viewport?: Viewport) {
- this._skeleton = skeleton;
- this._scene = scene;
- this._activeViewport = viewport || scene?.getViewports()[0];
- this._usable$.next(Boolean(skeleton && scene));
- }
-
- getSelectionDataWithStyle(): ISelectionWithCoordAndStyle[] {
- const selectionControls = this._selectionControls;
- return selectionControls.map((control) => control.getValue());
- }
-
- getSelectionControls() {
- return this._selectionControls;
- }
-
- // private _getCurrentControl() {
- // const controls = this.getCurrentControls();
- // if (controls && controls.length > 0) {
- // for (const control of controls) {
- // const currentCell = control.model.currentCell;
- // if (currentCell) {
- // return control;
- // }
- // }
- // }
- // }
-
- private _clearSelectionControls() {
- const allSelectionControls = this.getSelectionControls();
- for (const control of allSelectionControls) {
- control.dispose();
- }
-
- allSelectionControls.length = 0; // clear currentSelectionControls
- }
-
- private _getFreeze() {
- const freeze = this._renderManagerService.withCurrentTypeOfUnit(UniverInstanceType.UNIVER_SHEET, SheetSkeletonManagerService)
- ?.getCurrent()?.skeleton.getWorksheetConfig().freeze;
- return freeze;
- }
-
- private _getViewportByCell(row?: number, column?: number) {
- if (!this._scene || row === undefined || column === undefined) {
- return null;
- }
- const freeze = this._getFreeze();
- if (!freeze || (freeze.startRow <= 0 && freeze.startColumn <= 0)) {
- return this._scene.getViewport(SHEET_VIEWPORT_KEY.VIEW_MAIN);
- }
-
- if (row > freeze.startRow && column > freeze.startColumn) {
- return this._scene.getViewport(SHEET_VIEWPORT_KEY.VIEW_MAIN);
- }
-
- if (row <= freeze.startRow && column <= freeze.startColumn) {
- return this._scene.getViewport(SHEET_VIEWPORT_KEY.VIEW_MAIN_LEFT_TOP);
- }
-
- if (row <= freeze.startRow && column > freeze.startColumn) {
- return this._scene.getViewport(SHEET_VIEWPORT_KEY.VIEW_MAIN_TOP);
- }
-
- if (row > freeze.startRow && column <= freeze.startColumn) {
- return this._scene.getViewport(SHEET_VIEWPORT_KEY.VIEW_MAIN_LEFT);
- }
- }
-
- /**
- * Returns the list of active ranges in the active sheet or null if there are no active ranges.
- * If there is a single range selected, this behaves as a getActiveRange() call.
- *
- * @returns
- */
- getActiveSelections(): Nullable<ISelection[]> {
- const controls = this.getSelectionControls();
- if (controls && controls.length > 0) {
- const selections = controls?.map((control: SelectionShape) => {
- const model: SelectionRenderModel = control.model;
- const currentCell = model.currentCell;
- let primary: Nullable<ISelectionCell> = null;
- if (currentCell) {
- primary = {
- actualRow: currentCell.actualRow,
- actualColumn: currentCell.actualColumn,
- isMerged: currentCell.isMerged,
- isMergedMainCell: currentCell.isMergedMainCell,
- startRow: currentCell.mergeInfo.startRow,
- startColumn: currentCell.mergeInfo.startColumn,
- endRow: currentCell.mergeInfo.endRow,
- endColumn: currentCell.mergeInfo.endColumn,
- };
- }
- return {
- range: {
- startRow: model.startRow,
- startColumn: model.startColumn,
- endRow: model.endRow,
- endColumn: model.endColumn,
- },
- primary,
- };
- });
- return selections;
- }
- }
-
- /**
- * Returns the selected range in the active sheet, or null if there is no active range. If multiple ranges are selected this method returns only the last selected range.
- * TODO: 默认最后一个选区为当前激活选区,或者当前激活单元格所在选区为激活选区
- * @returns
- */
- getActiveRange(): Nullable<IRange> {
- const controls = this.getSelectionControls();
- const model = controls && controls[controls.length - 1].model;
- return (
- model && {
- startRow: model.startRow,
- startColumn: model.startColumn,
- endRow: model.endRow,
- endColumn: model.endColumn,
- }
+ super(
+ injector,
+ themeService,
+ shortcutService,
+ renderManagerService
);
- }
-
- /**
- * get active selection control
- * @returns
- */
- getActiveSelectionControl(): Nullable<SelectionShape> {
- const controls = this.getSelectionControls();
- return controls && controls[controls.length - 1];
- }
-
- endSelection() {
- this._endSelection();
- this._selectionMoveEnd$.next(this.getSelectionDataWithStyle());
- // when selection mouse up, enable the short cut service
- this._shortcutService.setDisable(false);
+ this._workbookSelections = selectionManagerService.getWorkbookSelections(this._context.unitId);
+ this._init();
}
- /**
- * first, clear All selection controls
- * then unsubscribe all events
- */
- reset() {
- this._clearSelectionControls();
-
- this._scenePointerMoveSub?.unsubscribe();
- this._scenePointerUpSub?.unsubscribe();
-
- this._scenePointerMoveSub = null;
- this._scenePointerUpSub = null;
- }
+ private _init() {
+ const sheetObject = this._getSheetObject();
- resetAndEndSelection() {
- this.endSelection();
- this.reset();
+ this._initEventListeners(sheetObject);
+ this._initSelectionChangeListener();
+ this._initThemeChangeListener();
+ this._initSkeletonChangeListener();
+ this._initUserActionSyncListener();
}
- /**
- *
- * @param evt component point event
- * @param style selection style, Styles for user-customized selectors
- * @param zIndex Stacking order of the selection object
- * @param rangeType Determines whether the selection is made normally according to the range or by rows and columns
- */
- eventTrigger(
- evt: IPointerEvent | IMouseEvent,
- zIndex = 0,
- rangeType: RANGE_TYPE = RANGE_TYPE.NORMAL,
- viewport?: Viewport,
- scrollTimerType: ScrollTimerType = ScrollTimerType.ALL
- ) {
- if (this._isSelectionEnabled === false) {
- return;
- }
-
- const skeleton = this._skeleton;
-
- const { offsetX: evtOffsetX, offsetY: evtOffsetY } = evt;
+ private _initEventListeners(sheetObject: ISheetObjectParam): void {
+ const { spreadsheetRowHeader, spreadsheetColumnHeader, spreadsheet, spreadsheetLeftTopPlaceholder } = sheetObject;
+ const { scene } = this._context;
- const scene = this._scene;
-
- if (scene == null || skeleton == null) {
- return;
- }
-
- if (viewport != null) {
- this._activeViewport = viewport;
- }
-
- const viewportMain = scene.getViewport(SHEET_VIEWPORT_KEY.VIEW_MAIN);
- const relativeCoords = scene.getRelativeCoord(Vector2.FromArray([evtOffsetX, evtOffsetY]));
-
- let { x: newEvtOffsetX, y: newEvtOffsetY } = relativeCoords;
-
- this._startOffsetX = newEvtOffsetX;
- this._startOffsetY = newEvtOffsetY;
-
- const scrollXY = scene.getScrollXYByRelativeCoords(relativeCoords);
-
- const { scaleX, scaleY } = scene.getAncestorScale();
-
- if (rangeType === RANGE_TYPE.ROW) {
- newEvtOffsetX = 0;
- } else if (rangeType === RANGE_TYPE.COLUMN) {
- newEvtOffsetY = 0;
- }
-
- const selectionData = this._getSelectedRangeWithMerge(newEvtOffsetX, newEvtOffsetY, scaleX, scaleY, scrollXY);
-
- if (!selectionData) {
- return false;
- }
-
- const { rangeWithCoord: actualRangeWithCoord, primaryWithCoord } = selectionData;
-
- const { startRow, startColumn, endColumn, endRow, startY, endY, startX, endX } = actualRangeWithCoord;
-
- const { rowHeaderWidth, columnHeaderHeight } = skeleton;
-
- const startSelectionRange = {
- startColumn,
- startRow,
- endColumn,
- endRow,
- startY,
- endY,
- startX,
- endX,
- rangeType,
- };
-
- this._startSelectionRange = startSelectionRange;
-
- let selectionControl: Nullable<SelectionShape> = this.getActiveSelectionControl();
-
- const curControls = this.getSelectionControls();
-
- if (!curControls) {
- return false;
- }
-
- for (const control of curControls) {
- // right click
- if (evt.button === 2 && control.model.isInclude(startSelectionRange)) {
- selectionControl = control;
- return;
+ this.disposeWithMe(spreadsheet?.onPointerDown$.subscribeEvent((evt: IPointerEvent | IMouseEvent, state) => {
+ if (this._normalSelectionDisabled()) return;
+ this._onPointerDown(evt, spreadsheet.zIndex + 1, RANGE_TYPE.NORMAL, this._getActiveViewport(evt));
+ if (evt.button !== 2) {
+ state.stopPropagation();
}
- // Click to an existing selection
- if (control.model.isEqual(startSelectionRange)) {
- selectionControl = control;
- break;
- }
-
- // There can only be one highlighted cell, so clear the highlighted cell of the existing selection
- if (!evt.shiftKey) {
- control.clearHighlight();
- }
- }
-
- // In addition to pressing the ctrl or shift key, we must clear the previous selection
- if (
- (curControls.length > 0 &&
- !evt.ctrlKey &&
- !evt.shiftKey &&
- !this._isShowPreviousEnable &&
- !this._isRemainLastEnable) ||
- (curControls.length > 0 && this._isSingleSelection && !evt.shiftKey)
- ) {
- this._clearSelectionControls();
- }
-
- const currentCell = selectionControl && selectionControl.model.currentCell;
-
- if (selectionControl && evt.shiftKey && currentCell) {
- const { actualRow, actualColumn, mergeInfo: actualMergeInfo } = currentCell;
-
- /**
- * Get the maximum range selected based on the two cells selected with Shift.
- */
-
- const newStartRow = Math.min(actualRow, startSelectionRange.startRow, actualMergeInfo.startRow);
-
- const newEndRow = Math.max(actualRow, startSelectionRange.endRow, actualMergeInfo.endRow);
-
- const newStartColumn = Math.min(actualColumn, startSelectionRange.startColumn, actualMergeInfo.startColumn);
-
- const newEndColumn = Math.max(actualColumn, startSelectionRange.endColumn, actualMergeInfo.endColumn);
-
- /**
- * Calculate whether there are merged cells within the range. If there are, recursively expand the selection again.
- */
- const bounding = skeleton.getMergeBounding(newStartRow, newStartColumn, newEndRow, newEndColumn);
-
- const startCell = skeleton.getNoMergeCellPositionByIndex(bounding.startRow, bounding.startColumn);
-
- const endCell = skeleton.getNoMergeCellPositionByIndex(bounding.endRow, bounding.endColumn);
-
- const newSelectionRange = {
- startColumn: bounding.startColumn,
- startRow: bounding.startRow,
- endColumn: bounding.endColumn,
- endRow: bounding.endRow,
-
- startY: startCell.startY,
- endY: endCell.endY,
- startX: startCell.startX,
- endX: endCell.endX,
-
- rangeType,
- };
-
- /**
- * When expanding the selection with the Shift key,
- * the original highlighted cell should remain unchanged.
- * If the highlighted cell is a merged cell, the selection needs to be expanded.
- */
- const activeCell = skeleton.getCellByIndex(actualRow, actualColumn);
+ }));
- this._startSelectionRange = {
- startColumn: activeCell.mergeInfo.startColumn,
- startRow: activeCell.mergeInfo.startRow,
- endColumn: activeCell.mergeInfo.endColumn,
- endRow: activeCell.mergeInfo.endRow,
- startY: activeCell.mergeInfo.startY || 0,
- endY: activeCell.mergeInfo.endY || 0,
- startX: activeCell.mergeInfo.startX || 0,
- endX: activeCell.mergeInfo.endX || 0,
- rangeType,
- };
+ this.disposeWithMe(
+ spreadsheetRowHeader?.onPointerDown$.subscribeEvent((evt: IPointerEvent | IMouseEvent, state) => {
+ if (this._normalSelectionDisabled()) return;
- selectionControl.update(
- newSelectionRange,
- rowHeaderWidth,
- columnHeaderHeight,
- this._selectionStyle,
- currentCell
- );
- } else if (
- this._isRemainLastEnable &&
- selectionControl &&
- !evt.ctrlKey &&
- !evt.shiftKey &&
- !this._isSkipRemainLastEnable && !this._isSingleSelection
- ) {
- /**
- * Supports the formula ref text selection feature,
- * under the condition of preserving all previous selections, it modifies the position of the latest selection.
- */
+ const skeleton = this._sheetSkeletonManagerService.getCurrent()!.skeleton;
+ const { row } = getCoordByOffset(evt.offsetX, evt.offsetY, scene, skeleton);
+ const matchSelectionData = checkInHeaderRanges(this._workbookSelections.getCurrentSelections(), row, RANGE_TYPE.ROW);
+ if (matchSelectionData) return;
- selectionControl.update(
- startSelectionRange,
- rowHeaderWidth,
- columnHeaderHeight,
- this._selectionStyle,
- primaryWithCoord
- );
- } else {
- /**
- * The default behavior is to clear previous selections and always create new selections.
- */
- selectionControl = new SelectionShape(
- scene,
- curControls.length + zIndex,
- this._isHeaderHighlight,
- this._themeService
- );
-
- // eslint-disable-next-line no-new
- new SelectionShapeExtension(selectionControl, skeleton, scene, this._themeService, this._injector);
-
- selectionControl.update(
- startSelectionRange,
- rowHeaderWidth,
- columnHeaderHeight,
- this._selectionStyle,
- primaryWithCoord
- );
-
- curControls.push(selectionControl);
- }
-
- this._selectionMoveStart$.next(this.getSelectionDataWithStyle());
-
- this.hasSelection = true;
-
- this._endSelection();
-
- scene.disableEvent();
-
- const startViewport = scene.getActiveViewportByCoord(Vector2.FromArray([newEvtOffsetX, newEvtOffsetY]));
-
- const scrollTimer = ScrollTimer.create(this._scene, scrollTimerType);
- scrollTimer.startScroll(viewportMain?.left ?? 0, viewportMain?.top ?? 0, viewportMain);
-
- this._scrollTimer = scrollTimer;
-
- this._addCancelObserver();
-
- scene.getTransformer()?.clearSelectedObjects();
-
- if (rangeType === RANGE_TYPE.ROW || rangeType === RANGE_TYPE.COLUMN) {
- this._moving(newEvtOffsetX, newEvtOffsetY, selectionControl, rangeType);
- }
-
- let xCrossTime = 0;
- let yCrossTime = 0;
- let lastX = newEvtOffsetX;
- let lastY = newEvtOffsetY;
-
- this._scenePointerMoveSub = scene.onPointerMove$.subscribeEvent((moveEvt: IPointerEvent | IMouseEvent) => {
- const { offsetX: moveOffsetX, offsetY: moveOffsetY } = moveEvt;
-
- const { x: newMoveOffsetX, y: newMoveOffsetY } = scene.getRelativeCoord(
- Vector2.FromArray([moveOffsetX, moveOffsetY])
- );
-
- this._moving(newMoveOffsetX, newMoveOffsetY, selectionControl, rangeType);
-
- let scrollOffsetX = newMoveOffsetX;
- let scrollOffsetY = newMoveOffsetY;
-
- const currentSelection = this.getActiveSelectionControl();
- const freeze = this._getFreeze();
-
- const selection = currentSelection?.model;
- const endViewport =
- scene.getActiveViewportByCoord(Vector2.FromArray([moveOffsetX, moveOffsetY])) ??
- this._getViewportByCell(selection?.endRow, selection?.endColumn);
-
- if (startViewport && endViewport && viewportMain) {
- const isCrossingX =
- (lastX < viewportMain.left && newMoveOffsetX > viewportMain.left) ||
- (lastX > viewportMain.left && newMoveOffsetX < viewportMain.left);
- const isCrossingY =
- (lastY < viewportMain.top && newMoveOffsetY > viewportMain.top) ||
- (lastY > viewportMain.top && newMoveOffsetY < viewportMain.top);
-
- if (isCrossingX) {
- xCrossTime += 1;
- }
-
- if (isCrossingY) {
- yCrossTime += 1;
+ this._onPointerDown(evt, (spreadsheet.zIndex || 1) + 1, RANGE_TYPE.ROW, this._getActiveViewport(evt), ScrollTimerType.Y);
+ if (evt.button !== 2) {
+ state.stopPropagation();
}
+ })
+ );
- const startKey = startViewport.viewportKey;
- const endKey = endViewport.viewportKey;
-
- if (startKey === SHEET_VIEWPORT_KEY.VIEW_ROW_TOP) {
- if (moveOffsetY < viewportMain.top && (selection?.endRow ?? 0) < (freeze?.startRow ?? 0)) {
- scrollOffsetY = viewportMain.top;
- } else if (isCrossingY && yCrossTime % 2 === 1) {
- viewportMain.scrollTo({
- y: 0,
- });
- }
- } else if (startKey === SHEET_VIEWPORT_KEY.VIEW_COLUMN_LEFT) {
- if (moveOffsetX < viewportMain.left && (selection?.endColumn ?? 0) < (freeze?.startColumn ?? 0)) {
- scrollOffsetX = viewportMain.left;
- } else if (isCrossingX && xCrossTime % 2 === 1) {
- viewportMain.scrollTo({
- x: 0,
- });
- }
- } else if (startKey === endKey) {
- let disableX = false;
- let disableY = false;
- if (startKey === SHEET_VIEWPORT_KEY.VIEW_MAIN_LEFT_TOP) {
- disableX = true;
- disableY = true;
- } else if (startKey === SHEET_VIEWPORT_KEY.VIEW_MAIN_TOP) {
- disableY = true;
- } else if (startKey === SHEET_VIEWPORT_KEY.VIEW_MAIN_LEFT) {
- disableX = true;
- }
-
- if ((selection?.endRow ?? 0) > (freeze?.startRow ?? 0)) {
- disableY = false;
- }
-
- if ((selection?.endColumn ?? 0) > (freeze?.startColumn ?? 0)) {
- disableX = false;
- }
- if (disableX) {
- scrollOffsetX = viewportMain.left;
- }
-
- if (disableY) {
- scrollOffsetY = viewportMain.top;
- }
- } else {
- const startXY = {
- x: startViewport.scrollX,
- y: startViewport.scrollY,
- };
- const endXY = {
- x: endViewport.scrollX,
- y: endViewport.scrollY,
- };
- const shouldResetX = startXY.x !== endXY.x && isCrossingX && xCrossTime % 2 === 1;
- const shouldResetY = startXY.y !== endXY.y && isCrossingY && yCrossTime % 2 === 1;
-
- if (shouldResetX || shouldResetY) {
- viewportMain.scrollTo({
- x: shouldResetX ? startXY.x : undefined,
- y: shouldResetY ? startXY.y : undefined,
- });
-
- if (!shouldResetX) {
- scrollOffsetX = viewportMain.left;
- }
-
- if (!shouldResetY) {
- scrollOffsetY = viewportMain.top;
- }
- }
+ this.disposeWithMe(spreadsheetColumnHeader?.onPointerDown$.subscribeEvent((evt: IPointerEvent | IMouseEvent, state) => {
+ if (this._normalSelectionDisabled()) return;
- if (
- (startKey === SHEET_VIEWPORT_KEY.VIEW_MAIN_LEFT_TOP && endKey === SHEET_VIEWPORT_KEY.VIEW_MAIN_LEFT) ||
- (endKey === SHEET_VIEWPORT_KEY.VIEW_MAIN_LEFT_TOP && startKey === SHEET_VIEWPORT_KEY.VIEW_MAIN_LEFT)
- ) {
- scrollOffsetX = viewportMain.left;
- }
+ const skeleton = this._sheetSkeletonManagerService.getCurrent()!.skeleton;
+ const { column } = getCoordByOffset(evt.offsetX, evt.offsetY, scene, skeleton);
+ const matchSelectionData = checkInHeaderRanges(this._workbookSelections.getCurrentSelections(), column, RANGE_TYPE.COLUMN);
+ if (matchSelectionData) return;
- if (
- (startKey === SHEET_VIEWPORT_KEY.VIEW_MAIN_LEFT_TOP && endKey === SHEET_VIEWPORT_KEY.VIEW_MAIN_TOP) ||
- (endKey === SHEET_VIEWPORT_KEY.VIEW_MAIN_LEFT_TOP && startKey === SHEET_VIEWPORT_KEY.VIEW_MAIN_TOP)
- ) {
- scrollOffsetY = viewportMain.top;
- }
- }
+ this._onPointerDown(evt, (spreadsheet.zIndex || 1) + 1, RANGE_TYPE.COLUMN, this._getActiveViewport(evt), ScrollTimerType.X);
- lastX = newMoveOffsetX;
- lastY = newMoveOffsetY;
+ if (evt.button !== 2) {
+ state.stopPropagation();
}
- scrollTimer.scrolling(scrollOffsetX, scrollOffsetY, () => {
- this._moving(newMoveOffsetX, newMoveOffsetY, selectionControl, rangeType);
- });
- });
+ }));
- this._scenePointerUpSub = scene.onPointerUp$.subscribeEvent((_upEvt: IPointerEvent | IMouseEvent) => {
- this._endSelection();
- this._selectionMoveEnd$.next(this.getSelectionDataWithStyle());
+ this.disposeWithMe(spreadsheetLeftTopPlaceholder?.onPointerDown$.subscribeEvent((evt: IPointerEvent | IMouseEvent, state) => {
+ if (this._normalSelectionDisabled()) return;
- // when selection mouse up, enable the short cut service
- this._shortcutService.setDisable(false);
- });
+ this._reset(); // remove all other selections
- // when selection mouse down, disable the short cut service
- this._shortcutService.setDisable(true);
- }
+ const skeleton = this._sheetSkeletonManagerService.getCurrent()!.skeleton;
+ const selectionWithStyle = getAllSelection(skeleton);
+ const selectionData = attachSelectionWithCoord(selectionWithStyle, skeleton);
+ this._addSelectionControlBySelectionData(selectionData);
+ this.refreshSelectionMoveStart();
- attachSelectionWithCoord(selectionWithStyle: ISelectionWithStyle): ISelectionWithCoordAndStyle {
- const { range, primary, style } = selectionWithStyle;
- let rangeWithCoord = this.attachRangeWithCoord(range);
- if (rangeWithCoord == null) {
- rangeWithCoord = {
- startRow: -1,
- startColumn: -1,
- endRow: -1,
- endColumn: -1,
- startY: 0,
- endY: 0,
- startX: 0,
- endX: 0,
- rangeType: RANGE_TYPE.NORMAL,
- };
- }
- return {
- rangeWithCoord,
- primaryWithCoord: this.attachPrimaryWithCoord(primary),
- style,
- };
+ if (evt.button !== 2) {
+ state.stopPropagation();
+ }
+ }));
}
- attachRangeWithCoord(range: IRange): Nullable<IRangeWithCoord> {
- const { startRow, startColumn, endRow, endColumn, rangeType } = range;
- const scene = this._scene;
- const skeleton = this._skeleton;
- if (scene == null || skeleton == null) {
- return;
- }
- const { scaleX, scaleY } = scene.getAncestorScale();
- const startCell = skeleton.getNoMergeCellPositionByIndex(startRow, startColumn);
- const endCell = skeleton.getNoMergeCellPositionByIndex(endRow, endColumn);
+ private _initThemeChangeListener() {
+ this.disposeWithMe(this._themeService.currentTheme$.subscribe(() => {
+ this._resetStyle();
+ const param = this._workbookSelections.getCurrentSelections();
+ if (!param) return;
- return {
- startRow,
- startColumn,
- endRow,
- endColumn,
- rangeType,
- startY: startCell?.startY || 0,
- endY: endCell?.endY || 0,
- startX: startCell?.startX || 0,
- endX: endCell?.endX || 0,
- };
+ this._refreshSelection(param);
+ }));
}
- attachPrimaryWithCoord(primary: Nullable<ISelectionCell>): Nullable<ISelectionCellWithMergeInfo> {
- if (primary == null) {
- return;
- }
-
- const scene = this._scene;
- const skeleton = this._skeleton;
- if (scene == null || skeleton == null) {
- return;
- }
- const { actualRow, actualColumn, isMerged, isMergedMainCell, startRow, startColumn, endRow, endColumn } =
- primary;
-
- const cellPosition = skeleton.getNoMergeCellPositionByIndex(actualRow, actualColumn);
-
- const startCell = skeleton.getNoMergeCellPositionByIndex(startRow, startColumn);
- const endCell = skeleton.getNoMergeCellPositionByIndex(endRow, endColumn);
+ private _refreshSelection(params: readonly ISelectionWithStyle[]) {
+ const selections = params.map((selectionWithStyle) => {
+ const selectionData = attachSelectionWithCoord(selectionWithStyle, this._skeleton);
+ selectionData.style = getNormalSelectionStyle(this._themeService);
+ return selectionData;
+ });
- return {
- actualRow,
- actualColumn,
- isMerged,
- isMergedMainCell,
- startX: cellPosition.startX,
- startY: cellPosition.startY,
- endX: cellPosition.endX,
- endY: cellPosition.endY,
- mergeInfo: {
- startRow,
- startColumn,
- endRow,
- endColumn,
- startY: startCell?.startY || 0,
- endY: endCell?.endY || 0,
- startX: startCell?.startX || 0,
- endX: endCell?.endX || 0,
- },
- };
+ this.updateControlForCurrentByRangeData(selections);
}
- getSelectionCellByPosition(x: number, y: number) {
- const scene = this._scene;
-
- if (scene == null) {
- return;
- }
-
- const skeleton = this._renderManagerService.withCurrentTypeOfUnit(UniverInstanceType.UNIVER_SHEET, SheetSkeletonManagerService)?.getCurrent()?.skeleton;
- if (skeleton == null) {
- return;
- }
-
- // const scrollXY = scene.getScrollXYByRelativeCoords(Vector2.FromArray([this._startOffsetX, this._startOffsetY]));
- const scrollXY = scene.getScrollXY(scene.getViewport(SHEET_VIEWPORT_KEY.VIEW_MAIN)!);
- const { scaleX, scaleY } = scene.getAncestorScale();
-
- return skeleton.calculateCellIndexByPosition(
- x,
- y,
- scaleX,
- scaleY,
- scrollXY
- );
+ private _normalSelectionDisabled(): boolean {
+ return this._contextService.getContextValue(DISABLE_NORMAL_SELECTIONS);
}
- /**
- * When mousedown and mouseup need to go to the coordination and undo stack, when mousemove does not need to go to the coordination and undo stack
- */
- private _moving(
- moveOffsetX: number,
- moveOffsetY: number,
- selectionControl: Nullable<SelectionShape>,
- rangeType: RANGE_TYPE
- ) {
- const skeleton = this._skeleton;
-
- const scene = this._scene;
-
- if (scene == null || skeleton == null) {
- return false;
- }
-
- const { startRow, startColumn, endRow, endColumn } = this._startSelectionRange;
-
- const {
- startRow: oldStartRow,
- endRow: oldEndRow,
- startColumn: oldStartColumn,
- endColumn: oldEndColumn,
- } = selectionControl?.model || { startRow: -1, endRow: -1, startColumn: -1, endColumn: -1 };
-
- const viewportMain = scene.getViewport(SHEET_VIEWPORT_KEY.VIEW_MAIN)!;
-
- const targetViewport = this._getViewportByCell(oldEndRow, oldEndColumn) ?? viewportMain;
-
- const scrollXY = scene.getScrollXYByRelativeCoords(
- Vector2.FromArray([this._startOffsetX, this._startOffsetY]),
- targetViewport
- );
-
- const { scaleX, scaleY } = scene.getAncestorScale();
-
- const { rowHeaderWidth, columnHeaderHeight } = skeleton;
-
- if (rangeType === RANGE_TYPE.ROW) {
- moveOffsetX = Number.POSITIVE_INFINITY;
- } else if (rangeType === RANGE_TYPE.COLUMN) {
- moveOffsetY = Number.POSITIVE_INFINITY;
- }
-
- const selectionData = this._getSelectedRangeWithMerge(moveOffsetX, moveOffsetY, scaleX, scaleY, scrollXY);
- if (!selectionData) {
- return false;
- }
-
- const { rangeWithCoord: moveRangeWithCoord } = selectionData;
-
- const {
- startRow: moveStartRow,
- startColumn: moveStartColumn,
- endColumn: moveEndColumn,
- endRow: moveEndRow,
- } = moveRangeWithCoord;
-
- const newStartRow = Math.min(moveStartRow, startRow);
- const newStartColumn = Math.min(moveStartColumn, startColumn);
- const newEndRow = Math.max(moveEndRow, endRow);
- const newEndColumn = Math.max(moveEndColumn, endColumn);
-
- let newBounding = {
- startRow: newStartRow,
- startColumn: newStartColumn,
- endRow: newEndRow,
- endColumn: newEndColumn,
- };
-
- if (this._isDetectMergedCell) {
- newBounding = skeleton.getSelectionBounding(newStartRow, newStartColumn, newEndRow, newEndColumn);
- }
-
- if (!newBounding) {
- return false;
- }
- const {
- startRow: finalStartRow,
- startColumn: finalStartColumn,
- endRow: finalEndRow,
- endColumn: finalEndColumn,
- } = newBounding;
-
- const startCell = skeleton.getNoMergeCellPositionByIndex(finalStartRow, finalStartColumn);
- const endCell = skeleton.getNoMergeCellPositionByIndex(finalEndRow, finalEndColumn);
-
- const newSelectionRange: IRangeWithCoord = {
- startColumn: finalStartColumn,
- startRow: finalStartRow,
- endColumn: finalEndColumn,
- endRow: finalEndRow,
- startY: startCell?.startY || 0,
- endY: endCell?.endY || 0,
- startX: startCell?.startX || 0,
- endX: endCell?.endX || 0,
- };
- // Only notify when the selection changes
-
- if (
- (oldStartColumn !== finalStartColumn ||
- oldStartRow !== finalStartRow ||
- oldEndColumn !== finalEndColumn ||
- oldEndRow !== finalEndRow) &&
- selectionControl != null
- ) {
- selectionControl.update(newSelectionRange, rowHeaderWidth, columnHeaderHeight);
-
- this._selectionMoving$.next(this.getSelectionDataWithStyle());
- }
+ private _initSelectionChangeListener() {
+ // When selection completes, we need to update the selections' rendering and clear event handlers.
+ this.disposeWithMe(this._workbookSelections.selectionMoveEnd$.subscribe((params) => {
+ this._reset();
+ for (const selectionWithStyle of params) {
+ const selectionData = attachSelectionWithCoord(selectionWithStyle, this._skeleton);
+ this._addSelectionControlBySelectionData(selectionData);
+ }
+ }));
}
- private _endSelection() {
- const scene = this._scene;
- if (scene == null) {
- return;
- }
-
- // scene.onPointerMove$.remove(this._scenePointerMoveSub);
- // scene.onPointerUp$.remove(this._scenePointerUpSub);
- this._scenePointerMoveSub?.unsubscribe();
- this._scenePointerUpSub?.unsubscribe();
- scene.enableEvent();
-
- this._scrollTimer?.dispose();
-
- // const mainScene = scene.getEngine()?.activeScene;
- // mainScene?.onPointerUp$.remove(this._mainScenePointerUpSub);
- this._mainScenePointerUpSub?.unsubscribe();
+ private _initUserActionSyncListener() {
+ this.disposeWithMe(this.selectionMoveStart$.subscribe((params) => this._updateSelections(params, SelectionMoveType.MOVE_START)));
+ this.disposeWithMe(this.selectionMoving$.subscribe((params) => this._updateSelections(params, SelectionMoveType.MOVING)));
- this._pointerdownSub?.unsubscribe();
- this._pointerdownSub = null;
+ this.disposeWithMe(this._contextService.subscribeContextValue$(DISABLE_NORMAL_SELECTIONS)
+ .pipe(startWith(false), distinctUntilChanged())
+ .subscribe((disabled) => {
+ if (disabled) {
+ this._renderDisposable?.dispose();
+ this._renderDisposable = null;
+ this._reset();
+ } else {
+ this._renderDisposable = toDisposable(
+ this.selectionMoveEnd$.subscribe((params) => this._updateSelections(params, SelectionMoveType.MOVE_END))
+ );
+ }
+ }));
}
- private _addCancelObserver() {
- const scene = this._scene;
- if (scene == null) {
- return;
- }
+ private _updateSelections(selectionDataWithStyleList: ISelectionWithCoordAndStyle[], type: SelectionMoveType) {
+ const workbook = this._context.unit;
+ const unitId = workbook.getUnitId();
+ const sheetId = workbook.getActiveSheet().getSheetId();
- const mainScene = scene.getEngine()?.activeScene;
- if (mainScene == null || mainScene === scene) {
+ if (selectionDataWithStyleList.length === 0) {
return;
}
- // mainScene.onPointerUp$.remove(this._mainScenePointerUpSub);
- this._mainScenePointerUpSub?.unsubscribe();
- this._mainScenePointerUpSub = mainScene.onPointerUp$.subscribeEvent(() => this._endSelection());
-
- this._pointerdownSub?.unsubscribe();
- this._pointerdownSub = mainScene.onPointerDown$.subscribeEvent(() => this._endSelection());
+ this._commandService.executeCommand(SetSelectionsOperation.id, {
+ unitId,
+ subUnitId: sheetId,
+ type,
+ selections: selectionDataWithStyleList.map((selectionDataWithStyle) =>
+ convertSelectionDataToRange(selectionDataWithStyle)
+ ),
+ });
}
- private _getSelectedRangeWithMerge(
- offsetX: number,
- offsetY: number,
- scaleX: number,
- scaleY: number,
- scrollXY: { x: number; y: number }
- ): Nullable<ISelectionWithCoord> {
- if (this._isDetectMergedCell) {
- const primaryWithCoord = this._skeleton?.calculateCellIndexByPosition(
- offsetX,
- offsetY,
- scaleX,
- scaleY,
- scrollXY
- );
- const rangeWithCoord = makeCellToSelection(primaryWithCoord);
- if (rangeWithCoord == null) {
+ private _initSkeletonChangeListener() {
+ this.disposeWithMe(this._sheetSkeletonManagerService.currentSkeleton$.subscribe((param) => {
+ if (param == null) {
+ this._logService.error('[SelectionRenderService]: should not receive null!');
return;
}
- return {
- primaryWithCoord,
- rangeWithCoord,
- };
- }
-
- const skeleton = this._skeleton;
-
- if (skeleton == null) {
- return;
- }
-
- const moveActualSelection = skeleton.getCellPositionByOffset(offsetX, offsetY, scaleX, scaleY, scrollXY);
-
- const { row, column } = moveActualSelection;
-
- const startCell = skeleton.getNoMergeCellPositionByIndex(row, column);
-
- const { startX, startY, endX, endY } = startCell;
- const rangeWithCoord = {
- startY,
- endY,
- startX,
- endX,
- startRow: row,
- endRow: row,
- startColumn: column,
- endColumn: column,
- };
-
- const primaryWithCoord = {
- actualRow: row,
- actualColumn: column,
-
- isMerged: false,
-
- isMergedMainCell: false,
+ const unitId = this._context.unitId;
+ const { sheetId, skeleton } = param;
+ const { scene } = this._context;
+ const viewportMain = scene.getViewport(SHEET_VIEWPORT_KEY.VIEW_MAIN);
+ this._changeRuntime(skeleton, scene, viewportMain);
+
+ // If there is no initial selection, add one by default in the top left corner.
+ const firstSelection = this._workbookSelections.getCurrentLastSelection();
+ if (!firstSelection) {
+ this._commandService.syncExecuteCommand(SetSelectionsOperation.id, {
+ unitId,
+ subUnitId: sheetId,
+ selections: [getTopLeftSelection(skeleton)],
+ } as ISetSelectionsOperationParams);
+ }
- startY,
- endY,
- startX,
- endX,
+ // for col width & row height resize
+ const currentSelections = this._workbookSelections.getCurrentSelections();
+ if (currentSelections != null) {
+ this._refreshSelection(currentSelections);
+ }
+ }));
+ }
- mergeInfo: rangeWithCoord,
- };
+ private _getActiveViewport(evt: IPointerEvent | IMouseEvent) {
+ const sheetObject = this._getSheetObject();
+ return sheetObject?.scene.getActiveViewportByCoord(Vector2.FromArray([evt.offsetX, evt.offsetY]));
+ }
- return {
- primaryWithCoord,
- rangeWithCoord,
- };
+ private _getSheetObject() {
+ return getSheetObject(this._context.unit, this._context)!;
}
}
-
-/**
- * @deprecated Should be refactored to RenderUnit.
- */
-export const ISelectionRenderService = createIdentifier<SelectionRenderService>(
- 'univer.sheet.selection-render-service'
-);
diff --git a/packages/sheets-ui/src/services/selection/selection-shape-extension.ts b/packages/sheets-ui/src/services/selection/selection-shape-extension.ts
index 288d33099d..7f354ade4f 100644
--- a/packages/sheets-ui/src/services/selection/selection-shape-extension.ts
+++ b/packages/sheets-ui/src/services/selection/selection-shape-extension.ts
@@ -20,12 +20,13 @@ import { ColorKit, UniverInstanceType } from '@univerjs/core';
import type { IMouseEvent, IPointerEvent, Scene, SpreadsheetSkeleton, Viewport } from '@univerjs/engine-render';
import { CURSOR_TYPE, IRenderManagerService, isRectIntersect, Rect, ScrollTimer, ScrollTimerType, SHEET_VIEWPORT_KEY, Vector2 } from '@univerjs/engine-render';
import { getNormalSelectionStyle, SELECTION_CONTROL_BORDER_BUFFER_WIDTH } from '@univerjs/sheets';
-import type { Injector } from '@wendellhu/redi';
+import { type Injector, Quantity } from '@wendellhu/redi';
import type { Subscription } from 'rxjs';
import { SheetSkeletonManagerService } from '../sheet-skeleton-manager.service';
+import { ISheetSelectionRenderService } from './base-selection-render.service';
+import { RANGE_FILL_PERMISSION_CHECK, RANGE_MOVE_PERMISSION_CHECK } from './const';
import type { SelectionControl } from './selection-shape';
-import { ISelectionRenderService, RANGE_FILL_PERMISSION_CHECK, RANGE_MOVE_PERMISSION_CHECK } from './selection-render.service';
const HELPER_SELECTION_TEMP_NAME = '__SpreadsheetHelperSelectionTempRect';
@@ -83,6 +84,9 @@ export class SelectionShapeExtension {
private _skeleton: SpreadsheetSkeleton,
private _scene: Scene,
private readonly _themeService: ThemeService,
+
+ /** @deprecated injection in extensions should be strictly limited. */
+ // TODO@ybzky: remove injector here, permission control should be update from the outside.
private readonly _injector: Injector
) {
this._initialControl();
@@ -145,8 +149,6 @@ export class SelectionShapeExtension {
}
private _clearObserverEvent() {
- // this._scene.onPointerMove$.remove(this._scenePointerMoveSub);
- // this._scene.onPointerUp$.remove(this._scenePointerUpSub);
this._scenePointerMoveSub?.unsubscribe();
this._scenePointerUpSub?.unsubscribe();
this._scenePointerMoveSub = null;
@@ -157,10 +159,10 @@ export class SelectionShapeExtension {
const { leftControl, rightControl, topControl, bottomControl } = this._control;
[leftControl, rightControl, topControl, bottomControl].forEach((control) => {
- control.onPointerEnter$.subscribeEvent(() => {
- const permissionCheck = this._injector.get(ISelectionRenderService).interceptor.fetchThroughInterceptors(RANGE_MOVE_PERMISSION_CHECK)(false, null);
-
- if (!permissionCheck) {
+ control.onPointerDown$.subscribeEvent(() => {
+ const permissionCheck = this._injector.get(ISheetSelectionRenderService, Quantity.OPTIONAL)
+ ?.interceptor.fetchThroughInterceptors(RANGE_MOVE_PERMISSION_CHECK)(false, null);
+ if (permissionCheck === false) {
return;
}
@@ -178,7 +180,7 @@ export class SelectionShapeExtension {
private _controlMoving(moveOffsetX: number, moveOffsetY: number) {
const scene = this._scene;
- const scrollXY = scene.getScrollXYByRelativeCoords(Vector2.FromArray([moveOffsetX, moveOffsetY]));
+ const scrollXY = scene.getVpScrollXYInfoByPosToVp(Vector2.FromArray([moveOffsetX, moveOffsetY]));
const { scaleX, scaleY } = scene.getAncestorScale();
@@ -262,11 +264,11 @@ export class SelectionShapeExtension {
const scene = this._scene;
- const relativeCoords = scene.getRelativeCoord(Vector2.FromArray([evtOffsetX, evtOffsetY]));
+ const relativeCoords = scene.getRelativeToViewportCoord(Vector2.FromArray([evtOffsetX, evtOffsetY]));
const { x: newEvtOffsetX, y: newEvtOffsetY } = relativeCoords;
- const scrollXY = scene.getScrollXYByRelativeCoords(relativeCoords);
+ const scrollXY = scene.getVpScrollXYInfoByPosToVp(relativeCoords);
const { scaleX, scaleY } = scene.getAncestorScale();
@@ -342,13 +344,13 @@ export class SelectionShapeExtension {
this._scenePointerMoveSub = scene.onPointerMove$.subscribeEvent((moveEvt: IPointerEvent | IMouseEvent) => {
const { offsetX: moveOffsetX, offsetY: moveOffsetY } = moveEvt;
- const permissionCheck = this._injector.get(ISelectionRenderService).interceptor.fetchThroughInterceptors(RANGE_MOVE_PERMISSION_CHECK)(false, null);
-
- if (!permissionCheck) {
+ const permissionCheck = this._injector.get(ISheetSelectionRenderService, Quantity.OPTIONAL)
+ ?.interceptor.fetchThroughInterceptors(RANGE_MOVE_PERMISSION_CHECK)(false, null);
+ if (permissionCheck === false) {
return;
}
- const { x: newMoveOffsetX, y: newMoveOffsetY } = scene.getRelativeCoord(
+ const { x: newMoveOffsetX, y: newMoveOffsetY } = scene.getRelativeToViewportCoord(
Vector2.FromArray([moveOffsetX, moveOffsetY])
);
@@ -422,7 +424,7 @@ export class SelectionShapeExtension {
private _widgetMoving(moveOffsetX: number, moveOffsetY: number, cursor: CURSOR_TYPE) {
const scene = this._scene;
- const scrollXY = scene.getScrollXYByRelativeCoords(Vector2.FromArray([this._startOffsetX, this._startOffsetY]));
+ const scrollXY = scene.getVpScrollXYInfoByPosToVp(Vector2.FromArray([this._startOffsetX, this._startOffsetY]));
const { scaleX, scaleY } = scene.getAncestorScale();
@@ -520,7 +522,7 @@ export class SelectionShapeExtension {
const scene = this._scene;
- const relativeCoords = scene.getRelativeCoord(Vector2.FromArray([evtOffsetX, evtOffsetY]));
+ const relativeCoords = scene.getRelativeToViewportCoord(Vector2.FromArray([evtOffsetX, evtOffsetY]));
const { x: newEvtOffsetX, y: newEvtOffsetY } = relativeCoords;
@@ -567,7 +569,7 @@ export class SelectionShapeExtension {
this._scenePointerMoveSub = scene.onPointerMove$.subscribeEvent((moveEvt: IPointerEvent | IMouseEvent) => {
const { offsetX: moveOffsetX, offsetY: moveOffsetY } = moveEvt;
- const { x: newMoveOffsetX, y: newMoveOffsetY } = scene.getRelativeCoord(
+ const { x: newMoveOffsetX, y: newMoveOffsetY } = scene.getRelativeToViewportCoord(
Vector2.FromArray([moveOffsetX, moveOffsetY])
);
@@ -594,7 +596,7 @@ export class SelectionShapeExtension {
const { fillControl } = this._control;
fillControl.onPointerEnter$.subscribeEvent((evt: IPointerEvent | IMouseEvent) => {
- const permissionCheck = this._injector.get(ISelectionRenderService).interceptor.fetchThroughInterceptors(RANGE_FILL_PERMISSION_CHECK)(false, { x: evt.offsetX, y: evt.offsetY, skeleton: this._skeleton, scene: this._scene });
+ const permissionCheck = this._injector.get(ISheetSelectionRenderService).interceptor.fetchThroughInterceptors(RANGE_FILL_PERMISSION_CHECK)(false, { x: evt.offsetX, y: evt.offsetY, skeleton: this._skeleton, scene: this._scene });
if (!permissionCheck) {
return;
@@ -613,7 +615,7 @@ export class SelectionShapeExtension {
const scene = this._scene;
// const activeViewport = scene.getActiveViewportByCoord(Vector2.FromArray([moveOffsetX, moveOffsetY]));
// const scrollXY = activeViewport ? scene.getScrollXY(activeViewport) : { x: 0, y: 0 };
- const scrollXY = scene.getScrollXY(this._activeViewport);
+ const scrollXY = scene.getViewportScrollXY(this._activeViewport);
const { scaleX, scaleY } = scene.getAncestorScale();
@@ -627,7 +629,7 @@ export class SelectionShapeExtension {
const { row, column } = moveActualSelection;
- const moveRelativeCoords = scene.getRelativeCoord(Vector2.FromArray([moveOffsetX, moveOffsetY]));
+ const moveRelativeCoords = scene.getRelativeToViewportCoord(Vector2.FromArray([moveOffsetX, moveOffsetY]));
const maxRow = this._skeleton.getRowCount() - 1;
@@ -757,7 +759,7 @@ export class SelectionShapeExtension {
const scene = this._scene;
- const relativeCoords = scene.getRelativeCoord(Vector2.FromArray([evtOffsetX, evtOffsetY]));
+ const relativeCoords = scene.getRelativeToViewportCoord(Vector2.FromArray([evtOffsetX, evtOffsetY]));
const { x: newEvtOffsetX, y: newEvtOffsetY } = relativeCoords;
@@ -834,13 +836,13 @@ export class SelectionShapeExtension {
const { offsetX: moveOffsetX, offsetY: moveOffsetY } = moveEvt;
const currentViewport = scene.getActiveViewportByCoord(Vector2.FromArray([moveOffsetX, moveOffsetY]));
- const permissionCheck = this._injector.get(ISelectionRenderService).interceptor.fetchThroughInterceptors(RANGE_FILL_PERMISSION_CHECK)(false, { x: evt.offsetX, y: evt.offsetY, skeleton: this._skeleton, scene: this._scene });
+ const permissionCheck = this._injector.get(ISheetSelectionRenderService).interceptor.fetchThroughInterceptors(RANGE_FILL_PERMISSION_CHECK)(false, { x: evt.offsetX, y: evt.offsetY, skeleton: this._skeleton, scene: this._scene });
if (!permissionCheck) {
return;
}
- const { x: newMoveOffsetX, y: newMoveOffsetY } = scene.getRelativeCoord(
+ const { x: newMoveOffsetX, y: newMoveOffsetY } = scene.getRelativeToViewportCoord(
Vector2.FromArray([moveOffsetX, moveOffsetY])
);
diff --git a/packages/sheets-ui/src/services/selection/selection-shape.ts b/packages/sheets-ui/src/services/selection/selection-shape.ts
index 401b083124..07c71319bf 100644
--- a/packages/sheets-ui/src/services/selection/selection-shape.ts
+++ b/packages/sheets-ui/src/services/selection/selection-shape.ts
@@ -121,9 +121,9 @@ export class SelectionControl extends Disposable {
private _dispose$ = new BehaviorSubject<SelectionControl>(this);
readonly dispose$ = this._dispose$.asObservable();
- readonly selectionMoving$ = new Subject<Nullable<IRangeWithCoord>>();
- readonly selectionMoved$ = new Subject<Nullable<IRangeWithCoord>>();
- readonly selectionScaling$ = new Subject<Nullable<IRangeWithCoord>>();
+ readonly selectionMoving$ = new Subject<IRangeWithCoord>();
+ readonly selectionMoved$ = new Subject<IRangeWithCoord>();
+ readonly selectionScaling$ = new Subject<IRangeWithCoord>();
readonly selectionScaled$ = new Subject<Nullable<IRangeWithCoord>>();
readonly selectionFilling$ = new Subject<Nullable<IRangeWithCoord>>();
@@ -306,14 +306,6 @@ export class SelectionControl extends Disposable {
this.bottomControl.evented = state;
}
- enableHeaderHighlight() {
- this._isHelperSelection = true;
- }
-
- disableHeaderHighlight() {
- this._isHeaderHighlight = false;
- }
-
refreshSelectionFilled(val: IRangeWithCoord) {
this._selectionFilled$.next(val);
}
@@ -343,7 +335,6 @@ export class SelectionControl extends Disposable {
columnHeaderHeight: number = 0,
style?: Nullable<ISelectionStyle>,
highlight?: Nullable<ISelectionCellWithMergeInfo>
- // rangeType?: RANGE_TYPE
) {
this._selectionModel.setValue(newSelectionRange, highlight);
if (style == null) {
diff --git a/packages/sheets-ui/src/services/selection/util.ts b/packages/sheets-ui/src/services/selection/util.ts
new file mode 100644
index 0000000000..4051b5b5e7
--- /dev/null
+++ b/packages/sheets-ui/src/services/selection/util.ts
@@ -0,0 +1,71 @@
+/**
+ * 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 { ISelectionCell, ISelectionCellWithMergeInfo } from '@univerjs/core';
+import type { SpreadsheetSkeleton } from '@univerjs/engine-render';
+import type { ISelectionWithCoordAndStyle, ISelectionWithStyle } from '@univerjs/sheets';
+import { attachRangeWithCoord } from '../sheet-skeleton-manager.service';
+
+// const nilSelection = {
+// startRow: -1,
+// startColumn: -1,
+// endRow: -1,
+// endColumn: -1,
+// startY: 0,
+// endY: 0,
+// startX: 0,
+// endX: 0,
+// rangeType: RANGE_TYPE.NORMAL,
+// }
+
+export function attachSelectionWithCoord(selection: ISelectionWithStyle, skeleton: SpreadsheetSkeleton) {
+ const { range, primary, style } = selection;
+ const rangeWithCoord = attachRangeWithCoord(skeleton, range);
+
+ return {
+ rangeWithCoord,
+ primaryWithCoord: primary ? attachPrimaryWithCoord(primary, skeleton) : null,
+ style,
+ } as ISelectionWithCoordAndStyle;
+}
+
+export function attachPrimaryWithCoord(primary: ISelectionCell, skeleton: SpreadsheetSkeleton): ISelectionCellWithMergeInfo {
+ const { actualRow, actualColumn, isMerged, isMergedMainCell, startRow, startColumn, endRow, endColumn } = primary;
+ const cellPosition = skeleton.getNoMergeCellPositionByIndex(actualRow, actualColumn);
+ const startCell = skeleton.getNoMergeCellPositionByIndex(startRow, startColumn);
+ const endCell = skeleton.getNoMergeCellPositionByIndex(endRow, endColumn);
+
+ return {
+ actualRow,
+ actualColumn,
+ isMerged,
+ isMergedMainCell,
+ startX: cellPosition.startX,
+ startY: cellPosition.startY,
+ endX: cellPosition.endX,
+ endY: cellPosition.endY,
+ mergeInfo: {
+ startRow,
+ startColumn,
+ endRow,
+ endColumn,
+ startY: startCell?.startY || 0,
+ endY: endCell?.endY || 0,
+ startX: startCell?.startX || 0,
+ endX: endCell?.endX || 0,
+ },
+ };
+}
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 a877f37efd..9e48966cce 100644
--- a/packages/sheets-ui/src/services/sheet-skeleton-manager.service.ts
+++ b/packages/sheets-ui/src/services/sheet-skeleton-manager.service.ts
@@ -14,7 +14,8 @@
* limitations under the License.
*/
-import { Disposable, type Nullable, type Workbook, type Worksheet } from '@univerjs/core';
+import type { IRange, IRangeWithCoord, Nullable, Workbook, Worksheet } from '@univerjs/core';
+import { Disposable } from '@univerjs/core';
import type { IRenderContext, IRenderModule } from '@univerjs/engine-render';
import { SpreadsheetSkeleton } from '@univerjs/engine-render';
import { Inject, Injector } from '@wendellhu/redi';
@@ -87,11 +88,14 @@ export class SheetSkeletonManagerService extends Disposable implements IRenderMo
return this.getCurrent()!.skeleton;
}
- /** @deprecated */
getCurrent(): Nullable<ISheetSkeletonManagerParam> {
return this._getSkeleton(this._currentSkeletonSearchParam);
}
+ getWorksheetSkeleton(sheetId: string): Nullable<ISheetSkeletonManagerParam> {
+ return this._getSkeleton({ sheetId });
+ }
+
/**
* unitId is never read?
*/
@@ -190,6 +194,12 @@ export class SheetSkeletonManagerService extends Disposable implements IRenderMo
}
}
+ /** @deprecated Use function `attachRangeWithCoord` instead. */
+ attachRangeWithCoord(range: IRange): Nullable<IRangeWithCoord> {
+ const skeleton = this.getCurrentSkeleton();
+ return attachRangeWithCoord(skeleton, range);
+ }
+
private _getSkeleton(searchParm: ISheetSkeletonManagerSearch): Nullable<ISheetSkeletonManagerParam> {
const item = this._sheetSkeletonParam.find((param) => param.sheetId === searchParm.sheetId);
if (item != null) {
@@ -212,3 +222,21 @@ export class SheetSkeletonManagerService extends Disposable implements IRenderMo
return spreadsheetSkeleton;
}
}
+
+export function attachRangeWithCoord(skeleton: SpreadsheetSkeleton, range: IRange): IRangeWithCoord {
+ const { startRow, startColumn, endRow, endColumn, rangeType } = range;
+ const startCell = skeleton.getNoMergeCellPositionByIndex(startRow, startColumn);
+ const endCell = skeleton.getNoMergeCellPositionByIndex(endRow, endColumn);
+
+ return {
+ startRow,
+ startColumn,
+ endRow,
+ endColumn,
+ rangeType,
+ startY: startCell?.startY || 0,
+ endY: endCell?.endY || 0,
+ startX: startCell?.startX || 0,
+ endX: endCell?.endX || 0,
+ };
+}
diff --git a/packages/sheets-ui/src/services/shortcut-experience.service.ts b/packages/sheets-ui/src/services/shortcut-experience.service.ts
index 2baf48612b..3f32a302d7 100644
--- a/packages/sheets-ui/src/services/shortcut-experience.service.ts
+++ b/packages/sheets-ui/src/services/shortcut-experience.service.ts
@@ -34,6 +34,8 @@ export interface IShortcutExperienceParam extends IShortcutExperienceSearch {
/**
* This service is prepared for shortcut experience optimization,
* including the combined use of enter and tab, the highlighting experience of formulas in the editor, and so on.
+ *
+ * @deprecated this class looks weired
*/
export class ShortcutExperienceService implements IDisposable {
private _current: Nullable<IShortcutExperienceSearch> = null;
diff --git a/packages/sheets-ui/src/services/utils/selection-util.ts b/packages/sheets-ui/src/services/utils/selection-util.ts
new file mode 100644
index 0000000000..42b0cb8a0f
--- /dev/null
+++ b/packages/sheets-ui/src/services/utils/selection-util.ts
@@ -0,0 +1,31 @@
+/**
+ * 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 { ThemeService } from '@univerjs/core';
+import type { ISelectionStyle } from '@univerjs/sheets';
+
+export function createCopyPasteSelectionStyle(
+ themeService: ThemeService
+): ISelectionStyle {
+ return {
+ strokeWidth: 1.5,
+ stroke: themeService.getCurrentTheme().primaryColor,
+ fill: 'rgba(178, 178, 178, 0.10)',
+ widgets: {},
+ hasAutoFill: false,
+ strokeDash: 8,
+ };
+}
diff --git a/packages/sheets-ui/src/sheets-ui-plugin.ts b/packages/sheets-ui/src/sheets-ui-plugin.ts
index 4cf882cfd0..82415217bd 100644
--- a/packages/sheets-ui/src/sheets-ui-plugin.ts
+++ b/packages/sheets-ui/src/sheets-ui-plugin.ts
@@ -34,7 +34,6 @@ import { HeaderMoveRenderController } from './controllers/render-controllers/hea
import { HeaderResizeRenderController } from './controllers/render-controllers/header-resize.render-controller';
import { HeaderUnhideRenderController } from './controllers/render-controllers/header-unhide.render-controller';
import { MarkSelectionRenderController } from './controllers/mark-selection.controller';
-import { SelectionRenderController } from './controllers/render-controllers/selection.render-controller';
import { SheetsRenderService } from './services/sheets-render.service';
import type { IUniverSheetsUIConfig } from './controllers/sheet-ui.controller';
import { DefaultSheetUiConfig, SheetUIController } from './controllers/sheet-ui.controller';
@@ -50,7 +49,7 @@ import { EditorBridgeService, IEditorBridgeService } from './services/editor-bri
import { FormatPainterService, IFormatPainterService } from './services/format-painter/format-painter.service';
import { IMarkSelectionService, MarkSelectionService } from './services/mark-selection/mark-selection.service';
import { ScrollManagerService } from './services/scroll-manager.service';
-import { ISelectionRenderService, SelectionRenderService } from './services/selection/selection-render.service';
+import { SheetSelectionRenderService } from './services/selection/selection-render.service';
import { ISheetBarService, SheetBarService } from './services/sheet-bar/sheet-bar.service';
import { SheetSkeletonManagerService } from './services/sheet-skeleton-manager.service';
import { ShortcutExperienceService } from './services/shortcut-experience.service';
@@ -82,8 +81,9 @@ import { SheetPermissionPanelModel } from './services/permission/sheet-permissio
import { SheetPermissionUserManagerService } from './services/permission/sheet-permission-user-list.service';
import { WorksheetProtectionRenderService } from './services/permission/worksheet-permission-render.service';
import { SheetPrintInterceptorService } from './services/print-interceptor.service';
-import { MoveRangeController } from './controllers/move-range.controller';
-import { SheetSkeletonRenderController } from './controllers/render-controllers/skeleton.render-controller';
+import { SheetsDefinedNameController } from './controllers/defined-name/defined-name.controller';
+import { MoveRangeRenderController } from './controllers/move-range.controller';
+import { ISheetSelectionRenderService } from './services/selection/base-selection-render.service';
@DependentOn(UniverSheetsPlugin)
export class UniverSheetsUIPlugin extends Plugin {
@@ -102,57 +102,55 @@ export class UniverSheetsUIPlugin extends Plugin {
}
override onStarting(injector: Injector): void {
- (
+ ([
+ // services
+ [ShortcutExperienceService],
+ [IEditorBridgeService, { useClass: EditorBridgeService }],
+ [ISheetClipboardService, { useClass: SheetClipboardService }],
+ [ISheetBarService, { useClass: SheetBarService }],
+ [IFormatPainterService, { useClass: FormatPainterService }],
+ [ICellEditorManagerService, { useClass: CellEditorManagerService }],
+ [IFormulaEditorManagerService, { useClass: FormulaEditorManagerService }],
+ [IAutoFillService, { useClass: AutoFillService }],
+ [SheetPrintInterceptorService],
+
+ [ScrollManagerService],
+ // This would be removed from global injector and moved into RenderUnit provider.
+ // [SheetSkeletonManagerService],
+ [IStatusBarService, { useClass: StatusBarService }],
+ [IMarkSelectionService, { useClass: MarkSelectionService }],
+ [HoverManagerService],
+ [DragManagerService],
+ [SheetCanvasPopManagerService],
+ [CellAlertManagerService],
+
+ // controllers
+ [ActiveWorksheetController],
+ [AutoHeightController],
+ [FormulaEditorController],
+ [HeaderFreezeRenderController],
+ [SheetClipboardController],
+ [SheetsRenderService],
[
- // services
- [ShortcutExperienceService],
- [IEditorBridgeService, { useClass: EditorBridgeService }],
- [ISheetClipboardService, { useClass: SheetClipboardService }],
- [ISheetBarService, { useClass: SheetBarService }],
- [IFormatPainterService, { useClass: FormatPainterService }],
- [ICellEditorManagerService, { useClass: CellEditorManagerService }],
- [IFormulaEditorManagerService, { useClass: FormulaEditorManagerService }],
- [IAutoFillService, { useClass: AutoFillService }],
- [SheetPrintInterceptorService],
-
- [ScrollManagerService],
- // This would be removed from global injector and moved into RenderUnit provider.
- // [SheetSkeletonManagerService],
- [ISelectionRenderService, { useClass: SelectionRenderService }],
- [IStatusBarService, { useClass: StatusBarService }],
- [IMarkSelectionService, { useClass: MarkSelectionService }],
- [HoverManagerService],
- [DragManagerService],
- [SheetCanvasPopManagerService],
- [CellAlertManagerService],
-
- // controllers
- [ActiveWorksheetController],
- [AutoHeightController],
- [FormulaEditorController],
- [HeaderFreezeRenderController],
- [SheetClipboardController],
- [SheetsRenderService],
- [
- SheetUIController,
- {
- useFactory: () => this._injector.createInstance(SheetUIController, this._config),
- },
- ],
- [StatusBarController],
- [AutoFillController],
- [FormatPainterController],
-
- // permission
- [SheetPermissionPanelModel],
- [SheetPermissionUserManagerService],
- [WorksheetProtectionRenderService],
- [SheetPermissionInterceptorClipboardController],
- [SheetPermissionInterceptorBaseController],
- [SheetPermissionInitController],
- [MoveRangeController],
-
- ] as Dependency[]
+ SheetUIController,
+ {
+ useFactory: () => this._injector.createInstance(SheetUIController, this._config),
+ },
+ ],
+ [StatusBarController],
+ [AutoFillController],
+ [FormatPainterController],
+ [SheetsDefinedNameController],
+
+ // permission
+ [SheetPermissionPanelModel],
+ [SheetPermissionUserManagerService],
+ [WorksheetProtectionRenderService],
+ [SheetPermissionInterceptorClipboardController],
+ [SheetPermissionInterceptorBaseController],
+ [SheetPermissionInitController],
+ // [MoveRangeController],
+ ] as Dependency[]
).forEach((d) => injector.add(d));
this._injector.add(
@@ -177,10 +175,10 @@ export class UniverSheetsUIPlugin extends Plugin {
private _registerRenderBasics(): void {
([
- SheetSkeletonManagerService,
- // SelectionRenderService,// still can not get renderContext
- SheetRenderController,
- ]).forEach((m) => {
+ [SheetSkeletonManagerService],
+ [SheetRenderController],
+ [ISheetSelectionRenderService, { useClass: SheetSelectionRenderService }],
+ ] as Dependency[]).forEach((m) => {
this.disposeWithMe(this._renderManagerService.registerRenderModule(UniverInstanceType.UNIVER_SHEET, m));
});
}
@@ -189,42 +187,37 @@ export class UniverSheetsUIPlugin extends Plugin {
// a correct skeleton when they get loaded.
private _registerRenderModules(): void {
([
- // https://github.com/dream-num/univer-pro/issues/669
- // HeaderMoveRenderController(HMRC) must be initialized before SelectionRenderController(SRC).
- // Before HMRC expected selections remain unchanged when user clicks on the header. If we don't initialize HMRC before SRC,
- // the selections will be changed by SRC first. Maybe we should merge row/col header related render controllers to one class.
- HeaderMoveRenderController,
- SelectionRenderController,
- HeaderFreezeRenderController,
- HeaderUnhideRenderController,
- HeaderResizeRenderController,
+ [HeaderMoveRenderController],
+ [HeaderFreezeRenderController],
+ [HeaderUnhideRenderController],
+ [HeaderResizeRenderController],
+
// Caution: ScrollRenderController should placed before ZoomRenderController
- // because ZoomRenderController would change scrollInfo in currentSkeletonBefore$
- // currentSkeletonBefore$ --> ZoomRenderController ---> viewport.resize --> setScrollInfo, but ScrollRenderController needs scrollInfo
- SheetsScrollRenderController,
- SheetsZoomRenderController,
- FormatPainterRenderController,
- HeaderMenuRenderController,
- CellAlertRenderController,
- ForceStringAlertRenderController,
- MarkSelectionRenderController,
- HoverRenderController,
- DragRenderController,
- ForceStringRenderController,
- CellCustomRenderController,
- SheetContextMenuRenderController,
+ // because ZoomRenderController ---> viewport.resize --> setScrollInfo, but ScrollRenderController needs scrollInfo
+ [SheetsScrollRenderController],
+ [SheetsZoomRenderController],
+
+ [FormatPainterRenderController],
+ [HeaderMenuRenderController],
+ [CellAlertRenderController],
+ [ForceStringAlertRenderController],
+ [MarkSelectionRenderController],
+ [HoverRenderController],
+ [DragRenderController],
+ [ForceStringRenderController],
+ [CellCustomRenderController],
+ [SheetContextMenuRenderController],
+ [MoveRangeRenderController],
// editor
- EditorBridgeRenderController,
- EditingRenderController,
+ [EditorBridgeRenderController],
+ [EditingRenderController],
// permission
- SheetPermissionInterceptorCanvasRenderController,
- SheetPermissionInterceptorFormulaRenderController,
- SheetPermissionRenderController,
-
- SheetSkeletonRenderController,
- ]).forEach((m) => {
+ [SheetPermissionInterceptorCanvasRenderController],
+ [SheetPermissionInterceptorFormulaRenderController],
+ [SheetPermissionRenderController],
+ ] as Dependency[]).forEach((m) => {
this.disposeWithMe(this._renderManagerService.registerRenderModule(UniverInstanceType.UNIVER_SHEET, m));
});
}
diff --git a/packages/sheets-ui/src/views/defined-name/DefinedNameContainer.tsx b/packages/sheets-ui/src/views/defined-name/DefinedNameContainer.tsx
index 53f6e8bceb..13e87a9655 100644
--- a/packages/sheets-ui/src/views/defined-name/DefinedNameContainer.tsx
+++ b/packages/sheets-ui/src/views/defined-name/DefinedNameContainer.tsx
@@ -23,7 +23,7 @@ import { CheckMarkSingle, DeleteSingle, IncreaseSingle } from '@univerjs/icons';
import type { IDefinedNamesServiceParam } from '@univerjs/engine-formula';
import { IDefinedNamesService, serializeRangeWithSheet } from '@univerjs/engine-formula';
import clsx from 'clsx';
-import { InsertDefinedNameCommand, RemoveDefinedNameCommand, SelectionManagerService, SetDefinedNameCommand } from '@univerjs/sheets';
+import { InsertDefinedNameCommand, RemoveDefinedNameCommand, SetDefinedNameCommand, SheetsSelectionsService } from '@univerjs/sheets';
import { Confirm, Tooltip } from '@univerjs/design';
import styles from './index.module.less';
import { DefinedNameInput } from './DefinedNameInput';
@@ -35,7 +35,7 @@ export const DefinedNameContainer = () => {
const workbook = univerInstanceService.getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET)!;
const localeService = useDependency(LocaleService);
const definedNamesService = useDependency(IDefinedNamesService);
- const selectionManagerService = useDependency(SelectionManagerService);
+ const selectionManagerService = useDependency(SheetsSelectionsService);
if (workbook == null) {
return;
@@ -123,7 +123,7 @@ export const DefinedNameContainer = () => {
return '';
}
- const selections = selectionManagerService.getSelections();
+ const selections = selectionManagerService.getCurrentSelections();
if (selections == null) {
return '';
}
diff --git a/packages/sheets-ui/src/views/formula-bar/FormulaBar.tsx b/packages/sheets-ui/src/views/formula-bar/FormulaBar.tsx
index 3f15855670..6d68ada3c3 100644
--- a/packages/sheets-ui/src/views/formula-bar/FormulaBar.tsx
+++ b/packages/sheets-ui/src/views/formula-bar/FormulaBar.tsx
@@ -23,7 +23,7 @@ import { useDependency } from '@wendellhu/redi/react-bindings';
import clsx from 'clsx';
import React, { useEffect, useLayoutEffect, useState } from 'react';
-import { RangeProtectionPermissionEditPoint, RangeProtectionRuleModel, SelectionManagerService, WorkbookEditablePermission, WorksheetEditPermission, WorksheetProtectionRuleModel, WorksheetSetCellValuePermission } from '@univerjs/sheets';
+import { RangeProtectionPermissionEditPoint, RangeProtectionRuleModel, SheetsSelectionsService, WorkbookEditablePermission, WorksheetEditPermission, WorksheetProtectionRuleModel, WorksheetSetCellValuePermission } from '@univerjs/sheets';
import { merge } from 'rxjs';
import { IFormulaEditorManagerService } from '../../services/editor/formula-editor-manager.service';
import { IEditorBridgeService } from '../../services/editor-bridge.service';
@@ -46,7 +46,7 @@ export function FormulaBar() {
const progressBarColor = themeService.getCurrentTheme().primaryColor;
const [disable, setDisable] = useState<boolean>(false);
const univerInstanceService = useDependency(IUniverInstanceService);
- const selectionManager = useDependency(SelectionManagerService);
+ const selectionManager = useDependency(SheetsSelectionsService);
const worksheetProtectionRuleModel = useDependency(WorksheetProtectionRuleModel);
const rangeProtectionRuleModel = useDependency(RangeProtectionRuleModel);
const permissionService = useDependency(IPermissionService);
@@ -62,7 +62,7 @@ export function FormulaBar() {
const worksheet = workbook.getActiveSheet();
if (!worksheet) return;
const subUnitId = worksheet.getSheetId();
- const range = selectionManager.getLast()?.range;
+ const range = selectionManager.getCurrentLastSelection()?.range;
if (!range) return;
const workbookEditPermission = permissionService.getPermissionPoint(new WorkbookEditablePermission(unitId).id)?.value;
const worksheetSetCellValuePermission = permissionService.getPermissionPoint(new WorksheetSetCellValuePermission(unitId, subUnitId).id)?.value;
@@ -73,7 +73,7 @@ export function FormulaBar() {
return;
}
- const selectionRanges = selectionManager.getSelections()?.map((selection) => selection.range);
+ const selectionRanges = selectionManager.getCurrentSelections()?.map((selection) => selection.range);
const permissionList = rangeProtectionRuleModel.getSubunitRuleList(unitId, subUnitId).filter((rule) => {
return rule.ranges.some((r) => {
return selectionRanges?.some((selectionRange) => {
diff --git a/packages/sheets-ui/src/views/operate-container/AutoFillPopupMenu.tsx b/packages/sheets-ui/src/views/operate-container/AutoFillPopupMenu.tsx
index 0fde6ddd1d..979a27191c 100644
--- a/packages/sheets-ui/src/views/operate-container/AutoFillPopupMenu.tsx
+++ b/packages/sheets-ui/src/views/operate-container/AutoFillPopupMenu.tsx
@@ -28,9 +28,9 @@ import { SetScrollOperation } from '../../commands/operations/scroll.operation';
import { getSheetObject } from '../../controllers/utils/component-tools';
import { IAutoFillService } from '../../services/auto-fill/auto-fill.service';
import { APPLY_TYPE } from '../../services/auto-fill/type';
-import { ISelectionRenderService } from '../../services/selection/selection-render.service';
import { SheetSkeletonManagerService } from '../../services/sheet-skeleton-manager.service';
import { useActiveWorkbook } from '../../components/hook';
+import { ISheetSelectionRenderService } from '../../services/selection/base-selection-render.service';
import styles from './index.module.less';
export interface IAnchorPoint {
@@ -54,7 +54,6 @@ export const AutoFillPopupMenu: React.FC<{}> = () => {
const commandService = useDependency(ICommandService);
const univerInstanceService = useDependency(IUniverInstanceService);
const renderManagerService = useDependency(IRenderManagerService);
- const selectionRenderService = useDependency(ISelectionRenderService);
const autoFillService = useDependency(IAutoFillService);
const localeService = useDependency(LocaleService);
const [menu, setMenu] = useState<IAutoFillPopupMenuItem[]>([]);
@@ -63,12 +62,16 @@ export const AutoFillPopupMenu: React.FC<{}> = () => {
const [selected, setSelected] = useState<APPLY_TYPE>(APPLY_TYPE.SERIES);
const [isHovered, setHovered] = useState(false);
const workbook = useActiveWorkbook();
- const sheetSkeletonManagerService = useMemo(() => {
+ const { sheetSkeletonManagerService, selectionRenderService } = useMemo(() => {
if (workbook) {
- return renderManagerService.getRenderById(workbook.getUnitId())?.with(SheetSkeletonManagerService);
+ const ru = renderManagerService.getRenderById(workbook.getUnitId());
+ return {
+ sheetSkeletonManagerService: ru?.with(SheetSkeletonManagerService),
+ selectionRenderService: ru?.with(ISheetSelectionRenderService),
+ };
}
- return null;
+ return { sheetSkeletonManagerService: null, selectionRenderService: null };
}, [workbook, renderManagerService]);
const handleMouseEnter = () => {
@@ -150,14 +153,14 @@ export const AutoFillPopupMenu: React.FC<{}> = () => {
}
const sheetObject = getSheetObject(univerInstanceService, renderManagerService);
- if (!sheetObject) return null;
+ if (!sheetObject || !selectionRenderService) return null;
const { scene } = sheetObject;
const skeleton = sheetSkeletonManagerService?.getCurrentSkeleton();
const viewport = selectionRenderService.getViewPort();
const scaleX = scene?.scaleX;
const scaleY = scene?.scaleY;
- const scrollXY = scene?.getScrollXY(viewport);
+ const scrollXY = scene?.getViewportScrollXY(viewport);
if (!scaleX || !scene || !scaleX || !scaleY || !scrollXY) return null;
const x = skeleton?.getNoMergeCellPositionByIndex(anchor.row, anchor.col).endX || 0;
const y = skeleton?.getNoMergeCellPositionByIndex(anchor.row, anchor.col).endY || 0;
diff --git a/packages/sheets-ui/src/views/permission/panel-detail/index.tsx b/packages/sheets-ui/src/views/permission/panel-detail/index.tsx
index 67afb6472c..c81c5b1ef6 100644
--- a/packages/sheets-ui/src/views/permission/panel-detail/index.tsx
+++ b/packages/sheets-ui/src/views/permission/panel-detail/index.tsx
@@ -20,7 +20,7 @@ import { useDependency } from '@wendellhu/redi/react-bindings';
import type { IRange, Workbook } from '@univerjs/core';
import { createInternalEditorID, IAuthzIoService, isValidRange, IUniverInstanceService, LocaleService, RANGE_TYPE, Rectangle, UniverInstanceType, UserManagerService } from '@univerjs/core';
import { IDialogService, ISidebarService, RangeSelector, useObservable } from '@univerjs/ui';
-import { RangeProtectionRuleModel, SelectionManagerService, setEndForRange, WorksheetProtectionRuleModel } from '@univerjs/sheets';
+import { RangeProtectionRuleModel, setEndForRange, SheetsSelectionsService, WorksheetProtectionRuleModel } from '@univerjs/sheets';
import { serializeRange } from '@univerjs/engine-formula';
import type { ICollaborator, IUser } from '@univerjs/protocol';
import { UnitObject, UnitRole } from '@univerjs/protocol';
@@ -36,7 +36,7 @@ export const SheetPermissionPanelDetail = ({ fromSheetBar }: { fromSheetBar: boo
const localeService = useDependency(LocaleService);
const dialogService = useDependency(IDialogService);
const univerInstanceService = useDependency(IUniverInstanceService);
- const selectionManagerService = useDependency(SelectionManagerService);
+ const selectionManagerService = useDependency(SheetsSelectionsService);
const sheetPermissionPanelModel = useDependency(SheetPermissionPanelModel);
const activeRule = useObservable(sheetPermissionPanelModel.rule$, sheetPermissionPanelModel.rule);
const userManagerService = useDependency(UserManagerService);
@@ -143,8 +143,8 @@ export const SheetPermissionPanelDetail = ({ fromSheetBar }: { fromSheetBar: boo
return;
}
if (fromSheetBar) {
- selectionManagerService.clear();
- selectionManagerService.add([
+ selectionManagerService.clearCurrentSelections();
+ selectionManagerService.addSelections([
{
primary: null,
style: null,
@@ -158,7 +158,7 @@ export const SheetPermissionPanelDetail = ({ fromSheetBar }: { fromSheetBar: boo
},
]);
}
- const ranges = selectionManagerService.getSelectionRanges() ?? [];
+ const ranges = selectionManagerService.getCurrentSelections()?.map((s) => s.range) ?? [];
const rangeErrorString = checkRangeValid(ranges);
sheetPermissionPanelModel.setRangeErrorMsg(rangeErrorString);
const rangeStr = ranges?.length
diff --git a/packages/sheets-ui/src/views/sheet-bar/sheet-bar-tabs/SheetBarTabs.tsx b/packages/sheets-ui/src/views/sheet-bar/sheet-bar-tabs/SheetBarTabs.tsx
index 74cb121992..896081ba96 100644
--- a/packages/sheets-ui/src/views/sheet-bar/sheet-bar-tabs/SheetBarTabs.tsx
+++ b/packages/sheets-ui/src/views/sheet-bar/sheet-bar-tabs/SheetBarTabs.tsx
@@ -15,7 +15,7 @@
*/
import type { ICommandInfo, Workbook } from '@univerjs/core';
-import { ICommandService, IConfigService, IPermissionService, IUniverInstanceService, LocaleService, nameCharacterCheck, UniverInstanceType } from '@univerjs/core';
+import { ICommandService, IPermissionService, IUniverInstanceService, LocaleService, nameCharacterCheck, UniverInstanceType } from '@univerjs/core';
import { Dropdown } from '@univerjs/design';
import {
InsertSheetMutation,
@@ -32,7 +32,7 @@ import {
WorkbookRenameSheetPermission,
WorksheetProtectionRuleModel,
} from '@univerjs/sheets';
-import { IConfirmService, Menu, UI_CONFIG_KEY, useObservable } from '@univerjs/ui';
+import { IConfirmService, Menu, useObservable } from '@univerjs/ui';
import { useDependency } from '@wendellhu/redi/react-bindings';
import React, { useCallback, useEffect, useRef, useState } from 'react';
@@ -40,7 +40,6 @@ import { LockSingle } from '@univerjs/icons';
import { merge } from 'rxjs';
import { Quantity } from '@wendellhu/redi';
import { SheetMenuPosition } from '../../../controllers/menu/menu';
-import { ISelectionRenderService } from '../../../services/selection/selection-render.service';
import { ISheetBarService } from '../../../services/sheet-bar/sheet-bar.service';
import { IEditorBridgeService } from '../../../services/editor-bridge.service';
import { useActiveWorkbook } from '../../../components/hook';
@@ -64,7 +63,6 @@ export function SheetBarTabs() {
const sheetBarService = useDependency(ISheetBarService);
const localeService = useDependency(LocaleService);
const confirmService = useDependency(IConfirmService);
- const selectionRenderService = useDependency(ISelectionRenderService);
const editorBridgeService = useDependency(IEditorBridgeService, Quantity.OPTIONAL);
const worksheetProtectionRuleModel = useDependency(WorksheetProtectionRuleModel);
const rangeProtectionRuleModel = useDependency(RangeProtectionRuleModel);
@@ -73,11 +71,6 @@ export function SheetBarTabs() {
const workbook = useActiveWorkbook()!;
const permissionService = useDependency(IPermissionService);
- const configService = useDependency(IConfigService);
- const uiConfigs = configService.getConfig<{ contextMenu?: boolean }>(UI_CONFIG_KEY);
-
- const contextMenu = uiConfigs?.contextMenu ?? true;
-
const updateSheetItems = useCallback(() => {
const currentSubUnitId = workbook.getActiveSheet()?.getSheetId() || '';
setActiveKey(currentSubUnitId);
@@ -293,7 +286,8 @@ export function SheetBarTabs() {
};
const focusTabEditor = () => {
- selectionRenderService.endSelection();
+ // FIXME@Dushusir: too strongly coupled
+ // selectionRenderService.endSelection();
// There is an asynchronous operation in endSelection, which will trigger blur immediately after focus, so it must be wrapped with setTimeout.
setTimeout(() => {
@@ -392,8 +386,6 @@ export function SheetBarTabs() {
};
const onVisibleChange = (visible: boolean) => {
- if (!contextMenu) return;
-
if (editorBridgeService?.isForceKeepVisible()) {
return;
}
@@ -417,7 +409,6 @@ export function SheetBarTabs() {
visible={visible}
align={{ offset }}
trigger={['contextMenu']}
- disabled={!contextMenu}
overlay={(
<Menu
menuType={SheetMenuPosition.SHEET_BAR}
diff --git a/packages/sheets/src/basics/utils.ts b/packages/sheets/src/basics/utils.ts
index fa3c711efb..769fdc91ab 100644
--- a/packages/sheets/src/basics/utils.ts
+++ b/packages/sheets/src/basics/utils.ts
@@ -14,8 +14,8 @@
* limitations under the License.
*/
-import type { ICellData, IObjectMatrixPrimitiveType, IRange, Nullable, Worksheet } from '@univerjs/core';
-import { ObjectMatrix } from '@univerjs/core';
+import type { ICellData, IObjectMatrixPrimitiveType, IRange, Nullable, UniverInstanceService, Workbook, Worksheet } from '@univerjs/core';
+import { ObjectMatrix, UniverInstanceType } from '@univerjs/core';
import type { IExpandParams } from '../commands/commands/utils/selection-utils';
export const groupByKey = <T = Record<string, unknown>>(arr: T[], key: string, blankKey = '') => {
@@ -220,3 +220,8 @@ export function generateNullCellStyle(ranges: IRange[]): IObjectMatrixPrimitiveT
return cellValue.clone();
}
+export function getActiveWorksheet(instanceService: UniverInstanceService): [Nullable<Workbook>, Nullable<Worksheet>] {
+ const workbook = instanceService.getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET);
+ const worksheet = workbook?.getActiveSheet();
+ return [workbook, worksheet];
+}
diff --git a/packages/sheets/src/commands/commands/__tests__/clear-selection.command.spec.ts b/packages/sheets/src/commands/commands/__tests__/clear-selection.command.spec.ts
index ecb67dd2cb..30746987fa 100644
--- a/packages/sheets/src/commands/commands/__tests__/clear-selection.command.spec.ts
+++ b/packages/sheets/src/commands/commands/__tests__/clear-selection.command.spec.ts
@@ -28,7 +28,7 @@ import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import { MergeCellController } from '../../../controllers/merge-cell.controller';
import { RefRangeService } from '../../../services/ref-range/ref-range.service';
-import { NORMAL_SELECTION_PLUGIN_NAME, SelectionManagerService } from '../../../services/selection-manager.service';
+import { SheetsSelectionsService } from '../../../services/selections/selection-manager.service';
import { AddWorksheetMergeMutation } from '../../mutations/add-worksheet-merge.mutation';
import { RemoveWorksheetMergeMutation } from '../../mutations/remove-worksheet-merge.mutation';
import { SetRangeValuesMutation } from '../../mutations/set-range-values.mutation';
@@ -69,13 +69,8 @@ describe('Test clear selection content commands', () => {
describe('clear selection contents', () => {
describe('correct situations', () => {
it('will clear selection content when there is a selected range', async () => {
- const selectionManager = get(SelectionManagerService);
- selectionManager.setCurrentSelection({
- pluginName: NORMAL_SELECTION_PLUGIN_NAME,
- unitId: 'test',
- sheetId: 'sheet1',
- });
- selectionManager.add([
+ const selectionManager = get(SheetsSelectionsService);
+ selectionManager.addSelections([
{
range: { startRow: 0, startColumn: 0, endColumn: 0, endRow: 0, rangeType: RANGE_TYPE.NORMAL },
primary: null,
@@ -118,13 +113,9 @@ describe('Test clear selection content commands', () => {
describe('clear selection formats', () => {
describe('correct situations', () => {
it('will clear selection format when there is a selected range', async () => {
- const selectionManager = get(SelectionManagerService);
- selectionManager.setCurrentSelection({
- pluginName: NORMAL_SELECTION_PLUGIN_NAME,
- unitId: 'test',
- sheetId: 'sheet1',
- });
- selectionManager.add([
+ const selectionManager = get(SheetsSelectionsService);
+
+ selectionManager.addSelections([
{
range: { startRow: 0, startColumn: 0, endColumn: 0, endRow: 0, rangeType: RANGE_TYPE.NORMAL },
primary: null,
@@ -182,13 +173,8 @@ describe('Test clear selection content commands', () => {
});
});
it('clear formats with merged cells', async () => {
- const selectionManager = get(SelectionManagerService);
- selectionManager.setCurrentSelection({
- pluginName: NORMAL_SELECTION_PLUGIN_NAME,
- unitId: 'test',
- sheetId: 'sheet1',
- });
- selectionManager.add([
+ const selectionManager = get(SheetsSelectionsService);
+ selectionManager.addSelections([
{
range: { startRow: 0, startColumn: 0, endColumn: 1, endRow: 1, rangeType: RANGE_TYPE.NORMAL },
primary: null,
@@ -278,13 +264,8 @@ describe('Test clear selection content commands', () => {
describe('clear selection all', () => {
describe('correct situations', () => {
it('will clear selection all when there is a selected range', async () => {
- const selectionManager = get(SelectionManagerService);
- selectionManager.setCurrentSelection({
- pluginName: NORMAL_SELECTION_PLUGIN_NAME,
- unitId: 'test',
- sheetId: 'sheet1',
- });
- selectionManager.add([
+ const selectionManager = get(SheetsSelectionsService);
+ selectionManager.addSelections([
{
range: { startRow: 0, startColumn: 0, endColumn: 0, endRow: 0, rangeType: RANGE_TYPE.NORMAL },
primary: null,
@@ -334,13 +315,8 @@ describe('Test clear selection content commands', () => {
expect(getValue()).toStrictEqual({});
});
it('clear all with merged cells', async () => {
- const selectionManager = get(SelectionManagerService);
- selectionManager.setCurrentSelection({
- pluginName: NORMAL_SELECTION_PLUGIN_NAME,
- unitId: 'test',
- sheetId: 'sheet1',
- });
- selectionManager.add([
+ const selectionManager = get(SheetsSelectionsService);
+ selectionManager.addSelections([
{
range: { startRow: 0, startColumn: 0, endColumn: 1, endRow: 1, rangeType: RANGE_TYPE.NORMAL },
primary: null,
diff --git a/packages/sheets/src/commands/commands/__tests__/create-command-test-bed.ts b/packages/sheets/src/commands/commands/__tests__/create-command-test-bed.ts
index e8dc60c625..4e3fcf1379 100644
--- a/packages/sheets/src/commands/commands/__tests__/create-command-test-bed.ts
+++ b/packages/sheets/src/commands/commands/__tests__/create-command-test-bed.ts
@@ -33,7 +33,7 @@ import { WorkbookPermissionService } from '../../../services/permission/workbook
import { WorksheetPermissionService } from '../../../services/permission/worksheet-permission/worksheet-permission.service';
import enUS from '../../../locale/en-US';
import { BorderStyleManagerService } from '../../../services/border-style-manager.service';
-import { SelectionManagerService } from '../../../services/selection-manager.service';
+import { SheetsSelectionsService } from '../../../services/selections/selection-manager.service';
import { SheetInterceptorService } from '../../../services/sheet-interceptor/sheet-interceptor.service';
import { WorksheetProtectionPointModel, WorksheetProtectionRuleModel } from '../../../services/permission/worksheet-permission';
import { RangeProtectionRuleModel } from '../../../model/range-protection-rule.model';
@@ -102,7 +102,7 @@ export function createCommandTestBed(workbookData?: IWorkbookData, dependencies?
injector.add([RangeProtectionRuleModel]);
injector.add([WorkbookPermissionService]);
injector.add([WorksheetProtectionRuleModel]);
- injector.add([SelectionManagerService]);
+ injector.add([SheetsSelectionsService]);
injector.add([BorderStyleManagerService]);
injector.add([SheetInterceptorService]);
diff --git a/packages/sheets/src/commands/commands/__tests__/delete-range.command.spec.ts b/packages/sheets/src/commands/commands/__tests__/delete-range.command.spec.ts
index 37debe3dfe..2b003c3f8c 100644
--- a/packages/sheets/src/commands/commands/__tests__/delete-range.command.spec.ts
+++ b/packages/sheets/src/commands/commands/__tests__/delete-range.command.spec.ts
@@ -27,7 +27,7 @@ import {
import type { Injector } from '@wendellhu/redi';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
-import { NORMAL_SELECTION_PLUGIN_NAME, SelectionManagerService } from '../../../services/selection-manager.service';
+import { SheetsSelectionsService } from '../../../services/selections/selection-manager.service';
import { AddWorksheetMergeMutation } from '../../mutations/add-worksheet-merge.mutation';
import { InsertColMutation, InsertRowMutation } from '../../mutations/insert-row-col.mutation';
import { MoveRangeMutation } from '../../mutations/move-range.mutation';
@@ -156,7 +156,7 @@ describe('Test delete range commands', () => {
let univer: Univer;
let get: Injector['get'];
let commandService: ICommandService;
- let selectionManager: SelectionManagerService;
+ let selectionManager: SheetsSelectionsService;
let getValueByPosition: (
startRow: number,
startColumn: number,
@@ -200,12 +200,7 @@ describe('Test delete range commands', () => {
commandService.registerCommand(MoveRangeMutation);
commandService.registerCommand(SetRangeValuesMutation);
- selectionManager = get(SelectionManagerService);
- selectionManager.setCurrentSelection({
- pluginName: NORMAL_SELECTION_PLUGIN_NAME,
- unitId: 'test',
- sheetId: 'sheet1',
- });
+ selectionManager = get(SheetsSelectionsService);
getValueByPosition = (
startRow: number,
@@ -263,7 +258,7 @@ describe('Test delete range commands', () => {
describe('Delete range move left', () => {
describe('correct situations', () => {
it('will insert range when there is a selected range, no merged cells', async () => {
- selectionManager.replace([
+ selectionManager.setSelections([
{
range: { startRow: 0, startColumn: 0, endRow: 0, endColumn: 0, rangeType: RANGE_TYPE.NORMAL },
primary: null,
@@ -295,7 +290,7 @@ describe('Test delete range commands', () => {
describe('fault situations', () => {
it('will not apply when there is no selected ranges', async () => {
- selectionManager.clear();
+ selectionManager.clearCurrentSelections();
const result = await commandService.executeCommand(DeleteRangeMoveLeftCommand.id);
expect(result).toBeFalsy();
});
@@ -304,7 +299,7 @@ describe('Test delete range commands', () => {
describe('Delete range move up', () => {
describe('correct situations', () => {
it('will insert range when there is a selected range, no merged cells', async () => {
- selectionManager.replace([
+ selectionManager.setSelections([
{
range: { startRow: 0, startColumn: 0, endRow: 0, endColumn: 0, rangeType: RANGE_TYPE.NORMAL },
primary: null,
@@ -337,7 +332,7 @@ describe('Test delete range commands', () => {
describe('fault situations', () => {
it('will not apply when there is no selected ranges', async () => {
- selectionManager.clear();
+ selectionManager.clearCurrentSelections();
const result = await commandService.executeCommand(DeleteRangeMoveUpCommand.id);
expect(result).toBeFalsy();
});
diff --git a/packages/sheets/src/commands/commands/__tests__/insert-range.command.spec.ts b/packages/sheets/src/commands/commands/__tests__/insert-range.command.spec.ts
index 03c28cf7ff..6bf2a08f52 100644
--- a/packages/sheets/src/commands/commands/__tests__/insert-range.command.spec.ts
+++ b/packages/sheets/src/commands/commands/__tests__/insert-range.command.spec.ts
@@ -30,7 +30,7 @@ import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import { MergeCellController } from '../../../controllers/merge-cell.controller';
import { RefRangeService } from '../../../services/ref-range/ref-range.service';
-import { NORMAL_SELECTION_PLUGIN_NAME, SelectionManagerService } from '../../../services/selection-manager.service';
+import { SheetsSelectionsService } from '../../../services/selections/selection-manager.service';
import { AddWorksheetMergeMutation } from '../../mutations/add-worksheet-merge.mutation';
import { InsertColMutation, InsertRowMutation } from '../../mutations/insert-row-col.mutation';
import { MoveRangeMutation } from '../../mutations/move-range.mutation';
@@ -159,7 +159,7 @@ describe('Test insert range commands', () => {
let univer: Univer;
let get: Injector['get'];
let commandService: ICommandService;
- let selectionManager: SelectionManagerService;
+ let selectionManager: SheetsSelectionsService;
let deduplicateRanges: (ranges: Array<Nullable<IRange>>) => IRange[];
let getValueByPosition: (
startRow: number,
@@ -206,12 +206,7 @@ describe('Test insert range commands', () => {
commandService.registerCommand(SetRangeValuesMutation);
commandService.registerCommand(MoveRangeMutation);
- selectionManager = get(SelectionManagerService);
- selectionManager.setCurrentSelection({
- pluginName: NORMAL_SELECTION_PLUGIN_NAME,
- unitId: 'test',
- sheetId: 'sheet1',
- });
+ selectionManager = get(SheetsSelectionsService);
getValueByPosition = (
startRow: number,
@@ -284,7 +279,7 @@ describe('Test insert range commands', () => {
describe('Insert range move right', () => {
describe('correct situations', () => {
it('will insert range when there is a selected range, no merged cells', async () => {
- selectionManager.replace([
+ selectionManager.setSelections([
{
range: { startRow: 0, startColumn: 0, endRow: 0, endColumn: 0, rangeType: RANGE_TYPE.NORMAL },
primary: null,
@@ -317,7 +312,7 @@ describe('Test insert range commands', () => {
expect(await commandService.executeCommand(UndoCommand.id)).toBeTruthy();
});
it('will insert range when there is a selected range, with merged cells of 2 rows and 1 column, break merged cells on the right', async () => {
- selectionManager.replace([
+ selectionManager.setSelections([
{
range: { startRow: 0, startColumn: 2, endRow: 1, endColumn: 2, rangeType: RANGE_TYPE.NORMAL },
primary: null,
@@ -344,7 +339,7 @@ describe('Test insert range commands', () => {
expect(await commandService.executeCommand(UndoCommand.id)).toBeTruthy();
});
it('will insert range when there is a selected range, with merged cells of 3 rows and 1 column, will not break merged cells on the right', async () => {
- selectionManager.replace([
+ selectionManager.setSelections([
{
range: { startRow: 4, startColumn: 2, endRow: 6, endColumn: 2, rangeType: RANGE_TYPE.NORMAL },
primary: null,
@@ -389,7 +384,7 @@ describe('Test insert range commands', () => {
describe('fault situations', () => {
it('will not apply when there is no selected ranges', async () => {
- selectionManager.clear();
+ selectionManager.clearCurrentSelections();
const result = await commandService.executeCommand(InsertRangeMoveRightCommand.id);
expect(result).toBeFalsy();
});
@@ -398,7 +393,7 @@ describe('Test insert range commands', () => {
describe('Insert range move down', () => {
describe('correct situations', () => {
it('will insert range when there is a selected range, no merged cells', async () => {
- selectionManager.replace([
+ selectionManager.setSelections([
{
range: { startRow: 0, startColumn: 0, endRow: 0, endColumn: 0, rangeType: RANGE_TYPE.NORMAL },
primary: null,
@@ -433,7 +428,7 @@ describe('Test insert range commands', () => {
});
it('will insert range when there is a selected range, with merged cells of 1 row and 2 columns, break merged cells on the bottom', async () => {
- selectionManager.replace([
+ selectionManager.setSelections([
{
range: { startRow: 1, startColumn: 6, endRow: 1, endColumn: 7, rangeType: RANGE_TYPE.NORMAL },
primary: null,
@@ -465,7 +460,7 @@ describe('Test insert range commands', () => {
expect(await commandService.executeCommand(UndoCommand.id)).toBeTruthy();
});
it('will insert range when there is a selected range, with merged cells of 1 row and 3 columns, will not break merged cells on the bottom', async () => {
- selectionManager.replace([
+ selectionManager.setSelections([
{
range: { startRow: 1, startColumn: 9, endRow: 1, endColumn: 11, rangeType: RANGE_TYPE.NORMAL },
primary: null,
@@ -509,7 +504,7 @@ describe('Test insert range commands', () => {
describe('fault situations', () => {
it('will not apply when there is no selected ranges', async () => {
- selectionManager.clear();
+ selectionManager.clearCurrentSelections();
const result = await commandService.executeCommand(InsertRangeMoveDownCommand.id);
expect(result).toBeFalsy();
});
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 821cf0d0c4..34aacc2e28 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
@@ -30,7 +30,7 @@ import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import { MergeCellController } from '../../../controllers/merge-cell.controller';
import { RefRangeService } from '../../../services/ref-range/ref-range.service';
-import { NORMAL_SELECTION_PLUGIN_NAME, SelectionManagerService } from '../../../services/selection-manager.service';
+import { SheetsSelectionsService } from '../../../services/selections/selection-manager.service';
import { AddWorksheetMergeMutation } from '../../mutations/add-worksheet-merge.mutation';
import { InsertColMutation, InsertRowMutation } from '../../mutations/insert-row-col.mutation';
import { MoveRangeMutation } from '../../mutations/move-range.mutation';
@@ -83,20 +83,14 @@ describe('Test insert and remove rows cols commands', () => {
MoveRangeMutation,
SetRangeValuesMutation,
].forEach((c) => commandService.registerCommand(c));
- const selectionManagerService = get(SelectionManagerService);
- selectionManagerService.setCurrentSelection({
- pluginName: NORMAL_SELECTION_PLUGIN_NAME,
- unitId: 'test',
- sheetId: 'sheet1',
- });
});
afterEach(() => univer.dispose());
function selectRow(rowStart: number, rowEnd: number): void {
- const selectionManagerService = get(SelectionManagerService);
+ const selectionManagerService = get(SheetsSelectionsService);
const endColumn = getColCount() - 1;
- selectionManagerService.add([
+ selectionManagerService.addSelections([
{
range: { startRow: rowStart, startColumn: 0, endColumn, endRow: rowEnd, rangeType: RANGE_TYPE.ROW },
primary: {
@@ -115,9 +109,9 @@ describe('Test insert and remove rows cols commands', () => {
}
function selectColumn(columnStart: number, columnEnd: number): void {
- const selectionManagerService = get(SelectionManagerService);
+ const selectionManagerService = get(SheetsSelectionsService);
const endRow = getRowCount() - 1;
- selectionManagerService.add([
+ selectionManagerService.addSelections([
{
range: {
startRow: 0,
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 59a5f2add8..920fa8cfb1 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
@@ -21,7 +21,6 @@ import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import { MergeCellController } from '../../../controllers/merge-cell.controller';
import { RefRangeService } from '../../../services/ref-range/ref-range.service';
-import { NORMAL_SELECTION_PLUGIN_NAME, SelectionManagerService } from '../../../services/selection-manager.service';
import { AddWorksheetMergeMutation } from '../../mutations/add-worksheet-merge.mutation';
import { MoveRangeMutation } from '../../mutations/move-range.mutation';
import { RemoveWorksheetMergeMutation } from '../../mutations/remove-worksheet-merge.mutation';
@@ -50,12 +49,6 @@ describe('Test move range commands', () => {
MoveRangeMutation,
SetSelectionsOperation,
].forEach((c) => commandService.registerCommand(c));
- const selectionManagerService = get(SelectionManagerService);
- selectionManagerService.setCurrentSelection({
- pluginName: NORMAL_SELECTION_PLUGIN_NAME,
- unitId: 'test',
- sheetId: 'sheet1',
- });
});
afterEach(() => univer.dispose());
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 4954de419f..ce25cc09e4 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
@@ -31,7 +31,7 @@ import { beforeEach, describe, expect, it } from 'vitest';
import { MergeCellController } from '../../../controllers/merge-cell.controller';
import { RefRangeService } from '../../../services/ref-range/ref-range.service';
-import { NORMAL_SELECTION_PLUGIN_NAME, SelectionManagerService } from '../../../services/selection-manager.service';
+import { SheetsSelectionsService } from '../../../services/selections/selection-manager.service';
import { AddWorksheetMergeMutation } from '../../mutations/add-worksheet-merge.mutation';
import { MoveColsMutation, MoveRowsMutation } from '../../mutations/move-rows-cols.mutation';
import { RemoveWorksheetMergeMutation } from '../../mutations/remove-worksheet-merge.mutation';
@@ -62,18 +62,12 @@ describe('Test move rows cols', () => {
SetSelectionsOperation,
].forEach((c) => commandService.registerCommand(c));
get(MergeCellController);
- const selectionManagerService = get(SelectionManagerService);
- selectionManagerService.setCurrentSelection({
- pluginName: NORMAL_SELECTION_PLUGIN_NAME,
- unitId: 'test',
- sheetId: 'sheet1',
- });
});
function selectRow(rowStart: number, rowEnd: number): void {
- const selectionManagerService = get(SelectionManagerService);
+ const selectionManagerService = get(SheetsSelectionsService);
const endColumn = getColCount() - 1;
- selectionManagerService.add([
+ selectionManagerService.addSelections([
{
range: { startRow: rowStart, startColumn: 0, endColumn, endRow: rowEnd, rangeType: RANGE_TYPE.ROW },
primary: {
@@ -92,9 +86,9 @@ describe('Test move rows cols', () => {
}
function selectColumn(columnStart: number, columnEnd: number): void {
- const selectionManagerService = get(SelectionManagerService);
+ const selectionManagerService = get(SheetsSelectionsService);
const endRow = getRowCount() - 1;
- selectionManagerService.add([
+ selectionManagerService.addSelections([
{
range: {
startRow: 0,
@@ -161,8 +155,8 @@ describe('Test move rows cols', () => {
}
function getCurrentSelection(): IRange {
- const selectionManagerService = get(SelectionManagerService);
- const currentSelection = selectionManagerService.getSelections();
+ const selectionManagerService = get(SheetsSelectionsService);
+ const currentSelection = selectionManagerService.getCurrentSelections();
if (!currentSelection) {
throw new Error('No current selection');
}
diff --git a/packages/sheets/src/commands/commands/__tests__/remove-rows-cols.command.spec.ts b/packages/sheets/src/commands/commands/__tests__/remove-rows-cols.command.spec.ts
index 38d96d9210..e84c40ab8f 100644
--- a/packages/sheets/src/commands/commands/__tests__/remove-rows-cols.command.spec.ts
+++ b/packages/sheets/src/commands/commands/__tests__/remove-rows-cols.command.spec.ts
@@ -30,7 +30,7 @@ import { beforeEach, describe, expect, it } from 'vitest';
import { MergeCellController } from '../../../controllers/merge-cell.controller';
import { RefRangeService } from '../../../services/ref-range/ref-range.service';
-import { NORMAL_SELECTION_PLUGIN_NAME, SelectionManagerService } from '../../../services/selection-manager.service';
+import { SheetsSelectionsService } from '../../../services/selections/selection-manager.service';
import { SetSelectionsOperation } from '../../operations/selection.operation';
import type { IRemoveRowColCommandParams } from '../remove-row-col.command';
import { RemoveColCommand, RemoveRowCommand } from '../remove-row-col.command';
@@ -62,18 +62,12 @@ describe('Test remove rows cols', () => {
SetRangeValuesMutation,
].forEach((c) => commandService.registerCommand(c));
get(MergeCellController);
- const selectionManagerService = get(SelectionManagerService);
- selectionManagerService.setCurrentSelection({
- pluginName: NORMAL_SELECTION_PLUGIN_NAME,
- unitId: 'test',
- sheetId: 'sheet1',
- });
});
function selectRow(rowStart: number, rowEnd: number): void {
- const selectionManagerService = get(SelectionManagerService);
+ const selectionManagerService = get(SheetsSelectionsService);
const endColumn = getColCount() - 1;
- selectionManagerService.add([
+ selectionManagerService.addSelections([
{
range: { startRow: rowStart, startColumn: 0, endColumn, endRow: rowEnd, rangeType: RANGE_TYPE.ROW },
primary: {
diff --git a/packages/sheets/src/commands/commands/__tests__/set-border.command.spec.ts b/packages/sheets/src/commands/commands/__tests__/set-border.command.spec.ts
index 1bb1eae87a..ebe9988aa6 100644
--- a/packages/sheets/src/commands/commands/__tests__/set-border.command.spec.ts
+++ b/packages/sheets/src/commands/commands/__tests__/set-border.command.spec.ts
@@ -19,7 +19,7 @@ import { BorderStyleTypes, BorderType, ICommandService, IUniverInstanceService,
import type { Injector } from '@wendellhu/redi';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
-import { NORMAL_SELECTION_PLUGIN_NAME, SelectionManagerService } from '../../../services/selection-manager.service';
+import { SheetsSelectionsService } from '../../../services/selections/selection-manager.service';
import { AddWorksheetMergeMutation } from '../../mutations/add-worksheet-merge.mutation';
import { RemoveWorksheetMergeMutation } from '../../mutations/remove-worksheet-merge.mutation';
import { SetRangeValuesMutation } from '../../mutations/set-range-values.mutation';
@@ -65,13 +65,8 @@ describe('Test style commands', () => {
describe('set border style', () => {
describe('correct situations', () => {
it('will set border style when there is a selected range', async () => {
- const selectionManager = get(SelectionManagerService);
- selectionManager.setCurrentSelection({
- pluginName: NORMAL_SELECTION_PLUGIN_NAME,
- unitId: 'test',
- sheetId: 'sheet1',
- });
- selectionManager.add([
+ const selectionManager = get(SheetsSelectionsService);
+ selectionManager.addSelections([
{
range: { startRow: 0, startColumn: 0, endColumn: 5, endRow: 5, rangeType: RANGE_TYPE.NORMAL },
primary: null,
diff --git a/packages/sheets/src/commands/commands/__tests__/set-col-width.command.spec.ts b/packages/sheets/src/commands/commands/__tests__/set-col-width.command.spec.ts
index 873cbbc709..528f8f3130 100644
--- a/packages/sheets/src/commands/commands/__tests__/set-col-width.command.spec.ts
+++ b/packages/sheets/src/commands/commands/__tests__/set-col-width.command.spec.ts
@@ -19,7 +19,7 @@ import { ICommandService, IUniverInstanceService, RANGE_TYPE, RedoCommand, UndoC
import type { Injector } from '@wendellhu/redi';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
-import { NORMAL_SELECTION_PLUGIN_NAME, SelectionManagerService } from '../../../services/selection-manager.service';
+import { SheetsSelectionsService } from '../../../services/selections/selection-manager.service';
import { SetWorksheetColWidthMutation } from '../../mutations/set-worksheet-col-width.mutation';
import type { IDeltaColumnWidthCommandParams, ISetColWidthCommandParams } from '../set-worksheet-col-width.command';
import { DeltaColumnWidthCommand, SetColWidthCommand } from '../set-worksheet-col-width.command';
@@ -47,13 +47,8 @@ describe('Test set col width commands', () => {
const worksheet = get(IUniverInstanceService).getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET)!.getActiveSheet()!;
const maxRow = worksheet.getMaxRows() - 1;
- const selectionManagerService = get(SelectionManagerService);
- selectionManagerService.setCurrentSelection({
- pluginName: NORMAL_SELECTION_PLUGIN_NAME,
- unitId: 'test',
- sheetId: 'sheet1',
- });
- selectionManagerService.add([
+ const selectionManagerService = get(SheetsSelectionsService);
+ selectionManagerService.addSelections([
{
range: { startRow: 0, startColumn: 1, endColumn: 2, endRow: maxRow, rangeType: RANGE_TYPE.COLUMN },
primary: {
@@ -69,7 +64,7 @@ describe('Test set col width commands', () => {
style: null,
},
]);
- selectionManagerService.add([
+ selectionManagerService.addSelections([
{
range: { startRow: 0, startColumn: 5, endColumn: 5, endRow: maxRow, rangeType: RANGE_TYPE.COLUMN },
primary: null,
diff --git a/packages/sheets/src/commands/commands/__tests__/set-range-values.command.spec.ts b/packages/sheets/src/commands/commands/__tests__/set-range-values.command.spec.ts
index 4341e5a4f8..d73ffa2537 100644
--- a/packages/sheets/src/commands/commands/__tests__/set-range-values.command.spec.ts
+++ b/packages/sheets/src/commands/commands/__tests__/set-range-values.command.spec.ts
@@ -30,7 +30,7 @@ import {
import type { Injector } from '@wendellhu/redi';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
-import { NORMAL_SELECTION_PLUGIN_NAME, SelectionManagerService } from '../../../services/selection-manager.service';
+import { SheetsSelectionsService } from '../../../services/selections/selection-manager.service';
import { SetRangeValuesMutation } from '../../mutations/set-range-values.mutation';
import type { ISetRangeValuesCommandParams } from '../set-range-values.command';
import { SetRangeValuesCommand } from '../set-range-values.command';
@@ -101,7 +101,7 @@ describe('Test set range values commands', () => {
let univer: Univer;
let get: Injector['get'];
let commandService: ICommandService;
- let selectionManager: SelectionManagerService;
+ let selectionManager: SheetsSelectionsService;
let getValue: (sheetId?: string) => Nullable<ICellData>;
let getValues: (
startRow: number,
@@ -120,13 +120,8 @@ describe('Test set range values commands', () => {
commandService.registerCommand(SetRangeValuesCommand);
commandService.registerCommand(SetRangeValuesMutation);
- selectionManager = get(SelectionManagerService);
- selectionManager.setCurrentSelection({
- pluginName: NORMAL_SELECTION_PLUGIN_NAME,
- unitId: 'test',
- sheetId: 'sheet1',
- });
- selectionManager.add([
+ selectionManager = get(SheetsSelectionsService);
+ selectionManager.addSelections([
{
range: { startRow: 0, startColumn: 0, endColumn: 0, endRow: 0, rangeType: RANGE_TYPE.NORMAL },
primary: null,
@@ -706,7 +701,7 @@ describe('Test set range values commands', () => {
describe('fault situations', () => {
it('will not apply when there is no selected ranges', async () => {
- selectionManager.clear();
+ selectionManager.clearCurrentSelections();
const params: ISetRangeValuesCommandParams = {
value: {
v: 'a1',
diff --git a/packages/sheets/src/commands/commands/__tests__/set-row-col-visible.command.spec.ts b/packages/sheets/src/commands/commands/__tests__/set-row-col-visible.command.spec.ts
index 3d4d46e058..6793c14a0c 100644
--- a/packages/sheets/src/commands/commands/__tests__/set-row-col-visible.command.spec.ts
+++ b/packages/sheets/src/commands/commands/__tests__/set-row-col-visible.command.spec.ts
@@ -19,7 +19,7 @@ import { ICommandService, IUniverInstanceService, RANGE_TYPE, RedoCommand, UndoC
import type { Injector } from '@wendellhu/redi';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
-import { NORMAL_SELECTION_PLUGIN_NAME, SelectionManagerService } from '../../../services/selection-manager.service';
+import { SheetsSelectionsService } from '../../../services/selections/selection-manager.service';
import { SetColHiddenMutation, SetColVisibleMutation } from '../../mutations/set-col-visible.mutation';
import { SetRowHiddenMutation, SetRowVisibleMutation } from '../../mutations/set-row-visible.mutation';
import { SetSelectionsOperation } from '../../operations/selection.operation';
@@ -62,13 +62,6 @@ describe('Test row col hide/unhine commands', () => {
].forEach((command) => {
commandService.registerCommand(command);
});
-
- const selectionManager = get(SelectionManagerService);
- selectionManager.setCurrentSelection({
- pluginName: NORMAL_SELECTION_PLUGIN_NAME,
- unitId: 'test',
- sheetId: 'sheet1',
- });
});
afterEach(() => univer.dispose());
@@ -100,9 +93,9 @@ describe('Test row col hide/unhine commands', () => {
}
function selectRow(rowStart: number, rowEnd: number): void {
- const selectionManagerService = get(SelectionManagerService);
+ const selectionManagerService = get(SheetsSelectionsService);
const endColumn = getColCount() - 1;
- selectionManagerService.add([
+ selectionManagerService.addSelections([
{
range: { startRow: rowStart, startColumn: 0, endColumn, endRow: rowEnd, rangeType: RANGE_TYPE.ROW },
primary: {
@@ -121,9 +114,9 @@ describe('Test row col hide/unhine commands', () => {
}
function selectColumn(columnStart: number, columnEnd: number): void {
- const selectionManagerService = get(SelectionManagerService);
+ const selectionManagerService = get(SheetsSelectionsService);
const endRow = getRowCount() - 1;
- selectionManagerService.add([
+ selectionManagerService.addSelections([
{
range: {
startRow: 0,
diff --git a/packages/sheets/src/commands/commands/__tests__/set-row-height.command.spec.ts b/packages/sheets/src/commands/commands/__tests__/set-row-height.command.spec.ts
index 5e6a9a828c..a3cf73b3c7 100644
--- a/packages/sheets/src/commands/commands/__tests__/set-row-height.command.spec.ts
+++ b/packages/sheets/src/commands/commands/__tests__/set-row-height.command.spec.ts
@@ -27,7 +27,7 @@ import {
import type { Injector } from '@wendellhu/redi';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
-import { NORMAL_SELECTION_PLUGIN_NAME, SelectionManagerService } from '../../../services/selection-manager.service';
+import { SheetsSelectionsService } from '../../../services/selections/selection-manager.service';
import {
SetWorksheetRowHeightMutation,
SetWorksheetRowIsAutoHeightMutation,
@@ -74,16 +74,10 @@ describe('Test set row height commands', () => {
const worksheet = get(IUniverInstanceService).getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET)!.getActiveSheet()!;
const maxColumn = worksheet.getMaxColumns() - 1;
- const selectionManager = get(SelectionManagerService);
-
- selectionManager.setCurrentSelection({
- pluginName: NORMAL_SELECTION_PLUGIN_NAME,
- unitId: 'test',
- sheetId: 'sheet1',
- });
+ const selectionManager = get(SheetsSelectionsService);
// select row 2, 3
- selectionManager.add([
+ selectionManager.addSelections([
{
range: { startRow: 1, startColumn: 0, endRow: 2, endColumn: maxColumn, rangeType: RANGE_TYPE.ROW },
primary: {
@@ -101,7 +95,7 @@ describe('Test set row height commands', () => {
]);
// and continue select row 5
- selectionManager.add([
+ selectionManager.addSelections([
{
range: { startRow: 5, startColumn: 0, endColumn: maxColumn, endRow: 5, rangeType: RANGE_TYPE.ROW },
primary: null,
diff --git a/packages/sheets/src/commands/commands/__tests__/set-style.command.spec.ts b/packages/sheets/src/commands/commands/__tests__/set-style.command.spec.ts
index 61526f9b39..11c6be6a36 100644
--- a/packages/sheets/src/commands/commands/__tests__/set-style.command.spec.ts
+++ b/packages/sheets/src/commands/commands/__tests__/set-style.command.spec.ts
@@ -31,7 +31,7 @@ import {
import type { Injector } from '@wendellhu/redi';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
-import { NORMAL_SELECTION_PLUGIN_NAME, SelectionManagerService } from '../../../services/selection-manager.service';
+import { SheetsSelectionsService } from '../../../services/selections/selection-manager.service';
import { SetRangeValuesMutation } from '../../mutations/set-range-values.mutation';
import type { ISetStyleCommandParams } from '../set-style.command';
import {
@@ -129,13 +129,8 @@ describe("Test commands used for updating cells' styles", () => {
describe('bold', () => {
describe('correct situations', () => {
it('will toggle bold style when there is a selected range', async () => {
- const selectionManagerService = get(SelectionManagerService);
- selectionManagerService.setCurrentSelection({
- pluginName: NORMAL_SELECTION_PLUGIN_NAME,
- unitId: 'test',
- sheetId: 'sheet1',
- });
- selectionManagerService.add([
+ const selectionManagerService = get(SheetsSelectionsService);
+ selectionManagerService.addSelections([
{
range: { startRow: 0, startColumn: 0, endColumn: 0, endRow: 0, rangeType: RANGE_TYPE.NORMAL },
primary: {
@@ -184,13 +179,8 @@ describe("Test commands used for updating cells' styles", () => {
describe('italic', () => {
describe('correct situations', () => {
it('will toggle italic style when there is a selected range', async () => {
- const selectionManager = get(SelectionManagerService);
- selectionManager.setCurrentSelection({
- pluginName: NORMAL_SELECTION_PLUGIN_NAME,
- unitId: 'test',
- sheetId: 'sheet1',
- });
- selectionManager.add([
+ const selectionManager = get(SheetsSelectionsService);
+ selectionManager.addSelections([
{
range: { startRow: 0, startColumn: 0, endColumn: 1, endRow: 0, rangeType: RANGE_TYPE.NORMAL },
primary: {
@@ -239,13 +229,8 @@ describe("Test commands used for updating cells' styles", () => {
describe('underline', () => {
describe('correct situations', () => {
it('will toggle underline style when there is a selected range', async () => {
- const selectionManager = get(SelectionManagerService);
- selectionManager.setCurrentSelection({
- pluginName: NORMAL_SELECTION_PLUGIN_NAME,
- unitId: 'test',
- sheetId: 'sheet1',
- });
- selectionManager.add([
+ const selectionManager = get(SheetsSelectionsService);
+ selectionManager.addSelections([
{
range: { startRow: 0, startColumn: 0, endColumn: 0, endRow: 0, rangeType: RANGE_TYPE.NORMAL },
primary: {
@@ -296,13 +281,8 @@ describe("Test commands used for updating cells' styles", () => {
describe('strike-through', () => {
describe('correct situations', () => {
it('will toggle strike-through style when there is a selected range', async () => {
- const selectionManager = get(SelectionManagerService);
- selectionManager.setCurrentSelection({
- pluginName: NORMAL_SELECTION_PLUGIN_NAME,
- unitId: 'test',
- sheetId: 'sheet1',
- });
- selectionManager.add([
+ const selectionManager = get(SheetsSelectionsService);
+ selectionManager.addSelections([
{
range: { startRow: 0, startColumn: 0, endColumn: 0, endRow: 0, rangeType: RANGE_TYPE.NORMAL },
primary: {
@@ -353,13 +333,8 @@ describe("Test commands used for updating cells' styles", () => {
describe('font size', () => {
describe('correct situations', () => {
it('will change font size when there is a selected range', async () => {
- const selectionManager = get(SelectionManagerService);
- selectionManager.setCurrentSelection({
- pluginName: NORMAL_SELECTION_PLUGIN_NAME,
- unitId: 'test',
- sheetId: 'sheet1',
- });
- selectionManager.add([
+ const selectionManager = get(SheetsSelectionsService);
+ selectionManager.addSelections([
{
range: { startRow: 0, startColumn: 0, endColumn: 0, endRow: 0, rangeType: RANGE_TYPE.NORMAL },
primary: null,
@@ -399,13 +374,8 @@ describe("Test commands used for updating cells' styles", () => {
describe('font family', () => {
describe('correct situations', () => {
it('will change font family when there is a selected range', async () => {
- const selectionManager = get(SelectionManagerService);
- selectionManager.setCurrentSelection({
- pluginName: NORMAL_SELECTION_PLUGIN_NAME,
- unitId: 'test',
- sheetId: 'sheet1',
- });
- selectionManager.add([
+ const selectionManager = get(SheetsSelectionsService);
+ selectionManager.addSelections([
{
range: { startRow: 0, startColumn: 0, endColumn: 0, endRow: 0, rangeType: RANGE_TYPE.NORMAL },
primary: null,
@@ -445,13 +415,8 @@ describe("Test commands used for updating cells' styles", () => {
describe('font color', () => {
describe('correct situations', () => {
it('will change font color when there is a selected range', async () => {
- const selectionManager = get(SelectionManagerService);
- selectionManager.setCurrentSelection({
- pluginName: NORMAL_SELECTION_PLUGIN_NAME,
- unitId: 'test',
- sheetId: 'sheet1',
- });
- selectionManager.add([
+ const selectionManager = get(SheetsSelectionsService);
+ selectionManager.addSelections([
{
range: { startRow: 0, startColumn: 0, endColumn: 0, endRow: 0, rangeType: RANGE_TYPE.NORMAL },
primary: {
@@ -547,13 +512,8 @@ describe("Test commands used for updating cells' styles", () => {
describe('background color', () => {
describe('correct situations', () => {
it('will change background color when there is a selected range', async () => {
- const selectionManager = get(SelectionManagerService);
- selectionManager.setCurrentSelection({
- pluginName: NORMAL_SELECTION_PLUGIN_NAME,
- unitId: 'test',
- sheetId: 'sheet1',
- });
- selectionManager.add([
+ const selectionManager = get(SheetsSelectionsService);
+ selectionManager.addSelections([
{
range: { startRow: 0, startColumn: 0, endColumn: 0, endRow: 0, rangeType: RANGE_TYPE.NORMAL },
primary: null,
@@ -595,13 +555,8 @@ describe("Test commands used for updating cells' styles", () => {
describe('vertical text align', () => {
describe('correct situations', () => {
it('will change vertical text align when there is a selected range', async () => {
- const selectionManager = get(SelectionManagerService);
- selectionManager.setCurrentSelection({
- pluginName: NORMAL_SELECTION_PLUGIN_NAME,
- unitId: 'test',
- sheetId: 'sheet1',
- });
- selectionManager.add([
+ const selectionManager = get(SheetsSelectionsService);
+ selectionManager.addSelections([
{
range: { startRow: 0, startColumn: 0, endColumn: 0, endRow: 0, rangeType: RANGE_TYPE.NORMAL },
primary: null,
@@ -643,13 +598,8 @@ describe("Test commands used for updating cells' styles", () => {
describe('horizontal text align', () => {
describe('correct situations', () => {
it('will change horizontal text align when there is a selected range', async () => {
- const selectionManager = get(SelectionManagerService);
- selectionManager.setCurrentSelection({
- pluginName: NORMAL_SELECTION_PLUGIN_NAME,
- unitId: 'test',
- sheetId: 'sheet1',
- });
- selectionManager.add([
+ const selectionManager = get(SheetsSelectionsService);
+ selectionManager.addSelections([
{
range: { startRow: 0, startColumn: 0, endColumn: 0, endRow: 0, rangeType: RANGE_TYPE.NORMAL },
primary: null,
@@ -693,13 +643,8 @@ describe("Test commands used for updating cells' styles", () => {
describe('text wrap', () => {
describe('correct situations', () => {
it('will change text wrap when there is a selected range', async () => {
- const selectionManager = get(SelectionManagerService);
- selectionManager.setCurrentSelection({
- pluginName: NORMAL_SELECTION_PLUGIN_NAME,
- unitId: 'test',
- sheetId: 'sheet1',
- });
- selectionManager.add([
+ const selectionManager = get(SheetsSelectionsService);
+ selectionManager.addSelections([
{
range: { startRow: 0, startColumn: 0, endColumn: 0, endRow: 0, rangeType: RANGE_TYPE.NORMAL },
primary: null,
@@ -743,13 +688,8 @@ describe("Test commands used for updating cells' styles", () => {
describe('text rotation', () => {
describe('correct situations', () => {
it('will change text rotation when there is a selected range', async () => {
- const selectionManager = get(SelectionManagerService);
- selectionManager.setCurrentSelection({
- pluginName: NORMAL_SELECTION_PLUGIN_NAME,
- unitId: 'test',
- sheetId: 'sheet1',
- });
- selectionManager.add([
+ const selectionManager = get(SheetsSelectionsService);
+ selectionManager.addSelections([
{
range: { startRow: 0, startColumn: 0, endColumn: 0, endRow: 0, rangeType: RANGE_TYPE.NORMAL },
primary: null,
diff --git a/packages/sheets/src/commands/commands/add-worksheet-merge.command.ts b/packages/sheets/src/commands/commands/add-worksheet-merge.command.ts
index 984f46dc94..d0dd62758a 100644
--- a/packages/sheets/src/commands/commands/add-worksheet-merge.command.ts
+++ b/packages/sheets/src/commands/commands/add-worksheet-merge.command.ts
@@ -32,7 +32,7 @@ import type {
IRemoveWorksheetMergeMutationParams,
} from '../../basics/interfaces/mutation-interface';
import { getAddMergeMutationRangeByType } from '../../controllers/merge-cell.controller';
-import { SelectionManagerService } from '../../services/selection-manager.service';
+import { SheetsSelectionsService } from '../../services/selections/selection-manager.service';
import { AddMergeUndoMutationFactory, AddWorksheetMergeMutation } from '../mutations/add-worksheet-merge.mutation';
import {
RemoveMergeUndoMutationFactory,
@@ -181,8 +181,8 @@ export const AddWorksheetMergeAllCommand: ICommand = {
id: 'sheet.command.add-worksheet-merge-all',
handler: async (accessor) => {
const commandService = accessor.get(ICommandService);
- const selectionManagerService = accessor.get(SelectionManagerService);
- const selections = selectionManagerService.getSelectionRanges();
+ const selectionManagerService = accessor.get(SheetsSelectionsService);
+ const selections = selectionManagerService.getCurrentSelections()?.map((s) => s.range);
if (!selections?.length) {
return false;
}
@@ -210,8 +210,8 @@ export const AddWorksheetMergeVerticalCommand: ICommand = {
id: 'sheet.command.add-worksheet-merge-vertical',
handler: async (accessor) => {
const commandService = accessor.get(ICommandService);
- const selectionManagerService = accessor.get(SelectionManagerService);
- const selections = selectionManagerService.getSelectionRanges();
+ const selectionManagerService = accessor.get(SheetsSelectionsService);
+ const selections = selectionManagerService.getCurrentSelections()?.map((s) => s.range);
if (!selections?.length) {
return false;
}
@@ -240,8 +240,8 @@ export const AddWorksheetMergeHorizontalCommand: ICommand = {
id: 'sheet.command.add-worksheet-merge-horizontal',
handler: async (accessor) => {
const commandService = accessor.get(ICommandService);
- const selectionManagerService = accessor.get(SelectionManagerService);
- const selections = selectionManagerService.getSelectionRanges();
+ const selectionManagerService = accessor.get(SheetsSelectionsService);
+ const selections = selectionManagerService.getCurrentSelections()?.map((s) => s.range);
if (!selections?.length) {
return false;
}
diff --git a/packages/sheets/src/commands/commands/clear-selection-all.command.ts b/packages/sheets/src/commands/commands/clear-selection-all.command.ts
index 60fc32221d..7a082a34b6 100644
--- a/packages/sheets/src/commands/commands/clear-selection-all.command.ts
+++ b/packages/sheets/src/commands/commands/clear-selection-all.command.ts
@@ -25,7 +25,7 @@ import {
} from '@univerjs/core';
import type { IAccessor } from '@wendellhu/redi';
-import { SelectionManagerService } from '../../services/selection-manager.service';
+import { SheetsSelectionsService } from '../../services/selections/selection-manager.service';
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';
@@ -40,7 +40,7 @@ export const ClearSelectionAllCommand: ICommand = {
handler: async (accessor: IAccessor) => {
const univerInstanceService = accessor.get(IUniverInstanceService);
const commandService = accessor.get(ICommandService);
- const selectionManagerService = accessor.get(SelectionManagerService);
+ const selectionManagerService = accessor.get(SheetsSelectionsService);
const undoRedoService = accessor.get(IUndoRedoService);
const sheetInterceptorService = accessor.get(SheetInterceptorService);
@@ -52,7 +52,7 @@ export const ClearSelectionAllCommand: ICommand = {
if (!worksheet) return false;
const subUnitId = worksheet.getSheetId();
- const selections = selectionManagerService.getSelectionRanges();
+ const selections = selectionManagerService.getCurrentSelections()?.map((s) => s.range);
if (!selections?.length) {
return false;
}
diff --git a/packages/sheets/src/commands/commands/clear-selection-content.command.ts b/packages/sheets/src/commands/commands/clear-selection-content.command.ts
index c4ce18c085..42e079857d 100644
--- a/packages/sheets/src/commands/commands/clear-selection-content.command.ts
+++ b/packages/sheets/src/commands/commands/clear-selection-content.command.ts
@@ -25,7 +25,7 @@ import {
} from '@univerjs/core';
import type { IAccessor } from '@wendellhu/redi';
-import { SelectionManagerService } from '../../services/selection-manager.service';
+import { SheetsSelectionsService } from '../../services/selections/selection-manager.service';
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';
@@ -42,7 +42,7 @@ export const ClearSelectionContentCommand: ICommand = {
handler: async (accessor: IAccessor) => {
const univerInstanceService = accessor.get(IUniverInstanceService);
const commandService = accessor.get(ICommandService);
- const selectionManagerService = accessor.get(SelectionManagerService);
+ const selectionManagerService = accessor.get(SheetsSelectionsService);
const undoRedoService = accessor.get(IUndoRedoService);
const sheetInterceptorService = accessor.get(SheetInterceptorService);
@@ -54,7 +54,7 @@ export const ClearSelectionContentCommand: ICommand = {
if (!worksheet) return false;
const subUnitId = worksheet.getSheetId();
- const selections = selectionManagerService.getSelectionRanges();
+ const selections = selectionManagerService.getCurrentSelections()?.map((s) => s.range);
if (!selections?.length) {
return false;
}
diff --git a/packages/sheets/src/commands/commands/clear-selection-format.command.ts b/packages/sheets/src/commands/commands/clear-selection-format.command.ts
index 7a7b23b296..f56e1156ef 100644
--- a/packages/sheets/src/commands/commands/clear-selection-format.command.ts
+++ b/packages/sheets/src/commands/commands/clear-selection-format.command.ts
@@ -25,7 +25,7 @@ import {
} from '@univerjs/core';
import type { IAccessor } from '@wendellhu/redi';
-import { SelectionManagerService } from '../../services/selection-manager.service';
+import { SheetsSelectionsService } from '../../services/selections/selection-manager.service';
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';
@@ -42,7 +42,7 @@ export const ClearSelectionFormatCommand: ICommand = {
handler: async (accessor: IAccessor) => {
const univerInstanceService = accessor.get(IUniverInstanceService);
const commandService = accessor.get(ICommandService);
- const selectionManagerService = accessor.get(SelectionManagerService);
+ const selectionManagerService = accessor.get(SheetsSelectionsService);
const undoRedoService = accessor.get(IUndoRedoService);
const sheetInterceptorService = accessor.get(SheetInterceptorService);
@@ -54,7 +54,7 @@ export const ClearSelectionFormatCommand: ICommand = {
if (!worksheet) return false;
const subUnitId = worksheet.getSheetId();
- const selections = selectionManagerService.getSelectionRanges();
+ const selections = selectionManagerService.getCurrentSelections()?.map((s) => s.range);
if (!selections?.length) {
return false;
}
diff --git a/packages/sheets/src/commands/commands/delete-range-move-left.command.ts b/packages/sheets/src/commands/commands/delete-range-move-left.command.ts
index a19ee4e42c..906a1f2fa7 100644
--- a/packages/sheets/src/commands/commands/delete-range-move-left.command.ts
+++ b/packages/sheets/src/commands/commands/delete-range-move-left.command.ts
@@ -26,7 +26,7 @@ import {
import type { IAccessor } from '@wendellhu/redi';
import type { IDeleteRangeMutationParams } from '../../basics/interfaces/mutation-interface';
-import { SelectionManagerService } from '../../services/selection-manager.service';
+import { SheetsSelectionsService } from '../../services/selections/selection-manager.service';
import { SheetInterceptorService } from '../../services/sheet-interceptor/sheet-interceptor.service';
import { getRemoveRangeMutations } from '../utils/handle-range-mutation';
import { followSelectionOperation } from './utils/selection-utils';
@@ -48,7 +48,7 @@ export const DeleteRangeMoveLeftCommand: ICommand = {
const commandService = accessor.get(ICommandService);
const undoRedoService = accessor.get(IUndoRedoService);
const univerInstanceService = accessor.get(IUniverInstanceService);
- const selectionManagerService = accessor.get(SelectionManagerService);
+ const selectionManagerService = accessor.get(SheetsSelectionsService);
const sheetInterceptorService = accessor.get(SheetInterceptorService);
const target = getSheetCommandTarget(univerInstanceService);
@@ -58,7 +58,7 @@ export const DeleteRangeMoveLeftCommand: ICommand = {
let range = params?.range;
if (!range) {
- range = selectionManagerService.getLast()?.range;
+ range = selectionManagerService.getCurrentLastSelection()?.range;
}
if (!range) return false;
diff --git a/packages/sheets/src/commands/commands/delete-range-move-up.command.ts b/packages/sheets/src/commands/commands/delete-range-move-up.command.ts
index a70e7543c0..5e7bc15688 100644
--- a/packages/sheets/src/commands/commands/delete-range-move-up.command.ts
+++ b/packages/sheets/src/commands/commands/delete-range-move-up.command.ts
@@ -26,7 +26,7 @@ import {
import type { IAccessor } from '@wendellhu/redi';
import type { IDeleteRangeMutationParams } from '../../basics/interfaces/mutation-interface';
-import { SelectionManagerService } from '../../services/selection-manager.service';
+import { SheetsSelectionsService } from '../../services/selections/selection-manager.service';
import { SheetInterceptorService } from '../../services/sheet-interceptor/sheet-interceptor.service';
import { getRemoveRangeMutations } from '../utils/handle-range-mutation';
import { followSelectionOperation } from './utils/selection-utils';
@@ -48,7 +48,7 @@ export const DeleteRangeMoveUpCommand: ICommand = {
const commandService = accessor.get(ICommandService);
const undoRedoService = accessor.get(IUndoRedoService);
const univerInstanceService = accessor.get(IUniverInstanceService);
- const selectionManagerService = accessor.get(SelectionManagerService);
+ const selectionManagerService = accessor.get(SheetsSelectionsService);
const sheetInterceptorService = accessor.get(SheetInterceptorService);
const target = getSheetCommandTarget(univerInstanceService);
@@ -57,7 +57,7 @@ export const DeleteRangeMoveUpCommand: ICommand = {
const { unitId, subUnitId, workbook, worksheet } = target;
let range = params?.range;
if (!range) {
- range = selectionManagerService.getLast()?.range!;
+ range = selectionManagerService.getCurrentLastSelection()?.range!;
}
if (!range) return false;
diff --git a/packages/sheets/src/commands/commands/insert-range-move-down.command.ts b/packages/sheets/src/commands/commands/insert-range-move-down.command.ts
index 7498faf486..ba44cfe4cb 100644
--- a/packages/sheets/src/commands/commands/insert-range-move-down.command.ts
+++ b/packages/sheets/src/commands/commands/insert-range-move-down.command.ts
@@ -34,7 +34,7 @@ import type {
IInsertRowMutationParams,
IRemoveRowsMutationParams,
} from '../../basics/interfaces/mutation-interface';
-import { SelectionManagerService } from '../../services/selection-manager.service';
+import { SheetsSelectionsService } from '../../services/selections/selection-manager.service';
import { SheetInterceptorService } from '../../services/sheet-interceptor/sheet-interceptor.service';
import { InsertRowMutation, InsertRowMutationUndoFactory } from '../mutations/insert-row-col.mutation';
import { RemoveRowMutation } from '../mutations/remove-row-col.mutation';
@@ -59,7 +59,7 @@ export const InsertRangeMoveDownCommand: ICommand = {
const commandService = accessor.get(ICommandService);
const undoRedoService = accessor.get(IUndoRedoService);
const univerInstanceService = accessor.get(IUniverInstanceService);
- const selectionManagerService = accessor.get(SelectionManagerService);
+ const selectionManagerService = accessor.get(SheetsSelectionsService);
const sheetInterceptorService = accessor.get(SheetInterceptorService);
const errorService = accessor.get(ErrorService);
const localeService = accessor.get(LocaleService);
@@ -76,7 +76,7 @@ export const InsertRangeMoveDownCommand: ICommand = {
let range = params?.range;
if (!range) {
- range = selectionManagerService.getLast()?.range;
+ range = selectionManagerService.getCurrentLastSelection()?.range;
}
if (!range) return false;
diff --git a/packages/sheets/src/commands/commands/insert-range-move-right.command.ts b/packages/sheets/src/commands/commands/insert-range-move-right.command.ts
index 3060380f57..03fda011b3 100644
--- a/packages/sheets/src/commands/commands/insert-range-move-right.command.ts
+++ b/packages/sheets/src/commands/commands/insert-range-move-right.command.ts
@@ -34,7 +34,7 @@ import type {
IInsertRangeMutationParams,
IRemoveColMutationParams,
} from '../../basics/interfaces/mutation-interface';
-import { SelectionManagerService } from '../../services/selection-manager.service';
+import { SheetsSelectionsService } from '../../services/selections/selection-manager.service';
import { SheetInterceptorService } from '../../services/sheet-interceptor/sheet-interceptor.service';
import { InsertColMutation, InsertColMutationUndoFactory } from '../mutations/insert-row-col.mutation';
import { RemoveColMutation } from '../mutations/remove-row-col.mutation';
@@ -58,7 +58,7 @@ export const InsertRangeMoveRightCommand: ICommand = {
const commandService = accessor.get(ICommandService);
const undoRedoService = accessor.get(IUndoRedoService);
const univerInstanceService = accessor.get(IUniverInstanceService);
- const selectionManagerService = accessor.get(SelectionManagerService);
+ const selectionManagerService = accessor.get(SheetsSelectionsService);
const sheetInterceptorService = accessor.get(SheetInterceptorService);
const errorService = accessor.get(ErrorService);
const localeService = accessor.get(LocaleService);
@@ -75,7 +75,7 @@ export const InsertRangeMoveRightCommand: ICommand = {
let range = params?.range;
if (!range) {
- range = selectionManagerService.getLast()?.range;
+ range = selectionManagerService.getCurrentLastSelection()?.range;
}
if (!range) return false;
diff --git a/packages/sheets/src/commands/commands/insert-row-col.command.ts b/packages/sheets/src/commands/commands/insert-row-col.command.ts
index 478b036c2f..1fc9478f77 100644
--- a/packages/sheets/src/commands/commands/insert-row-col.command.ts
+++ b/packages/sheets/src/commands/commands/insert-row-col.command.ts
@@ -35,7 +35,7 @@ import type {
IRemoveColMutationParams,
IRemoveRowsMutationParams,
} from '../../basics/interfaces/mutation-interface';
-import { SelectionManagerService } from '../../services/selection-manager.service';
+import { SheetsSelectionsService } from '../../services/selections/selection-manager.service';
import { SheetInterceptorService } from '../../services/sheet-interceptor/sheet-interceptor.service';
import {
InsertColMutation,
@@ -148,8 +148,8 @@ export const InsertRowBeforeCommand: ICommand = {
type: CommandType.COMMAND,
id: 'sheet.command.insert-row-before',
handler: async (accessor: IAccessor) => {
- const selectionManagerService = accessor.get(SelectionManagerService);
- const selections = selectionManagerService.getSelections()?.map((s) => s.range);
+ const selectionManagerService = accessor.get(SheetsSelectionsService);
+ const selections = selectionManagerService.getCurrentSelections()?.map((s) => s.range);
let range: IRange;
if (selections?.length === 1) {
@@ -206,8 +206,8 @@ export const InsertRowAfterCommand: ICommand = {
type: CommandType.COMMAND,
id: 'sheet.command.insert-row-after',
handler: async (accessor: IAccessor) => {
- const selectionManagerService = accessor.get(SelectionManagerService);
- const selections = selectionManagerService.getSelections()?.map((s) => s.range);
+ const selectionManagerService = accessor.get(SheetsSelectionsService);
+ const selections = selectionManagerService.getCurrentSelections()?.map((s) => s.range);
let range: IRange;
if (selections?.length === 1) {
@@ -335,8 +335,8 @@ export const InsertColBeforeCommand: ICommand = {
type: CommandType.COMMAND,
id: 'sheet.command.insert-col-before',
handler: async (accessor: IAccessor) => {
- const selectionManagerService = accessor.get(SelectionManagerService);
- const selections = selectionManagerService.getSelections();
+ const selectionManagerService = accessor.get(SheetsSelectionsService);
+ const selections = selectionManagerService.getCurrentSelections();
let range: IRange;
if (selections?.length === 1) {
@@ -392,8 +392,8 @@ export const InsertColAfterCommand: ICommand = {
type: CommandType.COMMAND,
id: 'sheet.command.insert-col-after',
handler: async (accessor: IAccessor) => {
- const selectionManagerService = accessor.get(SelectionManagerService);
- const selections = selectionManagerService.getSelections();
+ const selectionManagerService = accessor.get(SheetsSelectionsService);
+ const selections = selectionManagerService.getCurrentSelections();
let range: IRange;
if (selections?.length === 1) {
diff --git a/packages/sheets/src/commands/commands/move-range.command.ts b/packages/sheets/src/commands/commands/move-range.command.ts
index f782cb459c..c1fc149049 100644
--- a/packages/sheets/src/commands/commands/move-range.command.ts
+++ b/packages/sheets/src/commands/commands/move-range.command.ts
@@ -30,7 +30,6 @@ import {
} from '@univerjs/core';
import type { IAccessor } from '@wendellhu/redi';
-import { NORMAL_SELECTION_PLUGIN_NAME } from '../../services/selection-manager.service';
import { SheetInterceptorService } from '../../services/sheet-interceptor/sheet-interceptor.service';
import type { IMoveRangeMutationParams } from '../mutations/move-range.mutation';
import { MoveRangeMutation } from '../mutations/move-range.mutation';
@@ -83,7 +82,7 @@ export const MoveRangeCommand: ICommand = {
params: {
unitId,
subUnitId,
- pluginName: NORMAL_SELECTION_PLUGIN_NAME,
+
selections: [{ range: params.toRange, primary: getPrimaryForRange(params.toRange, worksheet) }],
} as ISetSelectionsOperationParams,
},
@@ -97,7 +96,7 @@ export const MoveRangeCommand: ICommand = {
params: {
unitId,
subUnitId,
- pluginName: NORMAL_SELECTION_PLUGIN_NAME,
+
selections: [{ range: params.fromRange, primary: getPrimaryForRange(params.fromRange, worksheet) }],
} as ISetSelectionsOperationParams,
},
diff --git a/packages/sheets/src/commands/commands/move-rows-cols.command.ts b/packages/sheets/src/commands/commands/move-rows-cols.command.ts
index 55fc94fad3..3aa23c52d7 100644
--- a/packages/sheets/src/commands/commands/move-rows-cols.command.ts
+++ b/packages/sheets/src/commands/commands/move-rows-cols.command.ts
@@ -29,7 +29,7 @@ import {
} from '@univerjs/core';
import type { IAccessor } from '@wendellhu/redi';
-import { NORMAL_SELECTION_PLUGIN_NAME, SelectionManagerService } from '../../services/selection-manager.service';
+import { SheetsSelectionsService } from '../../services/selections/selection-manager.service';
import { SheetInterceptorService } from '../../services/sheet-interceptor/sheet-interceptor.service';
import type { IMoveColumnsMutationParams, IMoveRowsMutationParams } from '../mutations/move-rows-cols.mutation';
import {
@@ -56,8 +56,8 @@ export const MoveRowsCommand: ICommand<IMoveRowsCommandParams> = {
id: MoveRowsCommandId,
type: CommandType.COMMAND,
handler: async (accessor: IAccessor, params: IMoveRowsCommandParams) => {
- const selectionManagerService = accessor.get(SelectionManagerService);
- const selections = selectionManagerService.getSelections();
+ const selectionManagerService = accessor.get(SheetsSelectionsService);
+ const selections = selectionManagerService.getCurrentSelections();
const {
fromRange: { startRow: fromRow },
toRange: { startRow: toRow },
@@ -132,13 +132,13 @@ export const MoveRowsCommand: ICommand<IMoveRowsCommandParams> = {
const setSelectionsParam: ISetSelectionsOperationParams = {
unitId,
subUnitId,
- pluginName: NORMAL_SELECTION_PLUGIN_NAME,
+
selections: [{ range: destSelection, primary: getPrimaryForRange(destSelection, worksheet), style: null }],
};
const undoSetSelectionsParam: ISetSelectionsOperationParams = {
unitId,
subUnitId,
- pluginName: NORMAL_SELECTION_PLUGIN_NAME,
+
selections: [{ range: rangeToMove, primary: beforePrimary, style: null }],
};
@@ -186,8 +186,8 @@ export const MoveColsCommand: ICommand<IMoveColsCommandParams> = {
id: MoveColsCommandId,
type: CommandType.COMMAND,
handler: async (accessor: IAccessor, params: IMoveColsCommandParams) => {
- const selectionManagerService = accessor.get(SelectionManagerService);
- const selections = selectionManagerService.getSelections();
+ const selectionManagerService = accessor.get(SheetsSelectionsService);
+ const selections = selectionManagerService.getCurrentSelections();
const {
fromRange: { startColumn: fromCol },
toRange: { startColumn: toCol },
@@ -262,13 +262,13 @@ export const MoveColsCommand: ICommand<IMoveColsCommandParams> = {
const setSelectionsParam: ISetSelectionsOperationParams = {
unitId,
subUnitId,
- pluginName: NORMAL_SELECTION_PLUGIN_NAME,
+
selections: [{ range: destSelection, primary: getPrimaryForRange(destSelection, worksheet), style: null }],
};
const undoSetSelectionsParam: ISetSelectionsOperationParams = {
unitId,
subUnitId,
- pluginName: NORMAL_SELECTION_PLUGIN_NAME,
+
selections: [{ range: rangeToMove, primary: beforePrimary, style: null }],
};
diff --git a/packages/sheets/src/commands/commands/remove-row-col.command.ts b/packages/sheets/src/commands/commands/remove-row-col.command.ts
index eef39f4f9e..7012def57d 100644
--- a/packages/sheets/src/commands/commands/remove-row-col.command.ts
+++ b/packages/sheets/src/commands/commands/remove-row-col.command.ts
@@ -30,7 +30,7 @@ import type {
IRemoveColMutationParams,
IRemoveRowsMutationParams,
} from '../../basics/interfaces/mutation-interface';
-import { SelectionManagerService } from '../../services/selection-manager.service';
+import { SheetsSelectionsService } from '../../services/selections/selection-manager.service';
import { SheetInterceptorService } from '../../services/sheet-interceptor/sheet-interceptor.service';
import { InsertColMutation, InsertRowMutation } from '../mutations/insert-row-col.mutation';
import {
@@ -57,11 +57,11 @@ export const RemoveRowCommand: ICommand<IRemoveRowColCommandParams> = {
// eslint-disable-next-line max-lines-per-function
handler: async (accessor: IAccessor, params?: IRemoveRowColCommandParams) => {
- const selectionManagerService = accessor.get(SelectionManagerService);
+ const selectionManagerService = accessor.get(SheetsSelectionsService);
const sheetInterceptorService = accessor.get(SheetInterceptorService);
let totalRange = params?.range;
- if (!totalRange) totalRange = selectionManagerService.getLast()?.range;
+ if (!totalRange) totalRange = selectionManagerService.getCurrentLastSelection()?.range;
if (!totalRange) return false;
const univerInstanceService = accessor.get(IUniverInstanceService);
@@ -172,11 +172,11 @@ export const RemoveColCommand: ICommand = {
id: RemoveColCommandId,
handler: async (accessor: IAccessor, params?: IRemoveRowColCommandParams) => {
- const selectionManagerService = accessor.get(SelectionManagerService);
+ const selectionManagerService = accessor.get(SheetsSelectionsService);
const sheetInterceptorService = accessor.get(SheetInterceptorService);
let range = params?.range;
- if (!range) range = selectionManagerService.getLast()?.range;
+ if (!range) range = selectionManagerService.getCurrentLastSelection()?.range;
if (!range) return false;
const univerInstanceService = accessor.get(IUniverInstanceService);
diff --git a/packages/sheets/src/commands/commands/remove-sheet.command.ts b/packages/sheets/src/commands/commands/remove-sheet.command.ts
index 5d255fa9dc..53c0b2daba 100644
--- a/packages/sheets/src/commands/commands/remove-sheet.command.ts
+++ b/packages/sheets/src/commands/commands/remove-sheet.command.ts
@@ -31,7 +31,6 @@ import type {
import { SheetInterceptorService } from '../../services/sheet-interceptor/sheet-interceptor.service';
import { InsertSheetMutation } from '../mutations/insert-sheet.mutation';
import { RemoveSheetMutation, RemoveSheetUndoMutationFactory } from '../mutations/remove-sheet.mutation';
-import type { ISetWorksheetActiveOperationParams } from '../operations/set-worksheet-active.operation';
import { getSheetCommandTarget } from './utils/target-util';
export interface IRemoveSheetCommandParams {
@@ -58,14 +57,6 @@ export const RemoveSheetCommand: ICommand = {
if (workbook.getSheets().length <= 1) return false;
- const index = workbook.getSheetIndex(worksheet);
- const activateSheetId = workbook.getConfig().sheetOrder[index + 1];
-
- const activeSheetMutationParams: ISetWorksheetActiveOperationParams = {
- unitId,
- subUnitId: activateSheetId,
- };
-
// prepare do mutations
const RemoveSheetMutationParams: IRemoveSheetMutationParams = {
subUnitId,
@@ -84,7 +75,7 @@ export const RemoveSheetCommand: ICommand = {
const undos = [...(intercepted.preUndos ?? []), { id: InsertSheetMutation.id, params: InsertSheetMutationParams }, ...intercepted.undos];
const result = sequenceExecute(redos, commandService);
- if (result) {
+ if (result.result) {
undoRedoService.pushUndoRedo({
unitID: unitId,
undoMutations: undos,
diff --git a/packages/sheets/src/commands/commands/remove-worksheet-merge.command.ts b/packages/sheets/src/commands/commands/remove-worksheet-merge.command.ts
index 66e8287901..8c0539e44c 100644
--- a/packages/sheets/src/commands/commands/remove-worksheet-merge.command.ts
+++ b/packages/sheets/src/commands/commands/remove-worksheet-merge.command.ts
@@ -22,7 +22,7 @@ import type {
IAddWorksheetMergeMutationParams,
IRemoveWorksheetMergeMutationParams,
} from '../../basics/interfaces/mutation-interface';
-import { SelectionManagerService } from '../../services/selection-manager.service';
+import { SheetsSelectionsService } from '../../services/selections/selection-manager.service';
import { AddWorksheetMergeMutation } from '../mutations/add-worksheet-merge.mutation';
import {
RemoveMergeUndoMutationFactory,
@@ -38,12 +38,12 @@ export const RemoveWorksheetMergeCommand: ICommand = {
id: 'sheet.command.remove-worksheet-merge',
// eslint-disable-next-line max-lines-per-function
handler: async (accessor: IAccessor) => {
- const selectionManagerService = accessor.get(SelectionManagerService);
+ const selectionManagerService = accessor.get(SheetsSelectionsService);
const commandService = accessor.get(ICommandService);
const undoRedoService = accessor.get(IUndoRedoService);
const univerInstanceService = accessor.get(IUniverInstanceService);
- const selections = selectionManagerService.getSelectionRanges();
+ const selections = selectionManagerService.getCurrentSelections()?.map((s) => s.range);
if (!selections?.length) return false;
const target = getSheetCommandTarget(univerInstanceService);
@@ -67,7 +67,7 @@ export const RemoveWorksheetMergeCommand: ICommand = {
removeMergeMutationParams
);
- const nowSelections = selectionManagerService.getSelections();
+ const nowSelections = selectionManagerService.getCurrentSelections();
if (!nowSelections?.length) return false;
const undoSelections = Tools.deepClone(nowSelections);
diff --git a/packages/sheets/src/commands/commands/set-border-command.ts b/packages/sheets/src/commands/commands/set-border-command.ts
index a95441b850..af130d7a1e 100644
--- a/packages/sheets/src/commands/commands/set-border-command.ts
+++ b/packages/sheets/src/commands/commands/set-border-command.ts
@@ -36,7 +36,7 @@ import {
import type { IAccessor } from '@wendellhu/redi';
import { BorderStyleManagerService, type IBorderInfo } from '../../services/border-style-manager.service';
-import { SelectionManagerService } from '../../services/selection-manager.service';
+import { SheetsSelectionsService } from '../../services/selections/selection-manager.service';
import type { ISetRangeValuesMutationParams } from '../mutations/set-range-values.mutation';
import { SetRangeValuesMutation, SetRangeValuesUndoMutationFactory } from '../mutations/set-range-values.mutation';
import { getSheetCommandTarget } from './utils/target-util';
@@ -139,14 +139,14 @@ export const SetBorderCommand: ICommand = {
const commandService = accessor.get(ICommandService);
const undoRedoService = accessor.get(IUndoRedoService);
const univerInstanceService = accessor.get(IUniverInstanceService);
- const selectionManagerService = accessor.get(SelectionManagerService);
+ const selectionManagerService = accessor.get(SheetsSelectionsService);
const borderStyleManagerService = accessor.get(BorderStyleManagerService);
const target = getSheetCommandTarget(univerInstanceService, params);
if (!target) return false;
const { worksheet, unitId, subUnitId } = target;
- const selections = selectionManagerService.getSelectionRanges();
+ const selections = selectionManagerService.getCurrentSelections()?.map((s) => s.range);
const mergeData = worksheet.getConfig().mergeData;
if (!selections?.length) {
return false;
diff --git a/packages/sheets/src/commands/commands/set-col-visible.command.ts b/packages/sheets/src/commands/commands/set-col-visible.command.ts
index 99b9d64c3d..2554476862 100644
--- a/packages/sheets/src/commands/commands/set-col-visible.command.ts
+++ b/packages/sheets/src/commands/commands/set-col-visible.command.ts
@@ -26,7 +26,7 @@ import {
} from '@univerjs/core';
import type { IAccessor } from '@wendellhu/redi';
-import { NORMAL_SELECTION_PLUGIN_NAME, SelectionManagerService } from '../../services/selection-manager.service';
+import { SheetsSelectionsService } from '../../services/selections/selection-manager.service';
import type { ISetColHiddenMutationParams, ISetColVisibleMutationParams } from '../mutations/set-col-visible.mutation';
import {
SetColHiddenMutation,
@@ -68,7 +68,7 @@ export const SetSpecificColsVisibleCommand: ICommand<ISetSpecificColsVisibleComm
const setSelectionOperationParams: ISetSelectionsOperationParams = {
unitId,
subUnitId,
- pluginName: NORMAL_SELECTION_PLUGIN_NAME,
+
selections: ranges.map((r) => ({ range: r, primary: getPrimaryForRange(r, worksheet), style: null })),
};
@@ -76,7 +76,7 @@ export const SetSpecificColsVisibleCommand: ICommand<ISetSpecificColsVisibleComm
const undoSetSelectionsOperationParams: ISetSelectionsOperationParams = {
unitId,
subUnitId,
- pluginName: NORMAL_SELECTION_PLUGIN_NAME,
+
selections: getSelectionsAfterHiding(ranges).map((range) => ({
range,
primary: getPrimaryForRange(range, worksheet),
@@ -123,10 +123,10 @@ export const SetSelectedColsVisibleCommand: ICommand = {
type: CommandType.COMMAND,
id: 'sheet.command.set-selected-cols-visible',
handler: async (accessor: IAccessor) => {
- const selectionManagerService = accessor.get(SelectionManagerService);
+ const selectionManagerService = accessor.get(SheetsSelectionsService);
const commandService = accessor.get(ICommandService);
- const ranges = selectionManagerService.getSelections()?.map((s) => s.range).filter((r) => r.rangeType === RANGE_TYPE.COLUMN);
+ const ranges = selectionManagerService.getCurrentSelections()?.map((s) => s.range).filter((r) => r.rangeType === RANGE_TYPE.COLUMN);
if (!ranges?.length) return false;
const target = getSheetCommandTarget(accessor.get(IUniverInstanceService));
@@ -148,12 +148,12 @@ export const SetColHiddenCommand: ICommand = {
type: CommandType.COMMAND,
id: 'sheet.command.set-col-hidden',
handler: async (accessor: IAccessor) => {
- const selectionManagerService = accessor.get(SelectionManagerService);
+ const selectionManagerService = accessor.get(SheetsSelectionsService);
const sheetInterceptorService = accessor.get(SheetInterceptorService);
const univerInstanceService = accessor.get(IUniverInstanceService);
const commandService = accessor.get(ICommandService);
- let ranges = selectionManagerService.getSelections()?.map((s) => s.range).filter((r) => r.rangeType === RANGE_TYPE.COLUMN);
+ let ranges = selectionManagerService.getCurrentSelections()?.map((s) => s.range).filter((r) => r.rangeType === RANGE_TYPE.COLUMN);
if (!ranges?.length) return false;
const target = getSheetCommandTarget(univerInstanceService);
@@ -165,7 +165,7 @@ export const SetColHiddenCommand: ICommand = {
const redoMutationParams: ISetColHiddenMutationParams = { unitId, subUnitId, ranges };
const setSelectionOperationParams: ISetSelectionsOperationParams = {
- unitId, subUnitId, pluginName: NORMAL_SELECTION_PLUGIN_NAME,
+ unitId, subUnitId,
selections: getSelectionsAfterHiding(ranges).map((range) => ({
range,
primary: getPrimaryForRange(range, worksheet),
@@ -175,7 +175,7 @@ export const SetColHiddenCommand: ICommand = {
const undoMutationParams = SetColHiddenUndoMutationFactory(accessor, redoMutationParams);
const undoSetSelectionsOperationParams: ISetSelectionsOperationParams = {
- unitId, subUnitId, pluginName: NORMAL_SELECTION_PLUGIN_NAME,
+ unitId, subUnitId,
selections: ranges.map((range) => ({
range,
primary: getPrimaryForRange(range, worksheet),
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 5fbcf088cc..387b0bcab1 100644
--- a/packages/sheets/src/commands/commands/set-range-values.command.ts
+++ b/packages/sheets/src/commands/commands/set-range-values.command.ts
@@ -28,7 +28,7 @@ import {
} from '@univerjs/core';
import type { IAccessor } from '@wendellhu/redi';
-import { SelectionManagerService } from '../../services/selection-manager.service';
+import { SheetsSelectionsService } from '../../services/selections/selection-manager.service';
import { SheetInterceptorService } from '../../services/sheet-interceptor/sheet-interceptor.service';
import { SetRangeValuesMutation, SetRangeValuesUndoMutationFactory } from '../mutations/set-range-values.mutation';
import type { ISheetCommandSharedParams } from '../utils/interface';
@@ -57,7 +57,7 @@ export const SetRangeValuesCommand: ICommand = {
const commandService = accessor.get(ICommandService);
const undoRedoService = accessor.get(IUndoRedoService);
const univerInstanceService = accessor.get(IUniverInstanceService);
- const selectionManagerService = accessor.get(SelectionManagerService);
+ const selectionManagerService = accessor.get(SheetsSelectionsService);
const sheetInterceptorService = accessor.get(SheetInterceptorService);
const permissionService = accessor.get(IPermissionService);
@@ -72,7 +72,7 @@ export const SetRangeValuesCommand: ICommand = {
const { subUnitId, unitId } = target;
const { value, range } = params;
- const currentSelections = range ? [range] : selectionManagerService.getSelectionRanges();
+ const currentSelections = range ? [range] : selectionManagerService.getCurrentSelections()?.map((s) => s.range);
if (!currentSelections || !currentSelections.length) {
return false;
diff --git a/packages/sheets/src/commands/commands/set-row-visible.command.ts b/packages/sheets/src/commands/commands/set-row-visible.command.ts
index 04eb2ccac2..502f724243 100644
--- a/packages/sheets/src/commands/commands/set-row-visible.command.ts
+++ b/packages/sheets/src/commands/commands/set-row-visible.command.ts
@@ -25,7 +25,7 @@ import {
} from '@univerjs/core';
import type { IAccessor } from '@wendellhu/redi';
-import { NORMAL_SELECTION_PLUGIN_NAME, SelectionManagerService } from '../../services/selection-manager.service';
+import { SheetsSelectionsService } from '../../services/selections/selection-manager.service';
import type { ISetRowHiddenMutationParams, ISetRowVisibleMutationParams } from '../mutations/set-row-visible.mutation';
import {
SetRowHiddenMutation,
@@ -62,7 +62,7 @@ export const SetSpecificRowsVisibleCommand: ICommand<ISetSpecificRowsVisibleComm
const setSelectionOperationParams: ISetSelectionsOperationParams = {
unitId,
subUnitId,
- pluginName: NORMAL_SELECTION_PLUGIN_NAME,
+
selections: ranges.map((range) => ({
range,
primary: getPrimaryForRange(range, worksheet),
@@ -74,7 +74,7 @@ export const SetSpecificRowsVisibleCommand: ICommand<ISetSpecificRowsVisibleComm
const undoSetSelectionsOperationParams: ISetSelectionsOperationParams = {
unitId,
subUnitId,
- pluginName: NORMAL_SELECTION_PLUGIN_NAME,
+
selections: getSelectionsAfterHiding(ranges).map((range) => ({
range,
primary: getPrimaryForRange(range, worksheet),
@@ -122,11 +122,11 @@ export const SetSelectedRowsVisibleCommand: ICommand = {
type: CommandType.COMMAND,
id: 'sheet.command.set-selected-rows-visible',
handler: async (accessor: IAccessor) => {
- const selectionManagerService = accessor.get(SelectionManagerService);
+ const selectionManagerService = accessor.get(SheetsSelectionsService);
const univerInstanceService = accessor.get(IUniverInstanceService);
const commandService = accessor.get(ICommandService);
- const ranges = selectionManagerService.getSelections()?.map((s) => s.range).filter((r) => r.rangeType === RANGE_TYPE.ROW);
+ const ranges = selectionManagerService.getCurrentSelections()?.map((s) => s.range).filter((r) => r.rangeType === RANGE_TYPE.ROW);
if (!ranges?.length) return false;
const target = getSheetCommandTarget(univerInstanceService);
@@ -146,14 +146,14 @@ export const SetRowHiddenCommand: ICommand = {
type: CommandType.COMMAND,
id: 'sheet.command.set-rows-hidden',
handler: async (accessor: IAccessor) => {
- const selectionManagerService = accessor.get(SelectionManagerService);
+ const selectionManagerService = accessor.get(SheetsSelectionsService);
const commandService = accessor.get(ICommandService);
const undoRedoService = accessor.get(IUndoRedoService);
const univerInstanceService = accessor.get(IUniverInstanceService);
const sheetInterceptorService = accessor.get(SheetInterceptorService);
// Ranges should be divided by already hidden rows.
- let ranges = selectionManagerService.getSelections()?.map((s) => s.range).filter((r) => r.rangeType === RANGE_TYPE.ROW);
+ let ranges = selectionManagerService.getCurrentSelections()?.map((s) => s.range).filter((r) => r.rangeType === RANGE_TYPE.ROW);
if (!ranges?.length) return false;
const target = getSheetCommandTarget(univerInstanceService);
@@ -166,7 +166,7 @@ export const SetRowHiddenCommand: ICommand = {
const setSelectionOperationParams: ISetSelectionsOperationParams = {
unitId,
subUnitId,
- pluginName: NORMAL_SELECTION_PLUGIN_NAME,
+
selections: getSelectionsAfterHiding(ranges).map((range) => ({
range,
primary: getPrimaryForRange(range, worksheet),
@@ -176,7 +176,7 @@ export const SetRowHiddenCommand: ICommand = {
const undoMutationParams = SetRowHiddenUndoMutationFactory(accessor, redoMutationParams);
const undoSetSelectionsOperationParams: ISetSelectionsOperationParams = {
- unitId, subUnitId, pluginName: NORMAL_SELECTION_PLUGIN_NAME,
+ unitId, subUnitId,
selections: ranges.map((range) => ({
range,
primary: getPrimaryForRange(range, worksheet),
diff --git a/packages/sheets/src/commands/commands/set-style.command.ts b/packages/sheets/src/commands/commands/set-style.command.ts
index 83aeeaa4ad..84a01eeb9e 100644
--- a/packages/sheets/src/commands/commands/set-style.command.ts
+++ b/packages/sheets/src/commands/commands/set-style.command.ts
@@ -39,7 +39,7 @@ import {
} from '@univerjs/core';
import type { IAccessor } from '@wendellhu/redi';
-import { SelectionManagerService } from '../../services/selection-manager.service';
+import { SheetsSelectionsService } from '../../services/selections/selection-manager.service';
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';
@@ -79,9 +79,9 @@ export const SetStyleCommand: ICommand<ISetStyleCommandParams<unknown>> = {
const { range, style } = params;
const commandService = accessor.get(ICommandService);
const undoRedoService = accessor.get(IUndoRedoService);
- const selectionManagerService = accessor.get(SelectionManagerService);
+ const selectionManagerService = accessor.get(SheetsSelectionsService);
- const ranges = range ? [range] : selectionManagerService.getSelectionRanges();
+ const ranges = range ? [range] : selectionManagerService.getCurrentSelections()?.map((s) => s.range);
if (!ranges?.length) {
return false;
}
@@ -156,7 +156,7 @@ export const SetBoldCommand: ICommand = {
type: CommandType.COMMAND,
id: 'sheet.command.set-bold',
handler: async (accessor) => {
- const selection = accessor.get(SelectionManagerService).getLast();
+ const selection = accessor.get(SheetsSelectionsService).getCurrentLastSelection();
if (!selection) return false;
const target = getSheetCommandTarget(accessor.get(IUniverInstanceService));
@@ -185,7 +185,7 @@ export const SetItalicCommand: ICommand = {
type: CommandType.COMMAND,
id: 'sheet.command.set-italic',
handler: async (accessor) => {
- const selection = accessor.get(SelectionManagerService).getLast();
+ const selection = accessor.get(SheetsSelectionsService).getCurrentLastSelection();
if (!selection) return false;
const target = getSheetCommandTarget(accessor.get(IUniverInstanceService));
@@ -218,7 +218,7 @@ export const SetUnderlineCommand: ICommand = {
type: CommandType.COMMAND,
id: 'sheet.command.set-underline',
handler: async (accessor) => {
- const selection = accessor.get(SelectionManagerService).getLast();
+ const selection = accessor.get(SheetsSelectionsService).getCurrentLastSelection();
if (!selection) return false;
const target = getSheetCommandTarget(accessor.get(IUniverInstanceService));
@@ -253,7 +253,7 @@ export const SetStrikeThroughCommand: ICommand = {
type: CommandType.COMMAND,
id: 'sheet.command.set-stroke',
handler: async (accessor) => {
- const selection = accessor.get(SelectionManagerService).getLast();
+ const selection = accessor.get(SheetsSelectionsService).getCurrentLastSelection();
if (!selection) return false;
const target = getSheetCommandTarget(accessor.get(IUniverInstanceService));
@@ -286,7 +286,7 @@ export const SetOverlineCommand: ICommand = {
type: CommandType.COMMAND,
id: 'sheet.command.set-overline',
handler: async (accessor) => {
- const selection = accessor.get(SelectionManagerService).getLast();
+ const selection = accessor.get(SheetsSelectionsService).getCurrentLastSelection();
if (!selection) return false;
const target = getSheetCommandTarget(accessor.get(IUniverInstanceService));
diff --git a/packages/sheets/src/commands/commands/set-worksheet-col-width.command.ts b/packages/sheets/src/commands/commands/set-worksheet-col-width.command.ts
index 1f1e512893..de6d93094b 100644
--- a/packages/sheets/src/commands/commands/set-worksheet-col-width.command.ts
+++ b/packages/sheets/src/commands/commands/set-worksheet-col-width.command.ts
@@ -26,7 +26,7 @@ import {
} from '@univerjs/core';
import type { IAccessor } from '@wendellhu/redi';
-import { SelectionManagerService } from '../../services/selection-manager.service';
+import { SheetsSelectionsService } from '../../services/selections/selection-manager.service';
import { SheetInterceptorService } from '../../services/sheet-interceptor/sheet-interceptor.service';
import type { ISetWorksheetColWidthMutationParams } from '../mutations/set-worksheet-col-width.mutation';
import {
@@ -45,8 +45,8 @@ export const DeltaColumnWidthCommand: ICommand<IDeltaColumnWidthCommandParams> =
id: 'sheet.command.delta-column-width',
// eslint-disable-next-line max-lines-per-function
handler: async (accessor: IAccessor, params: IDeltaColumnWidthCommandParams) => {
- const selectionManagerService = accessor.get(SelectionManagerService);
- const selections = selectionManagerService.getSelections();
+ const selectionManagerService = accessor.get(SheetsSelectionsService);
+ const selections = selectionManagerService.getCurrentSelections();
const sheetInterceptorService = accessor.get(SheetInterceptorService);
if (!selections?.length) {
@@ -154,12 +154,12 @@ export const SetColWidthCommand: ICommand = {
type: CommandType.COMMAND,
id: 'sheet.command.set-worksheet-col-width',
handler: async (accessor: IAccessor, params: ISetColWidthCommandParams) => {
- const selectionManagerService = accessor.get(SelectionManagerService);
+ const selectionManagerService = accessor.get(SheetsSelectionsService);
const commandService = accessor.get(ICommandService);
const undoRedoService = accessor.get(IUndoRedoService);
const sheetInterceptorService = accessor.get(SheetInterceptorService);
- const selections = selectionManagerService.getSelectionRanges();
+ const selections = selectionManagerService.getCurrentSelections()?.map((s) => s.range);
if (!selections?.length) return false;
const target = getSheetCommandTarget(accessor.get(IUniverInstanceService));
diff --git a/packages/sheets/src/commands/commands/set-worksheet-row-height.command.ts b/packages/sheets/src/commands/commands/set-worksheet-row-height.command.ts
index accd9ddfaf..bbc3be5797 100644
--- a/packages/sheets/src/commands/commands/set-worksheet-row-height.command.ts
+++ b/packages/sheets/src/commands/commands/set-worksheet-row-height.command.ts
@@ -27,7 +27,7 @@ import {
} from '@univerjs/core';
import type { IAccessor } from '@wendellhu/redi';
-import { SelectionManagerService } from '../../services/selection-manager.service';
+import { SheetsSelectionsService } from '../../services/selections/selection-manager.service';
import { SheetInterceptorService } from '../../services/sheet-interceptor/sheet-interceptor.service';
import type {
ISetWorksheetRowHeightMutationParams,
@@ -51,8 +51,8 @@ export const DeltaRowHeightCommand: ICommand = {
id: 'sheet.command.delta-row-height',
// eslint-disable-next-line max-lines-per-function
handler: async (accessor: IAccessor, params: IDeltaRowHeightCommand) => {
- const selectionManagerService = accessor.get(SelectionManagerService);
- const selections = selectionManagerService.getSelections();
+ const selectionManagerService = accessor.get(SheetsSelectionsService);
+ const selections = selectionManagerService.getCurrentSelections();
const sheetInterceptorService = accessor.get(SheetInterceptorService);
if (!selections?.length) {
@@ -197,13 +197,13 @@ export const SetRowHeightCommand: ICommand = {
id: 'sheet.command.set-row-height',
// eslint-disable-next-line max-lines-per-function
handler: (accessor: IAccessor, params: ISetRowHeightCommandParams) => {
- const selectionManagerService = accessor.get(SelectionManagerService);
+ const selectionManagerService = accessor.get(SheetsSelectionsService);
const commandService = accessor.get(ICommandService);
const undoRedoService = accessor.get(IUndoRedoService);
const univerInstanceService = accessor.get(IUniverInstanceService);
const sheetInterceptorService = accessor.get(SheetInterceptorService);
- const selections = selectionManagerService.getSelectionRanges();
+ const selections = selectionManagerService.getCurrentSelections()?.map((s) => s.range);
if (!selections?.length) {
return false;
}
@@ -298,7 +298,7 @@ export const SetWorksheetRowIsAutoHeightCommand: ICommand = {
handler: async (accessor: IAccessor, params: ISetWorksheetRowIsAutoHeightCommandParams) => {
const commandService = accessor.get(ICommandService);
const undoRedoService = accessor.get(IUndoRedoService);
- const selectionManagerService = accessor.get(SelectionManagerService);
+ const selectionManagerService = accessor.get(SheetsSelectionsService);
const univerInstanceService = accessor.get(IUniverInstanceService);
const target = getSheetCommandTarget(univerInstanceService);
@@ -317,7 +317,7 @@ export const SetWorksheetRowIsAutoHeightCommand: ICommand = {
endColumn: worksheet.getMaxColumns() - 1,
},
]
- : selectionManagerService.getSelectionRanges();
+ : selectionManagerService.getCurrentSelections()?.map((s) => s.range);
if (!ranges?.length) {
return false;
diff --git a/packages/sheets/src/commands/commands/utils/selection-utils.ts b/packages/sheets/src/commands/commands/utils/selection-utils.ts
index f4af3c257d..418a98b688 100644
--- a/packages/sheets/src/commands/commands/utils/selection-utils.ts
+++ b/packages/sheets/src/commands/commands/utils/selection-utils.ts
@@ -17,7 +17,6 @@
import type { IRange, ISelectionCell, Nullable, Workbook, Worksheet } from '@univerjs/core';
import { RANGE_TYPE, Rectangle, selectionToArray } from '@univerjs/core';
-import { NORMAL_SELECTION_PLUGIN_NAME } from '../../../services/selection-manager.service';
import type { ISetSelectionsOperationParams } from '../../operations/selection.operation';
import { SetSelectionsOperation } from '../../operations/selection.operation';
import type { ISelectionWithStyle } from '../../../basics/selection';
@@ -192,7 +191,7 @@ export const followSelectionOperation = (range: IRange, workbook: Workbook, work
params: {
unitId: workbook.getUnitId(),
subUnitId: worksheet.getSheetId(),
- pluginName: NORMAL_SELECTION_PLUGIN_NAME,
+
selections: [{ range, primary: getPrimaryForRange(range, worksheet) }],
} as ISetSelectionsOperationParams,
});
diff --git a/packages/sheets/src/commands/commands/utils/target-util.ts b/packages/sheets/src/commands/commands/utils/target-util.ts
index 627f32e86b..043be86efe 100644
--- a/packages/sheets/src/commands/commands/utils/target-util.ts
+++ b/packages/sheets/src/commands/commands/utils/target-util.ts
@@ -58,7 +58,7 @@ export function getSheetCommandTarget(univerInstanceService: IUniverInstanceServ
: univerInstanceService.getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET);
if (!workbook) return null;
- const worksheet = subUnitId ? workbook.getSheetBySheetId(subUnitId) : workbook.getActiveSheet();
+ const worksheet = subUnitId ? workbook.getSheetBySheetId(subUnitId) : workbook.getActiveSheet(true);
if (!worksheet) {
return null;
}
diff --git a/packages/sheets/src/commands/operations/selection.operation.ts b/packages/sheets/src/commands/operations/selection.operation.ts
index 4654d729d9..a02ac6c0dc 100644
--- a/packages/sheets/src/commands/operations/selection.operation.ts
+++ b/packages/sheets/src/commands/operations/selection.operation.ts
@@ -18,13 +18,12 @@ import type { IOperation } from '@univerjs/core';
import { CommandType } from '@univerjs/core';
import type { ISelectionWithStyle } from '../../basics/selection';
-import type { SelectionMoveType } from '../../services/selection-manager.service';
-import { SelectionManagerService } from '../../services/selection-manager.service';
+import type { SelectionMoveType } from '../../services/selections/selection-manager.service';
+import { getSelectionsService } from '../utils/selection-command-util';
export interface ISetSelectionsOperationParams {
unitId: string;
subUnitId: string;
- pluginName: string;
selections: ISelectionWithStyle[];
type?: SelectionMoveType;
}
@@ -33,13 +32,11 @@ export const SetSelectionsOperation: IOperation<ISetSelectionsOperationParams> =
id: 'sheet.operation.set-selections',
type: CommandType.OPERATION,
handler: (accessor, params) => {
- const selectionManagerService = accessor.get(SelectionManagerService);
- if (!params) {
- return false;
- }
+ if (!params) return false;
- const { selections, type } = params;
- selectionManagerService.replace(selections, type);
+ const { selections, type, unitId, subUnitId } = params;
+ const selectionManagerService = getSelectionsService(accessor);
+ selectionManagerService.setSelections(unitId, subUnitId, selections, type);
return true;
},
diff --git a/packages/sheets/src/commands/utils/handle-merge-operation.ts b/packages/sheets/src/commands/utils/handle-merge-operation.ts
index 19d6cc373a..116c9f07d6 100644
--- a/packages/sheets/src/commands/utils/handle-merge-operation.ts
+++ b/packages/sheets/src/commands/utils/handle-merge-operation.ts
@@ -18,13 +18,13 @@ import type { IAccessor } from '@wendellhu/redi';
import type { IRange } from '@univerjs/core';
import { Dimension } from '@univerjs/core';
import type { IAddMergeCommandParams } from '../commands/add-worksheet-merge.command';
-import { NORMAL_SELECTION_PLUGIN_NAME, SelectionManagerService } from '../../services/selection-manager.service';
+import { SheetsSelectionsService } from '../../services/selections/selection-manager.service';
import type { ISetSelectionsOperationParams } from '../operations/selection.operation';
import { SetSelectionsOperation } from '../operations/selection.operation';
export const AddMergeRedoSelectionsOperationFactory = (accessor: IAccessor, params: IAddMergeCommandParams, ranges: IRange[]) => {
- const selectionManagerService = accessor.get(SelectionManagerService);
- const selectionsBeforeMutation = selectionManagerService.getSelections();
+ const selectionManagerService = accessor.get(SheetsSelectionsService);
+ const selectionsBeforeMutation = selectionManagerService.getCurrentSelections();
const { value, selections, unitId, subUnitId } = params;
if (selectionsBeforeMutation) {
const lastSelectionBeforeMutation = selectionsBeforeMutation[selectionsBeforeMutation?.length - 1];
@@ -67,7 +67,7 @@ export const AddMergeRedoSelectionsOperationFactory = (accessor: IAccessor, para
const setSelectionsParamByRedo: ISetSelectionsOperationParams = {
unitId,
subUnitId,
- pluginName: NORMAL_SELECTION_PLUGIN_NAME,
+
selections: selectionsByRedo,
};
return {
@@ -81,8 +81,8 @@ export const AddMergeRedoSelectionsOperationFactory = (accessor: IAccessor, para
};
export const AddMergeUndoSelectionsOperationFactory = (accessor: IAccessor, params: IAddMergeCommandParams) => {
- const selectionManagerService = accessor.get(SelectionManagerService);
- const selectionsBeforeMutation = selectionManagerService.getSelections();
+ const selectionManagerService = accessor.get(SheetsSelectionsService);
+ const selectionsBeforeMutation = selectionManagerService.getCurrentSelections();
const { unitId, subUnitId } = params;
if (selectionsBeforeMutation) {
const lastSelectionBeforeMutation = selectionsBeforeMutation[selectionsBeforeMutation?.length - 1];
@@ -91,7 +91,7 @@ export const AddMergeUndoSelectionsOperationFactory = (accessor: IAccessor, para
const setSelectionsParamByUndo: ISetSelectionsOperationParams = {
unitId,
subUnitId,
- pluginName: NORMAL_SELECTION_PLUGIN_NAME,
+
selections: [...selectionsBeforeMutation],
};
return {
diff --git a/packages/sheets/src/commands/utils/selection-command-util.ts b/packages/sheets/src/commands/utils/selection-command-util.ts
new file mode 100644
index 0000000000..b7ff564f5b
--- /dev/null
+++ b/packages/sheets/src/commands/utils/selection-command-util.ts
@@ -0,0 +1,29 @@
+/**
+ * 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 { IAccessor } from '@wendellhu/redi';
+import { IContextService } from '@univerjs/core';
+import { DISABLE_NORMAL_SELECTIONS, SheetsSelectionsService } from '../../services/selections/selection-manager.service';
+import { IRefSelectionsService } from '../../services/selections/ref-selections.service';
+
+export function getSelectionsService(
+ accessor: IAccessor
+): SheetsSelectionsService {
+ const contextService = accessor.get(IContextService);
+ const disabledNormalSelections = contextService.getContextValue(DISABLE_NORMAL_SELECTIONS);
+
+ return accessor.get(disabledNormalSelections ? IRefSelectionsService : SheetsSelectionsService);
+}
diff --git a/packages/sheets/src/controllers/merge-cell.controller.ts b/packages/sheets/src/controllers/merge-cell.controller.ts
index 4caf0bf6c1..134d8c261a 100644
--- a/packages/sheets/src/controllers/merge-cell.controller.ts
+++ b/packages/sheets/src/controllers/merge-cell.controller.ts
@@ -65,7 +65,7 @@ import { RefRangeService } from '../services/ref-range/ref-range.service';
import type { EffectRefRangeParams } from '../services/ref-range/type';
import { EffectRefRangId } from '../services/ref-range/type';
import { handleMoveCols, handleMoveRows, runRefRangeMutations } from '../services/ref-range/util';
-import { SelectionManagerService } from '../services/selection-manager.service';
+import { SheetsSelectionsService } from '../services/selections/selection-manager.service';
import { SheetInterceptorService } from '../services/sheet-interceptor/sheet-interceptor.service';
import type { IMoveRowsMutationParams } from '../commands/mutations/move-rows-cols.mutation';
import { MoveColsMutation, MoveRowsMutation } from '../commands/mutations/move-rows-cols.mutation';
@@ -126,7 +126,7 @@ export class MergeCellController extends Disposable {
@Inject(IUniverInstanceService) private readonly _univerInstanceService: IUniverInstanceService,
@Inject(Injector) private _injector: Injector,
@Inject(SheetInterceptorService) private _sheetInterceptorService: SheetInterceptorService,
- @Inject(SelectionManagerService) private _selectionManagerService: SelectionManagerService
+ @Inject(SheetsSelectionsService) private _selectionManagerService: SheetsSelectionsService
) {
super();
this._onRefRangeChange();
@@ -151,7 +151,7 @@ export class MergeCellController extends Disposable {
const subUnitId = worksheet.getSheetId();
const mergeData = worksheet.getConfig().mergeData;
- const selections = self._selectionManagerService.getSelectionRanges();
+ const selections = self._selectionManagerService.getCurrentSelections()?.map((s) => s.range);
if (selections && selections.length > 0) {
const isHasMerge = selections.some((range) =>
mergeData.some((item) => Rectangle.intersects(item, range))
diff --git a/packages/sheets/src/index.ts b/packages/sheets/src/index.ts
index e569f54536..faf41ae0c1 100644
--- a/packages/sheets/src/index.ts
+++ b/packages/sheets/src/index.ts
@@ -46,6 +46,7 @@ export {
export { rangeMerge, createTopMatrixFromRanges, createTopMatrixFromMatrix, findAllRectangle, RangeMergeUtil } from './basics/rangeMerge';
export { getSheetCommandTarget, getSheetCommandTargetWorkbook, getSheetMutationTarget } from './commands/commands/utils/target-util';
export { alignToMergedCellsBorders, getCellAtRowCol, setEndForRange, isSingleCellSelection } from './commands/commands/utils/selection-utils';
+export { getSelectionsService } from './commands/utils/selection-command-util';
export { followSelectionOperation, getPrimaryForRange } from './commands/commands/utils/selection-utils';
export { handleDeleteRangeMutation } from './commands/utils/handle-range-mutation';
export { getInsertRangeMutations, getRemoveRangeMutations } from './commands/utils/handle-range-mutation';
@@ -57,10 +58,12 @@ export * from './services/permission/permission-point';
export { WorksheetPermissionService } from './services/permission/worksheet-permission/worksheet-permission.service';
export { WorkbookPermissionService } from './services/permission/workbook-permission/workbook-permission.service';
export {
- NORMAL_SELECTION_PLUGIN_NAME,
- SelectionManagerService,
+ SheetsSelectionsService,
+ WorkbookSelections,
SelectionMoveType,
-} from './services/selection-manager.service';
+ DISABLE_NORMAL_SELECTIONS,
+} from './services/selections/selection-manager.service';
+export { IRefSelectionsService } from './services/selections/ref-selections.service';
export { getAddMergeMutationRangeByType } from './controllers/merge-cell.controller';
export { NumfmtService } from './services/numfmt/numfmt.service';
diff --git a/packages/sheets/src/services/__tests__/ref-range.setvice.spec.ts b/packages/sheets/src/services/__tests__/ref-range.setvice.spec.ts
index f7efb91bef..6fd94fb53b 100644
--- a/packages/sheets/src/services/__tests__/ref-range.setvice.spec.ts
+++ b/packages/sheets/src/services/__tests__/ref-range.setvice.spec.ts
@@ -24,7 +24,7 @@ import { MoveRangeCommand } from '../../commands/commands/move-range.command';
import { MoveRangeMutation } from '../../commands/mutations/move-range.mutation';
import { SetSelectionsOperation } from '../../commands/operations/selection.operation';
import { RefRangeService } from '../ref-range/ref-range.service';
-import { SelectionManagerService } from '../selection-manager.service';
+import { SheetsSelectionsService } from '../selections/selection-manager.service';
import { SheetInterceptorService } from '../sheet-interceptor/sheet-interceptor.service';
import { createTestBase, TEST_WORKBOOK_DATA_DEMO } from './util';
@@ -51,7 +51,7 @@ describe('Test ref-range.service', () => {
beforeEach(() => {
const testBed = createTestBase(TEST_WORKBOOK_DATA_DEMO, [
- [SelectionManagerService],
+ [SheetsSelectionsService],
[RefRangeService],
[SheetInterceptorService],
]);
diff --git a/packages/sheets/src/services/ref-range/__tests__/ref-range.service.spec.ts b/packages/sheets/src/services/ref-range/__tests__/ref-range.service.spec.ts
index bd7a909617..4727584392 100644
--- a/packages/sheets/src/services/ref-range/__tests__/ref-range.service.spec.ts
+++ b/packages/sheets/src/services/ref-range/__tests__/ref-range.service.spec.ts
@@ -21,7 +21,7 @@ import type { Dependency } from '@wendellhu/redi';
import { Inject, Injector } from '@wendellhu/redi';
import { RefRangeService } from '../ref-range.service';
-import { SelectionManagerService } from '../../selection-manager.service';
+import { SheetsSelectionsService } from '../../selections/selection-manager.service';
import { InsertColMutation } from '../../../commands/mutations/insert-row-col.mutation';
import type { IInsertColMutationParams } from '../../../basics';
import { SheetInterceptorService } from '../../sheet-interceptor/sheet-interceptor.service';
@@ -74,7 +74,7 @@ export function createRefRangeTestBed() {
([
[RefRangeService],
- [SelectionManagerService],
+ [SheetsSelectionsService],
[SheetInterceptorService],
] as Dependency[]).forEach((d) => injector.add(d));
diff --git a/packages/sheets/src/services/ref-range/ref-range.service.ts b/packages/sheets/src/services/ref-range/ref-range.service.ts
index 2efc818895..429e4f7b13 100644
--- a/packages/sheets/src/services/ref-range/ref-range.service.ts
+++ b/packages/sheets/src/services/ref-range/ref-range.service.ts
@@ -32,7 +32,7 @@ import {
import type { IDisposable } from '@wendellhu/redi';
import { Inject } from '@wendellhu/redi';
-import { SelectionManagerService } from '../selection-manager.service';
+import { SheetsSelectionsService } from '../selections/selection-manager.service';
import { SheetInterceptorService } from '../sheet-interceptor/sheet-interceptor.service';
import type { ISheetCommandSharedParams } from '../../commands/utils/interface';
import type { EffectRefRangeParams } from './type';
@@ -102,7 +102,7 @@ export class RefRangeService extends Disposable {
@ICommandService private readonly _commandService: ICommandService,
@Inject(SheetInterceptorService) private _sheetInterceptorService: SheetInterceptorService,
@Inject(IUniverInstanceService) private _univerInstanceService: IUniverInstanceService,
- @Inject(SelectionManagerService) private _selectionManagerService: SelectionManagerService
+ @Inject(SheetsSelectionsService) private _selectionManagerService: SheetsSelectionsService
) {
super();
this._onRefRangeChange();
@@ -424,8 +424,8 @@ function getSubUnitId(univerInstanceService: IUniverInstanceService) {
return univerInstanceService.getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET)!.getActiveSheet()?.getSheetId();
}
-function getSelectionRanges(selectionManagerService: SelectionManagerService) {
- return selectionManagerService.getSelectionRanges() || [];
+function getSelectionRanges(selectionManagerService: SheetsSelectionsService) {
+ return selectionManagerService.getCurrentSelections()?.map((s) => s.range) || [];
}
function getRefRangId(unitId: string, subUnitId: string) {
diff --git a/packages/sheets/src/services/ref-range/util.ts b/packages/sheets/src/services/ref-range/util.ts
index e70ad1dfb3..31afe52bc4 100644
--- a/packages/sheets/src/services/ref-range/util.ts
+++ b/packages/sheets/src/services/ref-range/util.ts
@@ -24,7 +24,7 @@ import { RemoveSheetMutation } from '../../commands/mutations/remove-sheet.mutat
import { RemoveColMutation, RemoveRowMutation } from '../../commands/mutations/remove-row-col.mutation';
import { InsertColMutation, InsertRowMutation } from '../../commands/mutations/insert-row-col.mutation';
import type { ISheetCommandSharedParams } from '../../commands/utils/interface';
-import type { SelectionManagerService } from '../selection-manager.service';
+import type { SheetsSelectionsService } from '../selections/selection-manager.service';
import type {
EffectRefRangeParams,
IDeleteRangeMoveLeftCommand,
@@ -965,7 +965,7 @@ export const handleDefaultRangeChangeWithEffectRefCommands = (range: IRange, com
return resultRange;
};
-export const handleDefaultRangeChangeWithEffectRefCommandsSkipNoInterests = (range: IRange, commandInfo: ICommandInfo, deps: { selectionManagerService: SelectionManagerService }) => {
+export const handleDefaultRangeChangeWithEffectRefCommandsSkipNoInterests = (range: IRange, commandInfo: ICommandInfo, deps: { selectionManagerService: SheetsSelectionsService }) => {
const effectRanges = getEffectedRangesOnCommand(commandInfo as EffectRefRangeParams, deps);
if (effectRanges.some((effectRange) => Rectangle.intersects(effectRange, range))) {
return handleDefaultRangeChangeWithEffectRefCommands(range, commandInfo);
@@ -1115,7 +1115,7 @@ export function adjustRangeOnMutation(range: Readonly<IRange>, mutation: IMutati
}
// eslint-disable-next-line max-lines-per-function
-export function getEffectedRangesOnCommand(command: EffectRefRangeParams, deps: { selectionManagerService: SelectionManagerService }) {
+export function getEffectedRangesOnCommand(command: EffectRefRangeParams, deps: { selectionManagerService: SheetsSelectionsService }) {
const { selectionManagerService } = deps;
switch (command.id) {
case EffectRefRangId.MoveColsCommandId: {
@@ -1179,7 +1179,7 @@ export function getEffectedRangesOnCommand(command: EffectRefRangeParams, deps:
case EffectRefRangId.DeleteRangeMoveUpCommandId:
case EffectRefRangId.InsertRangeMoveDownCommandId: {
const params = command;
- const range = params.params?.range || selectionManagerService.getSelectionRanges()?.[0];
+ const range = params.params?.range || selectionManagerService.getCurrentSelections()?.map((s) => s.range)?.[0];
if (!range) {
return [];
}
@@ -1188,7 +1188,7 @@ export function getEffectedRangesOnCommand(command: EffectRefRangeParams, deps:
case EffectRefRangId.DeleteRangeMoveLeftCommandId:
case EffectRefRangId.InsertRangeMoveRightCommandId: {
const params = command;
- const range = params.params?.range || selectionManagerService.getSelectionRanges()?.[0];
+ const range = params.params?.range || selectionManagerService.getCurrentSelections()?.map((s) => s.range)?.[0];
if (!range) {
return [];
}
diff --git a/packages/sheets/src/services/selection-manager.service.ts b/packages/sheets/src/services/selection-manager.service.ts
deleted file mode 100644
index 24ef161adb..0000000000
--- a/packages/sheets/src/services/selection-manager.service.ts
+++ /dev/null
@@ -1,454 +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 IRange, type ISelectionCell, type Nullable, ThemeService } from '@univerjs/core';
-import { type IDisposable, Inject } from '@wendellhu/redi';
-import { BehaviorSubject, Subject } from 'rxjs';
-
-import type { ISelectionStyle, ISelectionWithStyle } from '../basics/selection';
-
-export const NORMAL_SELECTION_PLUGIN_NAME = 'normalSelectionPluginName';
-
-export interface ISelectionManagerSearchParam {
- pluginName: string;
- unitId: string;
- sheetId: string;
-}
-
-export interface ISelectionManagerInsertParam extends ISelectionManagerSearchParam {
- selectionDatas: ISelectionWithStyle[];
-}
-
-//{ [pluginName: string]: { [unitId: string]: { [sheetId: string]: ISelectionWithCoord[] } } }
-export type ISelectionInfo = Map<string, Map<string, Map<string, ISelectionWithStyle[]>>>;
-
-export enum SelectionMoveType {
- MOVE_START,
- MOVING,
- MOVE_END,
-}
-
-/**
- * This service is responsible for managing the selection data.
- *
- * You can generally modify its data through SetSelectionsOperation.
- *
- * In the same app and sub-table, there will be different functional selection areas,
- * such as charts, formulas, conditional formats, etc.,
- * which are distinguished by the pluginName.
- *
- * The selection data drawn by the user through the SelectionRenderService will be saved to this service.
- *
- * Data changes within the service will also notify the SelectionController to redraw the selection area.
- *
- * Not only will switching sub-tables trigger a redraw, but also changing row and column widths,
- * hiding rows and columns, automatic row height, dragging rows and columns, deleting rows and columns,
- * and so on, will cause the size of the selection area to change.
- */
-export class SelectionManagerService implements IDisposable {
- private readonly _selectionInfo: ISelectionInfo = new Map();
-
- private _searchParamForSelection: Nullable<ISelectionManagerSearchParam> = null;
-
- private readonly _selectionMoveStart$ = new Subject<Nullable<ISelectionWithStyle[]>>();
- readonly selectionMoveStart$ = this._selectionMoveStart$.asObservable();
-
- private readonly _selectionMoving$ = new Subject<Nullable<ISelectionWithStyle[]>>();
- readonly selectionMoving$ = this._selectionMoving$.asObservable();
-
- private readonly _selectionMoveEnd$ = new BehaviorSubject<Nullable<ISelectionWithStyle[]>>(null);
- readonly selectionMoveEnd$ = this._selectionMoveEnd$.asObservable();
-
- private readonly _selectionMoveEndBefore$ = new BehaviorSubject<Nullable<ISelectionWithStyle[]>>(null);
- readonly selectionMoveEndBefore$ = this._selectionMoveEndBefore$.asObservable();
-
- private _dirty: boolean = true;
-
- // FIMXE: this dependency is not correct!
- constructor(@Inject(ThemeService) private readonly _themeService: ThemeService) {
- // empty
- }
-
- getCurrent() {
- return this._searchParamForSelection;
- }
-
- getLastByPlugin(pluginName: string) {
- if (this._searchParamForSelection == null) {
- return;
- }
- return this._getLastByParam({ ...this._searchParamForSelection, pluginName });
- }
-
- changePlugin(pluginName: string) {
- if (this._searchParamForSelection == null) {
- return;
- }
- this._searchParamForSelection = {
- pluginName,
- unitId: this._searchParamForSelection?.unitId,
- sheetId: this._searchParamForSelection?.sheetId,
- };
-
- this._refresh(this._searchParamForSelection);
- }
-
- changePluginNoRefresh(pluginName: string) {
- if (this._searchParamForSelection == null || this._searchParamForSelection.pluginName === pluginName) {
- return;
- }
-
- // Fetch the old selections.
- const selections = this.getSelectionDatasByParam(this._searchParamForSelection);
-
- this._searchParamForSelection = {
- pluginName,
- unitId: this._searchParamForSelection?.unitId,
- sheetId: this._searchParamForSelection?.sheetId,
- };
-
- if (selections != null) {
- this.add([]);
- }
- }
-
- reset() {
- if (this._searchParamForSelection == null) {
- return;
- }
- this._searchParamForSelection = {
- pluginName: NORMAL_SELECTION_PLUGIN_NAME,
- unitId: this._searchParamForSelection?.unitId,
- sheetId: this._searchParamForSelection?.sheetId,
- };
- this._selectionInfo.clear();
-
- this._refresh(this._searchParamForSelection);
- }
-
- resetPlugin() {
- if (this._searchParamForSelection == null) {
- return;
- }
-
- this._searchParamForSelection.pluginName = NORMAL_SELECTION_PLUGIN_NAME;
- this._refresh(this._searchParamForSelection);
- }
-
- dispose(): void {
- this._selectionMoveEnd$.complete();
- this._selectionMoveStart$.complete();
- this._selectionMoving$.complete();
- }
-
- makeDirty(dirty: boolean = true) {
- this._dirty = dirty;
- }
-
- refreshSelection() {
- if (this._searchParamForSelection == null) {
- return;
- }
-
- this._refresh(this._searchParamForSelection);
- }
-
- setCurrentSelection(param: ISelectionManagerSearchParam) {
- if (this._dirty === false) {
- return;
- }
-
- this._searchParamForSelection = param;
- this._refresh(param);
- }
-
- setCurrentSelectionNotRefresh(param: ISelectionManagerSearchParam) {
- this._searchParamForSelection = param;
- }
-
- getSelectionInfo(): Readonly<ISelectionInfo> {
- return this._selectionInfo;
- }
-
- getSelectionDatasByParam(param: Nullable<ISelectionManagerSearchParam>): Readonly<Nullable<ISelectionWithStyle[]>> {
- return this._getSelectionDatas(param);
- }
-
- getSelections(): Readonly<Nullable<ISelectionWithStyle[]>> {
- return this._getSelectionDatas(this._searchParamForSelection);
- }
-
- getSelectionRanges(): Nullable<IRange[]> {
- const selectionDataList = this.getSelections();
- if (selectionDataList == null) {
- return;
- }
-
- return selectionDataList.map((selectionData: ISelectionWithStyle) => selectionData.range);
- }
-
- getFirst(): Readonly<Nullable<ISelectionWithStyle>> {
- return this._getFirstByParam(this._searchParamForSelection);
- }
-
- getLast(): Readonly<Nullable<ISelectionWithStyle & { primary: ISelectionCell }>> {
- // The last selection position must have a primary.
- return this._getLastByParam(this._searchParamForSelection) as Readonly<
- Nullable<ISelectionWithStyle & { primary: ISelectionCell }>
- >;
- }
-
- addNoRefresh(selectionDatas: ISelectionWithStyle[]) {
- if (this._searchParamForSelection == null) {
- return;
- }
- this._addByParam(
- {
- ...this._searchParamForSelection,
- selectionDatas,
- },
- false
- );
- }
-
- add(selectionDatas: ISelectionWithStyle[]) {
- if (this._searchParamForSelection == null) {
- return;
- }
-
- this._addByParam({
- ...this._searchParamForSelection,
- selectionDatas,
- });
- }
-
- replace(selectionDatas: ISelectionWithStyle[], type: SelectionMoveType = SelectionMoveType.MOVE_END) {
- if (this._searchParamForSelection == null) {
- return;
- }
-
- this._replaceByParam({
- ...this._searchParamForSelection,
- selectionDatas,
- });
-
- if (type === SelectionMoveType.MOVE_START) {
- this._refreshStart(this._searchParamForSelection);
- } else if (type === SelectionMoveType.MOVING) {
- this._refreshMoving(this._searchParamForSelection);
- } else {
- // type == SelectionMoveType.MOVE_END
- this._refresh(this._searchParamForSelection);
- }
- }
-
- replaceWithNoRefresh(selectionDatas: ISelectionWithStyle[]) {
- if (this._searchParamForSelection == null) {
- return;
- }
- this._replaceByParam({
- ...this._searchParamForSelection,
- selectionDatas,
- });
- }
-
- clear(): void {
- if (this._searchParamForSelection == null) {
- return;
- }
- this._clearByParam(this._searchParamForSelection);
- }
-
- remove(index: number): void {
- if (this._searchParamForSelection == null) {
- return;
- }
-
- this._removeByParam(index, this._searchParamForSelection);
- }
-
- createDefaultAutoFillSelection(): ISelectionStyle {
- return {
- strokeWidth: 2,
- stroke: '#FFF000',
- fill: 'rgba(0, 0, 0, 0.2)',
- widgets: {},
- hasAutoFill: true,
- };
- }
-
- createCopyPasteSelection(): ISelectionStyle {
- return {
- strokeWidth: 1.5,
- stroke: this._themeService.getCurrentTheme().primaryColor,
- fill: 'rgba(178, 178, 178, 0.10)',
- widgets: {},
- hasAutoFill: false,
- strokeDash: 8,
- };
- }
-
- createDefaultSelection(): ISelectionStyle {
- return {
- strokeWidth: 2,
- stroke: '#FFF000',
- fill: 'rgba(0, 0, 0, 0.2)',
- widgets: { tr: true, tl: true, br: true, bl: true },
- hasAutoFill: false,
- };
- }
-
- /**
- * Determine whether multiple current selections overlap
- */
- isOverlapping(): boolean {
- const selectionDataList = this.getSelections();
- if (selectionDataList == null) {
- return false;
- }
-
- return selectionDataList.some(({ range }, index) =>
- selectionDataList.some(({ range: range2 }, index2) => {
- if (index === index2) {
- return false;
- }
- return (
- range.startRow <= range2.endRow &&
- range.endRow >= range2.startRow &&
- range.startColumn <= range2.endColumn &&
- range.endColumn >= range2.startColumn
- );
- })
- );
- }
-
- private _getSelectionDatas(param: Nullable<ISelectionManagerSearchParam>) {
- if (param == null) {
- return;
- }
- const { pluginName, unitId, sheetId } = param;
- return this._selectionInfo.get(pluginName)?.get(unitId)?.get(sheetId);
- }
-
- private _refresh(param?: ISelectionManagerSearchParam): void {
- // _selectionMoveEndBefore$ listener:
- // selection.render-controller _selectionManagerService.selectionMoveEndBefore$.subscribe
- // --> _selectionRenderService.reset() --> _clearSelectionControls()
- // --> _selectionRenderService.addCellSelectionControlBySelectionData()
- this._selectionMoveEndBefore$.next(this._getSelectionDatas(param));
- this._selectionMoveEnd$.next(this._getSelectionDatas(param));
- }
-
- private _refreshStart(param?: ISelectionManagerSearchParam): void {
- this._selectionMoveStart$.next(this._getSelectionDatas(param));
- }
-
- private _refreshMoving(param?: ISelectionManagerSearchParam): void {
- this._selectionMoving$.next(this._getSelectionDatas(param));
- }
-
- private _getFirstByParam(param: Nullable<ISelectionManagerSearchParam>): Readonly<Nullable<ISelectionWithStyle>> {
- const selectionData = this._getSelectionDatas(param);
-
- return selectionData?.[0];
- }
-
- private _getLastByParam(param: Nullable<ISelectionManagerSearchParam>): Readonly<Nullable<ISelectionWithStyle>> {
- const selectionData = this._getSelectionDatas(param);
-
- return selectionData?.[selectionData.length - 1];
- }
-
- private _addByParam(insertParam: ISelectionManagerInsertParam, isRefresh = true): void {
- const { pluginName, unitId, sheetId, selectionDatas } = insertParam;
-
- if (!this._selectionInfo.has(pluginName)) {
- this._selectionInfo.set(pluginName, new Map());
- }
-
- const unitSelectionData = this._selectionInfo.get(pluginName)!;
-
- if (!unitSelectionData.has(unitId)) {
- unitSelectionData.set(unitId, new Map());
- }
-
- const sheetSelectionData = unitSelectionData.get(unitId)!;
-
- if (!sheetSelectionData.has(sheetId)) {
- sheetSelectionData.set(sheetId, [...selectionDatas]);
- } else {
- let oldSelectionDatas = sheetSelectionData.get(sheetId);
- if (oldSelectionDatas == null) {
- oldSelectionDatas = [];
- sheetSelectionData.set(sheetId, oldSelectionDatas);
- }
- oldSelectionDatas.push(...selectionDatas);
- }
-
- if (isRefresh) {
- this._refresh({ pluginName, unitId, sheetId });
- }
- }
-
- private _replaceByParam(insertParam: ISelectionManagerInsertParam) {
- const { pluginName, unitId, sheetId, selectionDatas } = insertParam;
-
- if (!this._selectionInfo.has(pluginName)) {
- this._selectionInfo.set(pluginName, new Map());
- }
-
- const unitSelectionData = this._selectionInfo.get(pluginName)!;
-
- if (!unitSelectionData.has(unitId)) {
- unitSelectionData.set(unitId, new Map());
- }
-
- const sheetSelectionData = unitSelectionData.get(unitId)!;
-
- if (!sheetSelectionData.has(sheetId)) {
- sheetSelectionData.set(sheetId, selectionDatas);
- } else {
- let oldSelectionDatas = sheetSelectionData.get(sheetId);
- if (oldSelectionDatas == null) {
- oldSelectionDatas = [];
- sheetSelectionData.set(sheetId, oldSelectionDatas);
- }
- oldSelectionDatas.splice(0, oldSelectionDatas.length, ...selectionDatas);
- }
-
- // this.refresh({ pluginName, unitId, sheetId });
- }
-
- private _clearByParam(param: ISelectionManagerSearchParam): void {
- const selectionData = this._getSelectionDatas(param);
-
- selectionData?.splice(0);
-
- this._refresh(param);
- }
-
- private _removeByParam(index: number, param: ISelectionManagerSearchParam): void {
- const selectionData = this._getSelectionDatas(param);
-
- selectionData?.splice(index, 1);
-
- this._refresh(param);
- }
-
- // private refreshCurrentSelection(): void {
- // this._currentSelection$.next(this._currentSelection);
- // }
-}
diff --git a/packages/sheets/src/services/selections/ref-selections.service.ts b/packages/sheets/src/services/selections/ref-selections.service.ts
new file mode 100644
index 0000000000..0a84a45f22
--- /dev/null
+++ b/packages/sheets/src/services/selections/ref-selections.service.ts
@@ -0,0 +1,29 @@
+/**
+ * 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 { SheetsSelectionsService } from '@univerjs/sheets';
+import { createIdentifier } from '@wendellhu/redi';
+
+/**
+ * Ref selections service reuses code of `SelectionManagerService`. And it only contains ref selections
+ * when user is editing formula.
+ *
+ * Its data should be cleared by the caller quit editing formula and reconstructed when user starts editing.
+ */
+export const IRefSelectionsService = createIdentifier<SheetsSelectionsService>('sheets-formula.ref-selections.service');
+
+// TODO@wzhudev: `IRefSelectionsService` should have a total different implementation than `SheetsSelectionsService`
+// because ref ranges could from different units in a formula.
diff --git a/packages/sheets/src/services/selections/selection-manager.service.ts b/packages/sheets/src/services/selections/selection-manager.service.ts
new file mode 100644
index 0000000000..0c37b7e8ec
--- /dev/null
+++ b/packages/sheets/src/services/selections/selection-manager.service.ts
@@ -0,0 +1,275 @@
+/**
+ * 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 { ISelectionCell, Nullable, Workbook } from '@univerjs/core';
+import { Disposable, IUniverInstanceService, RxDisposable, UniverInstanceType } from '@univerjs/core';
+import type { Observable } from 'rxjs';
+import { BehaviorSubject, of, shareReplay, Subject, switchMap, takeUntil } from 'rxjs';
+
+import type { ISelectionWithStyle } from '../../basics/selection';
+
+export interface ISelectionManagerSearchParam {
+ unitId: string;
+ sheetId: string;
+}
+
+export enum SelectionMoveType {
+ MOVE_START,
+ MOVING,
+ MOVE_END,
+}
+
+export class SheetsSelectionsService extends RxDisposable {
+ private get _currentSelectionPos(): Nullable<ISelectionManagerSearchParam> {
+ const workbook = this._instanceSrv.getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET);
+ if (!workbook) return null;
+
+ const worksheet = workbook.getActiveSheet();
+ return { unitId: workbook.getUnitId(), sheetId: worksheet.getSheetId() };
+ }
+
+ readonly selectionMoveStart$: Observable<Nullable<ISelectionWithStyle[]>>;
+ readonly selectionMoving$: Observable<Nullable<ISelectionWithStyle[]>>;
+ readonly selectionMoveEnd$: Observable<ISelectionWithStyle[]>;
+
+ constructor(
+ @IUniverInstanceService private readonly _instanceSrv: IUniverInstanceService
+ ) {
+ super();
+
+ const c$ = this._instanceSrv.getCurrentTypeOfUnit$(UniverInstanceType.UNIVER_SHEET).pipe(shareReplay(1), takeUntil(this.dispose$));
+ this.selectionMoveStart$ = c$.pipe(switchMap((workbook) => !workbook ? of() : this._ensureWorkbookSelection(workbook.getUnitId()).selectionMoveStart$));
+ this.selectionMoving$ = c$.pipe(switchMap((workbook) => !workbook ? of() : this._ensureWorkbookSelection(workbook.getUnitId()).selectionMoving$));
+ this.selectionMoveEnd$ = c$.pipe(switchMap((workbook) => !workbook ? of([]) : this._ensureWorkbookSelection(workbook.getUnitId()).selectionMoveEnd$));
+
+ this._instanceSrv.getTypeOfUnitDisposed$(UniverInstanceType.UNIVER_SHEET).pipe(takeUntil(this.dispose$)).subscribe((workbook) => {
+ this._workbookSelections.delete(workbook.getUnitId());
+ });
+ }
+
+ /** Clear all selections in all workbooks. */
+ clear(): void {
+ this._workbookSelections.forEach((wbSelection) => wbSelection.clear());
+ }
+
+ getCurrentSelections(): Readonly<ISelectionWithStyle[]> {
+ return this._getCurrentSelections();
+ }
+
+ getCurrentLastSelection(): Readonly<Nullable<ISelectionWithStyle & { primary: ISelectionCell }>> {
+ const selectionData = this._getCurrentSelections();
+ return selectionData?.[selectionData.length - 1] as Readonly<Nullable<ISelectionWithStyle & { primary: ISelectionCell }>>;
+ }
+
+ addSelections(selectionsData: ISelectionWithStyle[]): void;
+ addSelections(unitId: string, worksheetId: string, selectionDatas: ISelectionWithStyle[]): void;
+ addSelections(unitIdOrSelections: string | ISelectionWithStyle[], worksheetId?: string, selectionDatas?: ISelectionWithStyle[]): void {
+ if (typeof unitIdOrSelections === 'string') {
+ this._ensureWorkbookSelection(unitIdOrSelections).addSelections(worksheetId!, selectionDatas!);
+ return;
+ }
+
+ const current = this._currentSelectionPos;
+ if (!current) {
+ throw new Error('[SheetsSelectionsService]: cannot find current selection position!');
+ }
+
+ const { unitId, sheetId } = current;
+ this._ensureWorkbookSelection(unitId).addSelections(sheetId, unitIdOrSelections);
+ }
+
+ setSelections(selectionDatas: ISelectionWithStyle[], type?: SelectionMoveType): void;
+ setSelections(unitId: string, worksheetId: string, selectionDatas: ISelectionWithStyle[], type?: SelectionMoveType): void;
+ setSelections(
+ unitIdOrSelections: string | ISelectionWithStyle[],
+ worksheetIdOrType: string | SelectionMoveType | undefined,
+ selectionDatas?: ISelectionWithStyle[],
+ type?: SelectionMoveType
+ ): void {
+ if (typeof unitIdOrSelections === 'string') {
+ this._ensureWorkbookSelection(unitIdOrSelections).setSelections(worksheetIdOrType as string, selectionDatas!, type ?? SelectionMoveType.MOVE_END);
+ return;
+ }
+
+ const current = this._currentSelectionPos;
+ if (!current) {
+ throw new Error('[SheetsSelectionsService]: cannot find current selection position!');
+ }
+
+ const { unitId, sheetId } = current;
+ this._ensureWorkbookSelection(unitId).setSelections(sheetId, unitIdOrSelections, worksheetIdOrType as SelectionMoveType ?? SelectionMoveType.MOVE_END);
+ }
+
+ clearCurrentSelections(): void {
+ const selectionData = this._getCurrentSelections();
+ selectionData.splice(0);
+ }
+
+ /**
+ * Determine whether multiple current selections overlap
+ *
+ * @deprecated this should be extracted to an pure function
+ */
+ isOverlapping(): boolean {
+ const selectionDataList = this.getCurrentSelections();
+ if (selectionDataList == null) {
+ return false;
+ }
+
+ return selectionDataList.some(({ range }, index) =>
+ selectionDataList.some(({ range: range2 }, index2) => {
+ if (index === index2) {
+ return false;
+ }
+ return (
+ range.startRow <= range2.endRow &&
+ range.endRow >= range2.startRow &&
+ range.startColumn <= range2.endColumn &&
+ range.endColumn >= range2.startColumn
+ );
+ })
+ );
+ }
+
+ private _getCurrentSelections() {
+ const current = this._currentSelectionPos;
+ if (!current) {
+ return [];
+ }
+
+ const { unitId, sheetId } = current;
+ return this._ensureWorkbookSelection(unitId).getSelectionOfWorksheet(sheetId);
+ }
+
+ getWorkbookSelections(unitId: string): WorkbookSelections {
+ return this._ensureWorkbookSelection(unitId);
+ }
+
+ private _workbookSelections = new Map<string, WorkbookSelections>();
+ private _ensureWorkbookSelection(unitId: string): WorkbookSelections {
+ let wbSelection = this._workbookSelections.get(unitId);
+ if (!wbSelection) {
+ const workbook = this._instanceSrv.getUnit<Workbook>(unitId);
+ if (!workbook) {
+ throw new Error(`[SheetsSelectionsService]: cannot resolve unit with id "${unitId}"!`);
+ }
+
+ wbSelection = new WorkbookSelections(workbook);
+ this._workbookSelections.set(unitId, wbSelection);
+ }
+
+ return wbSelection;
+ }
+}
+
+/**
+ * This class manages selections in a single workbook.
+ */
+export class WorkbookSelections extends Disposable {
+ private readonly _selectionMoveStart$ = new Subject<Nullable<ISelectionWithStyle[]>>();
+ readonly selectionMoveStart$ = this._selectionMoveStart$.asObservable();
+
+ private readonly _selectionMoving$ = new Subject<Nullable<ISelectionWithStyle[]>>();
+ readonly selectionMoving$ = this._selectionMoving$.asObservable();
+
+ private readonly _selectionMoveEnd$ = new BehaviorSubject<ISelectionWithStyle[]>([]);
+ readonly selectionMoveEnd$ = this._selectionMoveEnd$.asObservable();
+
+ private readonly _beforeSelectionMoveEnd$ = new BehaviorSubject<ISelectionWithStyle[]>([]);
+ readonly beforeSelectionMoveEnd$ = this._beforeSelectionMoveEnd$.asObservable();
+
+ constructor(
+ private readonly _workbook: Workbook
+ ) {
+ super();
+ }
+
+ override dispose(): void {
+ super.dispose();
+
+ this._beforeSelectionMoveEnd$.complete();
+ this._selectionMoveEnd$.complete();
+ this._selectionMoving$.complete();
+ this._selectionMoveStart$.complete();
+ }
+
+ /** Clear all selections in this workbook. */
+ clear(): void {
+ this._worksheetSelections.clear();
+ this._emitOnEnd([]);
+ }
+
+ addSelections(sheetId: string, selectionDatas: ISelectionWithStyle[]) {
+ const selections = this._ensureSheetSelection(sheetId);
+ selections.push(...selectionDatas);
+ this._emitOnEnd(selections);
+ }
+
+ setSelections(sheetId: string, selectionDatas: ISelectionWithStyle[], type: SelectionMoveType = SelectionMoveType.MOVE_END) {
+ const selections = this._ensureSheetSelection(sheetId);
+ selections.length = 0;
+ selections.push(...selectionDatas);
+
+ // WTF: why we would not refresh in add but in replace?
+ if (type === SelectionMoveType.MOVE_START) {
+ this._selectionMoveStart$.next(selectionDatas);
+ } else if (type === SelectionMoveType.MOVING) {
+ this._selectionMoving$.next(selectionDatas);
+ } else {
+ this._emitOnEnd(selectionDatas);
+ }
+ }
+
+ getCurrentSelections(): Readonly<ISelectionWithStyle[]> {
+ return this._getCurrentSelections();
+ }
+
+ getSelectionOfWorksheet(sheetId: string): ISelectionWithStyle[] {
+ if (!this._worksheetSelections.has(sheetId)) {
+ return [];
+ }
+
+ return this._worksheetSelections.get(sheetId)!;
+ }
+
+ private _getCurrentSelections() {
+ return this.getSelectionOfWorksheet(this._workbook.getActiveSheet()!.getSheetId());
+ }
+
+ getCurrentLastSelection(): Readonly<Nullable<ISelectionWithStyle & { primary: ISelectionCell }>> {
+ const selectionData = this._getCurrentSelections();
+ return selectionData[selectionData.length - 1] as Readonly<Nullable<ISelectionWithStyle & { primary: ISelectionCell }>>;
+ }
+
+ private _worksheetSelections = new Map<string, ISelectionWithStyle[]>();
+ private _ensureSheetSelection(sheetId: string): ISelectionWithStyle[] {
+ let worksheetSelection = this._worksheetSelections.get(sheetId);
+ if (!worksheetSelection) {
+ worksheetSelection = [];
+ this._worksheetSelections.set(sheetId, worksheetSelection);
+ }
+
+ return worksheetSelection;
+ }
+
+ private _emitOnEnd(selections: ISelectionWithStyle[]): void {
+ this._beforeSelectionMoveEnd$.next(selections);
+ this._selectionMoveEnd$.next(selections);
+ }
+}
+
+/** An context key to disable normal selections if its value is set to `true`. */
+export const DISABLE_NORMAL_SELECTIONS = 'DISABLE_NORMAL_SELECTIONS';
diff --git a/packages/sheets/src/sheets-plugin.ts b/packages/sheets/src/sheets-plugin.ts
index 6d0fadc19b..de0bc871f2 100644
--- a/packages/sheets/src/sheets-plugin.ts
+++ b/packages/sheets/src/sheets-plugin.ts
@@ -29,7 +29,7 @@ import { INumfmtService } from './services/numfmt/type';
import { WorkbookPermissionService } from './services/permission/workbook-permission/workbook-permission.service';
import { RefRangeService } from './services/ref-range/ref-range.service';
-import { SelectionManagerService } from './services/selection-manager.service';
+import { SheetsSelectionsService } from './services/selections/selection-manager.service';
import { SheetInterceptorService } from './services/sheet-interceptor/sheet-interceptor.service';
import { DefinedNameDataController } from './controllers/defined-name-data.controller';
import { WorksheetPermissionService, WorksheetProtectionPointModel, WorksheetProtectionRuleModel } from './services/permission/worksheet-permission';
@@ -88,7 +88,7 @@ export class UniverSheetsPlugin extends Plugin {
const dependencies: Dependency[] = [
// services
[BorderStyleManagerService],
- [SelectionManagerService],
+ [SheetsSelectionsService],
[RefRangeService],
[WorkbookPermissionService],
[INumfmtService, { useClass: NumfmtService }],
diff --git a/packages/ui/src/services/shortcut/keycode.ts b/packages/ui/src/services/shortcut/keycode.ts
index 5cebfc6248..c1e63b2489 100644
--- a/packages/ui/src/services/shortcut/keycode.ts
+++ b/packages/ui/src/services/shortcut/keycode.ts
@@ -26,6 +26,8 @@ export enum KeyCode {
TAB = 9,
ENTER = 13,
+ SHIFT = 16,
+ CTRL = 17,
ESC = 27,
SPACE = 32,