Build your own AI office with Univer Office SDK. Bring editing, calculation, collaboration, and file processing into your product for people and AI agents. Built on an extensible open-source core.
TypeScript boardcollaborationdocdocxexceloffce365officepdfpptpptxpresentationsdksheetslidesspreadsheetuniverwordwordprocessorworkspacexlsx
refactor(base-sheet): use DI to make arch clear (#29)
Wenzhao Hu42a4ae2b7fea
diff --git a/.circleci/config.yml b/.circleci/config.ymlindex 049e9562c2..839e6960f0 100644--- a/.circleci/config.yml+++ b/.circleci/config.yml@@ -1,47 +1,39 @@-version: 2+version: 2.1defaults: &defaultsdocker:- image: cimg/node:16.20.0-jobs:- prepare:- <<: *defaults+commands:+ prepare: &preparesteps:- checkout-- run:name: Install pnpmcommand: npm install -g pnpm-- # dependencies- # we do not use caches here because monorepos have their own package.json files- # it is fast to install dependencies on CI- run:name: Install dependenciescommand: pnpm install+jobs:lint:<<: *defaultssteps:+ - prepare- run:- name: lint+ name: Lintcommand: pnpm run linttest:<<: *defaultssteps:+ - prepare- run:name: Unit testcommand: pnpm run test-workflow:+workflows:lint_and_build:jobs:- - prepare- - lint:- requires:- - prepare- - test:- requires:- - prepare+ - lint+ - test\ No newline at end of filediff --git a/package.json b/package.jsonindex 914e7eb473..e7a2d17abc 100644--- a/package.json+++ b/package.json@@ -51,6 +51,7 @@"@types/numeral": "^2.0.2","@typescript-eslint/eslint-plugin": "^5.54.0","@typescript-eslint/parser": "^5.54.0",+ "@wendellhu/redi": "^0.6.5","cross-env": "^7.0.3","esbuild": "^0.18.11","esbuild-style-plugin": "^1.6.1",diff --git a/packages/base-sheets/package.json b/packages/base-sheets/package.jsonindex 966a1e24a8..2a357aaa4c 100644--- a/packages/base-sheets/package.json+++ b/packages/base-sheets/package.json@@ -65,6 +65,7 @@},"dependencies": {"@univerjs/base-render": "workspace:^0.0.1",- "@univerjs/core": "workspace:^0.0.1"+ "@univerjs/core": "workspace:^0.0.1",+ "@wendellhu/redi": "^0.6.5"}}diff --git a/packages/base-sheets/src/Basics/Observer.ts b/packages/base-sheets/src/Basics/Observer.tsindex a515952901..8fb467dc84 100644--- a/packages/base-sheets/src/Basics/Observer.ts+++ b/packages/base-sheets/src/Basics/Observer.ts@@ -1,104 +1,104 @@-import { Observable, Plugin } from '@univerjs/core';-import { SelectionControl } from '../Controller/Selection/SelectionController';--interface ISelectionControlFillConfig {- //TODO ...-}--interface ISelectionControlDragAndDropConfig {- //TODO ...-}--export type SheetPluginObserve = {- // onAfterChangeFontFamilyObservable: Observable<string>;- // onAfterChangeFontSizeObservable: Observable<number>;- // onAfterChangeFontWeightObservable: Observable<boolean>;- // onAfterChangeFontItalicObservable: Observable<boolean>;- // onAfterChangeFontStrikethroughObservable: Observable<boolean>;- // onAfterChangeFontUnderlineObservable: Observable<boolean>;- // onAfterChangeFontBackgroundObservable: Observable<string>;- // onAfterChangeFontColorObservable: Observable<string>;-- onDragAndDropStartObserver: Observable<ISelectionControlDragAndDropConfig>;-- onDragAndDroppingObserver: Observable<ISelectionControlDragAndDropConfig>;-- onDragAndDropEndEndObserver: Observable<ISelectionControlDragAndDropConfig>;-- onFillStartObserver: Observable<ISelectionControlFillConfig>;-- onFillingObserver: Observable<ISelectionControlFillConfig>;-- onFillEndObserver: Observable<ISelectionControlFillConfig>;-- onChangeSelectionObserver: Observable<SelectionControl>;-- onChangeCurrentSheetObserver: Observable<string>;-- // onSpreadsheetKeyDownObservable: Observable<IKeyboardEvent>;- // onSpreadsheetKeyUpObservable: Observable<IKeyboardEvent>;- // onSpreadsheetKeyCopyObservable: Observable<IKeyboardEvent>;- // onSpreadsheetKeyPasteObservable: Observable<IKeyboardEvent>;- // onSpreadsheetKeyCutObservable: Observable<IKeyboardEvent>;- // onSpreadsheetKeyCompositionStartObservable: Observable<IKeyboardEvent>;- // onSpreadsheetKeyCompositionUpdateObservable: Observable<IKeyboardEvent>;- // onSpreadsheetKeyCompositionEndObservable: Observable<IKeyboardEvent>;-};--export function uninstall(plugin: Plugin) {- // plugin.deleteObserve('onAfterChangeFontFamilyObservable');- // plugin.deleteObserve('onAfterChangeFontSizeObservable');- // plugin.deleteObserve('onAfterChangeFontWeightObservable');- // plugin.deleteObserve('onAfterChangeFontItalicObservable');- // plugin.deleteObserve('onAfterChangeFontStrikethroughObservable');- // plugin.deleteObserve('onAfterChangeFontUnderlineObservable');- // plugin.deleteObserve('onAfterChangeFontBackgroundObservable');- // plugin.deleteObserve('onAfterChangeFontColorObservable');-- plugin.deleteObserve('onDragAndDropStartObserver');- plugin.deleteObserve('onDragAndDroppingObserver');- plugin.deleteObserve('onDragAndDropEndEndObserver');- plugin.deleteObserve('onFillStartObserver');- plugin.deleteObserve('onFillingObserver');- plugin.deleteObserve('onFillEndObserver');- plugin.deleteObserve('onChangeSelectionObserver');- plugin.deleteObserve('onChangeCurrentSheetObserver');- // plugin.deleteObserve('onSpreadsheetKeyDownObservable');- // plugin.deleteObserve('onSpreadsheetKeyUpObservable');- // plugin.deleteObserve('onSpreadsheetKeyCopyObservable');- // plugin.deleteObserve('onSpreadsheetKeyPasteObservable');- // plugin.deleteObserve('onSpreadsheetKeyCutObservable');- // plugin.deleteObserve('onSpreadsheetKeyCompositionStartObservable');- // plugin.deleteObserve('onSpreadsheetKeyCompositionUpdateObservable');- // plugin.deleteObserve('onSpreadsheetKeyCompositionEndObservable');-}--export function install(plugin: Plugin) {- // plugin.pushToObserve('onAfterChangeFontFamilyObservable');- // plugin.pushToObserve('onAfterChangeFontSizeObservable');- // plugin.pushToObserve('onAfterChangeFontWeightObservable');- // plugin.pushToObserve('onAfterChangeFontItalicObservable');- // plugin.pushToObserve('onAfterChangeFontStrikethroughObservable');- // plugin.pushToObserve('onAfterChangeFontUnderlineObservable');- // plugin.pushToObserve('onAfterChangeFontBackgroundObservable');- // plugin.pushToObserve('onAfterChangeFontColorObservable');-- plugin.pushToObserve('onDragAndDropStartObserver');- plugin.pushToObserve('onDragAndDroppingObserver');- plugin.pushToObserve('onDragAndDropEndEndObserver');- plugin.pushToObserve('onFillStartObserver');- plugin.pushToObserve('onFillingObserver');- plugin.pushToObserve('onFillEndObserver');- plugin.pushToObserve('onChangeSelectionObserver');-- plugin.pushToObserve('onChangeCurrentSheetObserver');-- // plugin.pushToObserve('onSpreadsheetKeyDownObservable');- // plugin.pushToObserve('onSpreadsheetKeyUpObservable');- // plugin.pushToObserve('onSpreadsheetKeyCopyObservable');- // plugin.pushToObserve('onSpreadsheetKeyPasteObservable');- // plugin.pushToObserve('onSpreadsheetKeyCutObservable');- // plugin.pushToObserve('onSpreadsheetKeyCompositionStartObservable');- // plugin.pushToObserve('onSpreadsheetKeyCompositionUpdateObservable');- // plugin.pushToObserve('onSpreadsheetKeyCompositionEndObservable');-}+import { Observable, Plugin } from '@univerjs/core';+import { SelectionController } from '../Controller/Selection/SelectionController';++interface ISelectionControlFillConfig {+ //TODO ...+}++interface ISelectionControlDragAndDropConfig {+ //TODO ...+}++export type SheetPluginObserve = {+ // onAfterChangeFontFamilyObservable: Observable<string>;+ // onAfterChangeFontSizeObservable: Observable<number>;+ // onAfterChangeFontWeightObservable: Observable<boolean>;+ // onAfterChangeFontItalicObservable: Observable<boolean>;+ // onAfterChangeFontStrikethroughObservable: Observable<boolean>;+ // onAfterChangeFontUnderlineObservable: Observable<boolean>;+ // onAfterChangeFontBackgroundObservable: Observable<string>;+ // onAfterChangeFontColorObservable: Observable<string>;++ onDragAndDropStartObserver: Observable<ISelectionControlDragAndDropConfig>;++ onDragAndDroppingObserver: Observable<ISelectionControlDragAndDropConfig>;++ onDragAndDropEndEndObserver: Observable<ISelectionControlDragAndDropConfig>;++ onFillStartObserver: Observable<ISelectionControlFillConfig>;++ onFillingObserver: Observable<ISelectionControlFillConfig>;++ onFillEndObserver: Observable<ISelectionControlFillConfig>;++ onChangeSelectionObserver: Observable<SelectionController>;++ onChangeCurrentSheetObserver: Observable<string>;++ // onSpreadsheetKeyDownObservable: Observable<IKeyboardEvent>;+ // onSpreadsheetKeyUpObservable: Observable<IKeyboardEvent>;+ // onSpreadsheetKeyCopyObservable: Observable<IKeyboardEvent>;+ // onSpreadsheetKeyPasteObservable: Observable<IKeyboardEvent>;+ // onSpreadsheetKeyCutObservable: Observable<IKeyboardEvent>;+ // onSpreadsheetKeyCompositionStartObservable: Observable<IKeyboardEvent>;+ // onSpreadsheetKeyCompositionUpdateObservable: Observable<IKeyboardEvent>;+ // onSpreadsheetKeyCompositionEndObservable: Observable<IKeyboardEvent>;+};++export function uninstall(plugin: Plugin) {+ // plugin.deleteObserve('onAfterChangeFontFamilyObservable');+ // plugin.deleteObserve('onAfterChangeFontSizeObservable');+ // plugin.deleteObserve('onAfterChangeFontWeightObservable');+ // plugin.deleteObserve('onAfterChangeFontItalicObservable');+ // plugin.deleteObserve('onAfterChangeFontStrikethroughObservable');+ // plugin.deleteObserve('onAfterChangeFontUnderlineObservable');+ // plugin.deleteObserve('onAfterChangeFontBackgroundObservable');+ // plugin.deleteObserve('onAfterChangeFontColorObservable');++ plugin.deleteObserve('onDragAndDropStartObserver');+ plugin.deleteObserve('onDragAndDroppingObserver');+ plugin.deleteObserve('onDragAndDropEndEndObserver');+ plugin.deleteObserve('onFillStartObserver');+ plugin.deleteObserve('onFillingObserver');+ plugin.deleteObserve('onFillEndObserver');+ plugin.deleteObserve('onChangeSelectionObserver');+ plugin.deleteObserve('onChangeCurrentSheetObserver');+ // plugin.deleteObserve('onSpreadsheetKeyDownObservable');+ // plugin.deleteObserve('onSpreadsheetKeyUpObservable');+ // plugin.deleteObserve('onSpreadsheetKeyCopyObservable');+ // plugin.deleteObserve('onSpreadsheetKeyPasteObservable');+ // plugin.deleteObserve('onSpreadsheetKeyCutObservable');+ // plugin.deleteObserve('onSpreadsheetKeyCompositionStartObservable');+ // plugin.deleteObserve('onSpreadsheetKeyCompositionUpdateObservable');+ // plugin.deleteObserve('onSpreadsheetKeyCompositionEndObservable');+}++export function install(plugin: Plugin) {+ // plugin.pushToObserve('onAfterChangeFontFamilyObservable');+ // plugin.pushToObserve('onAfterChangeFontSizeObservable');+ // plugin.pushToObserve('onAfterChangeFontWeightObservable');+ // plugin.pushToObserve('onAfterChangeFontItalicObservable');+ // plugin.pushToObserve('onAfterChangeFontStrikethroughObservable');+ // plugin.pushToObserve('onAfterChangeFontUnderlineObservable');+ // plugin.pushToObserve('onAfterChangeFontBackgroundObservable');+ // plugin.pushToObserve('onAfterChangeFontColorObservable');++ plugin.pushToObserve('onDragAndDropStartObserver');+ plugin.pushToObserve('onDragAndDroppingObserver');+ plugin.pushToObserve('onDragAndDropEndEndObserver');+ plugin.pushToObserve('onFillStartObserver');+ plugin.pushToObserve('onFillingObserver');+ plugin.pushToObserve('onFillEndObserver');+ plugin.pushToObserve('onChangeSelectionObserver');++ plugin.pushToObserve('onChangeCurrentSheetObserver');++ // plugin.pushToObserve('onSpreadsheetKeyDownObservable');+ // plugin.pushToObserve('onSpreadsheetKeyUpObservable');+ // plugin.pushToObserve('onSpreadsheetKeyCopyObservable');+ // plugin.pushToObserve('onSpreadsheetKeyPasteObservable');+ // plugin.pushToObserve('onSpreadsheetKeyCutObservable');+ // plugin.pushToObserve('onSpreadsheetKeyCompositionStartObservable');+ // plugin.pushToObserve('onSpreadsheetKeyCompositionUpdateObservable');+ // plugin.pushToObserve('onSpreadsheetKeyCompositionEndObservable');+}diff --git a/packages/base-sheets/src/Basics/Register/NamedRangeActionExtension.ts b/packages/base-sheets/src/Basics/Register/NamedRangeActionExtension.tsindex 92b1fe992b..559b821775 100644--- a/packages/base-sheets/src/Basics/Register/NamedRangeActionExtension.ts+++ b/packages/base-sheets/src/Basics/Register/NamedRangeActionExtension.ts@@ -1,60 +1,60 @@-import {- ActionOperation,- ACTION_NAMES,- BaseActionExtension,- BaseActionExtensionFactory,- ISetNamedRangeActionData,- ISheetActionData,- Tools,- IInsertRowActionData,-} from '@univerjs/core';-import { SheetPlugin } from '../../SheetPlugin';--/**- * TODO insertColumn/insertRange/insertRange/deleteRange- */-export class NamedRangeActionExtension extends BaseActionExtension<SheetPlugin> {- execute() {- const actionDataList = this.actionDataList;-- actionDataList.forEach((actionData) => {- if (actionData.operation != null && !ActionOperation.hasExtension(actionData)) {- return false;- }-- if (actionData.actionName === ACTION_NAMES.INSERT_ROW_ACTION) {- const { sheetId, rowCount, rowIndex } = actionData as IInsertRowActionData;- const namedRanges = Tools.deepClone(this._plugin.getWorkbook().getConfig().namedRanges);-- for (let i = 0; i < namedRanges.length; i++) {- const namedRangeData = namedRanges[i].range.rangeData;- if (rowIndex > namedRangeData.endRow) {- continue;- } else if (rowIndex >= namedRangeData.startRow && rowIndex <= namedRangeData.endRow) {- namedRangeData.endRow += rowCount;- } else {- namedRangeData.startRow += rowCount;- namedRangeData.endRow += rowCount;- }-- const actionData: ISetNamedRangeActionData = {- actionName: ACTION_NAMES.SET_NAMED_RANGE_ACTION,- namedRange: namedRanges[i],- sheetId,- };- this.push(actionData);- }- }- });- }-}--export class NamedRangeActionExtensionFactory extends BaseActionExtensionFactory<SheetPlugin> {- get zIndex(): number {- return 3;- }-- create(actionDataList: ISheetActionData[]): BaseActionExtension<SheetPlugin> {- return new NamedRangeActionExtension(actionDataList, this._plugin);- }-}+import {+ ActionOperation,+ ACTION_NAMES,+ BaseActionExtension,+ BaseActionExtensionFactory,+ ISetNamedRangeActionData,+ ISheetActionData,+ Tools,+ IInsertRowActionData,+} from '@univerjs/core';+import { SheetPlugin } from '../../SheetPlugin';++/**+ * TODO insertColumn/insertRange/insertRange/deleteRange+ */+export class NamedRangeActionExtension extends BaseActionExtension<SheetPlugin> {+ override execute() {+ const actionDataList = this.actionDataList;++ actionDataList.forEach((actionData) => {+ if (actionData.operation != null && !ActionOperation.hasExtension(actionData)) {+ return false;+ }++ if (actionData.actionName === ACTION_NAMES.INSERT_ROW_ACTION) {+ const { sheetId, rowCount, rowIndex } = actionData as IInsertRowActionData;+ const namedRanges = Tools.deepClone(this._plugin.getWorkbook().getConfig().namedRanges);++ for (let i = 0; i < namedRanges.length; i++) {+ const namedRangeData = namedRanges[i].range.rangeData;+ if (rowIndex > namedRangeData.endRow) {+ continue;+ } else if (rowIndex >= namedRangeData.startRow && rowIndex <= namedRangeData.endRow) {+ namedRangeData.endRow += rowCount;+ } else {+ namedRangeData.startRow += rowCount;+ namedRangeData.endRow += rowCount;+ }++ const actionData: ISetNamedRangeActionData = {+ actionName: ACTION_NAMES.SET_NAMED_RANGE_ACTION,+ namedRange: namedRanges[i],+ sheetId,+ };+ this.push(actionData);+ }+ }+ });+ }+}++export class NamedRangeActionExtensionFactory extends BaseActionExtensionFactory<SheetPlugin> {+ override get zIndex(): number {+ return 3;+ }++ override create(actionDataList: ISheetActionData[]): BaseActionExtension<SheetPlugin> {+ return new NamedRangeActionExtension(actionDataList, this._plugin);+ }+}diff --git a/packages/base-sheets/src/Controller/AntLineController.ts b/packages/base-sheets/src/Controller/AntLineController.tsindex 4ac675f440..87f91669a0 100644--- a/packages/base-sheets/src/Controller/AntLineController.ts+++ b/packages/base-sheets/src/Controller/AntLineController.ts@@ -1,8 +1,10 @@-import { Workbook } from '@univerjs/core';+import { Inject } from '@wendellhu/redi';++import { SheetContext, Workbook } from '@univerjs/core';import { Rect, Scene } from '@univerjs/base-render';-import { SheetView } from '../View/Views';import { AntLine, AntLineModel, IAntLineRange } from '../Model/AntLineModel';-import { SheetPlugin } from '../SheetPlugin';+import { ISheetContext } from '../Services/tokens';+import { CanvasView } from '../View';enum ANT_LINE_MANAGER_KEY {AntLine = '__AntLineShape__',@@ -14,31 +16,22 @@ enum ANT_LINE_MANAGER_KEY {export class AntLineControl {private _antLineModelList: AntLineModel[];- private _plugin: SheetPlugin;-private _activeSheetId: string;/*** Create AntLineController- * @param plugin*/- constructor(plugin: SheetPlugin) {- this._plugin = plugin;+ constructor(@ISheetContext private readonly _sheetContext: SheetContext, @Inject(CanvasView) private readonly _canvasView: CanvasView) {this._antLineModelList = [];- plugin- .getContext()- .getContextObserver('onAfterChangeActiveSheetObservable')- .add(() => {- this._activeSheetId = plugin.getWorkbook().getActiveSheet().getSheetId();- this._makeUpdateSceneAntLineRect();- });- plugin- .getContext()- .getContextObserver('onSheetRenderDidMountObservable')- .add(() => {- this._activeSheetId = plugin.getWorkbook().getActiveSheet().getSheetId();- this._makeUpdateSceneAntLineRect();- });++ this._sheetContext.getContextObserver('onAfterChangeActiveSheetObservable').add(() => {+ this._activeSheetId = this._sheetContext.getWorkBook().getActiveSheet().getSheetId();+ this._makeUpdateSceneAntLineRect();+ });+ this._sheetContext.getContextObserver('onSheetRenderDidMountObservable').add(() => {+ this._activeSheetId = this._sheetContext.getWorkBook().getActiveSheet().getSheetId();+ this._makeUpdateSceneAntLineRect();+ });}/**@@ -62,28 +55,20 @@ export class AntLineControl {this._makeUpdateSceneAntLineRect();}- /**- * Return SheetView- * @returns- */- getSheetView(): SheetView {- return this._plugin.getCanvasView().getSheetView();- }-/*** Return WorkBook* @returns Workbook*/- getWorkBook(): Workbook {- return this._plugin.getWorkbook();+ private getWorkBook(): Workbook {+ return this._sheetContext.getWorkBook();}/*** Return SheetView Scene* @returns*/- getSheetViewScene(): Scene {- return this._plugin.getCanvasView().getSheetView().getScene();+ private getSheetViewScene(): Scene {+ return this._canvasView.getSheetView().getScene();}/**diff --git a/packages/base-sheets/src/Controller/CellEditorController.ts b/packages/base-sheets/src/Controller/CellEditorController.tsindex a1703c1d20..2430174325 100644--- a/packages/base-sheets/src/Controller/CellEditorController.ts+++ b/packages/base-sheets/src/Controller/CellEditorController.ts@@ -1,102 +1,95 @@-import { Direction, IDocumentData, IRangeData, IStyleData, Nullable, ICellData, handleJsonToDom } from '@univerjs/core';-import { SheetPlugin } from '../SheetPlugin';--/**- * Cell Editor- */-export class CellEditorController {- isEditMode: boolean;-- // current edit cell- currentEditRangeData: IRangeData;-- private _plugin: SheetPlugin;-- constructor(plugin: SheetPlugin) {- this._plugin = plugin;- }-- setEditMode(value: boolean) {- this.isEditMode = value;- }-- getEditMode() {- return this.isEditMode;- }-- setCurrentEditRangeData() {- const currentCell = this._plugin.getSelectionManager().getCurrentCellModel();- if (!currentCell) return;-- let row;- let column;-- if (currentCell.isMerged) {- const mergeInfo = currentCell.mergeInfo;- row = mergeInfo.startRow;- column = mergeInfo.startColumn;- } else {- row = currentCell.row;- column = currentCell.column;- }-- this.currentEditRangeData = {- startRow: row,- startColumn: column,- endRow: row,- endColumn: column,- };- }-- getCurrentEditRangeData() {- return this.currentEditRangeData;- }-- setCurrentEditRangeValue(cell: ICellData) {- // only one selection- const { startRow, startColumn, endRow, endColumn } = this.currentEditRangeData;- const range = this._plugin.getContext().getWorkBook().getActiveSheet().getRange(startRow, startColumn, endRow, endColumn);-- range.setRangeData(cell);-- // this._plugin.getMainComponent().makeDirty(true);- }-- getSelectionValue(): string {- const range = this._plugin.getSelectionManager().getActiveRange();- if (!range) return '';-- const value = range && range.getDisplayValue();- if (typeof value === 'string') {- return value;- }- if (typeof value === 'object' && value !== null) {- return handleJsonToDom(value);- }- return '';- }-- getSelectionStyle(): Nullable<IStyleData> {- return this._plugin.getSelectionManager().getActiveRange()?.getTextStyle();- }-- setSelectionValue(value: IDocumentData | string) {- const range = this._plugin.getSelectionManager().getActiveRange();- if (!range) return;-- if (typeof value === 'string') {- range.setValue(value);- }- if (typeof value === 'object') {- range.setRangeData({ p: value });- }-- // this._plugin.getMainComponent().makeDirty(true);- }-- handleBackSpace() {}-- handleDirection(direction: Direction) {- // todo- }-}+import { Direction, IDocumentData, IRangeData, IStyleData, Nullable, ICellData, handleJsonToDom, SheetContext } from '@univerjs/core';+import { ISelectionManager, ISheetContext } from '../Services/tokens';+import { SelectionManager } from './Selection';++/**+ * Cell Editor+ */+export class CellEditorController {+ isEditMode: boolean;++ // current edit cell+ currentEditRangeData: IRangeData;++ constructor(@ISelectionManager private readonly _selectionManager: SelectionManager, @ISheetContext private readonly _sheetContext: SheetContext) {}++ setEditMode(value: boolean) {+ this.isEditMode = value;+ }++ getEditMode() {+ return this.isEditMode;+ }++ setCurrentEditRangeData() {+ const currentCell = this._selectionManager.getCurrentCellModel();+ if (!currentCell) return;++ let row;+ let column;++ if (currentCell.isMerged) {+ const mergeInfo = currentCell.mergeInfo;+ row = mergeInfo.startRow;+ column = mergeInfo.startColumn;+ } else {+ row = currentCell.row;+ column = currentCell.column;+ }++ this.currentEditRangeData = {+ startRow: row,+ startColumn: column,+ endRow: row,+ endColumn: column,+ };+ }++ getCurrentEditRangeData() {+ return this.currentEditRangeData;+ }++ setCurrentEditRangeValue(cell: ICellData) {+ // only one selection+ const { startRow, startColumn, endRow, endColumn } = this.currentEditRangeData;+ const range = this._sheetContext.getWorkBook().getActiveSheet().getRange(startRow, startColumn, endRow, endColumn);++ range.setRangeData(cell);+ }++ getSelectionValue(): string {+ const range = this._selectionManager.getActiveRange();+ if (!range) return '';++ const value = range && range.getDisplayValue();+ if (typeof value === 'string') {+ return value;+ }+ if (typeof value === 'object' && value !== null) {+ return handleJsonToDom(value);+ }+ return '';+ }++ getSelectionStyle(): Nullable<IStyleData> {+ return this._selectionManager.getActiveRange()?.getTextStyle();+ }++ setSelectionValue(value: IDocumentData | string) {+ const range = this._selectionManager.getActiveRange();+ if (!range) return;++ if (typeof value === 'string') {+ range.setValue(value);+ }+ if (typeof value === 'object') {+ range.setRangeData({ p: value });+ }+ }++ handleBackSpace() {}++ handleDirection(direction: Direction) {+ // todo+ }+}diff --git a/packages/base-sheets/src/Controller/CountBarController.ts b/packages/base-sheets/src/Controller/CountBarController.tsindex 2e95f3c2f9..fa74af4a40 100644--- a/packages/base-sheets/src/Controller/CountBarController.ts+++ b/packages/base-sheets/src/Controller/CountBarController.ts@@ -1,22 +1,14 @@-import { UIObserver } from '@univerjs/core';-import { SheetPlugin } from '../SheetPlugin';+import { Context, SheetContext, UIObserver } from '@univerjs/core';+import { IGlobalContext, ISheetContext } from '../Services/tokens';export class CountBarController {- private _plugin: SheetPlugin;-- constructor(plugin: SheetPlugin) {- this._plugin = plugin;- }-- getPlugin(): SheetPlugin {- return this._plugin;- }+ constructor(@ISheetContext private readonly _sheetContext: SheetContext, @IGlobalContext private readonly _globalContext: Context) {}listenEventManager(): void {this._getCoreObserver<number>('onUIChangeObservable').add(({ name, value }) => {switch (name) {case 'changeZoom': {- const workbook = this._plugin.getContext().getWorkBook();+ const workbook = this._sheetContext.getWorkBook();if (workbook) {workbook.getActiveSheet().setZoomRatio(value!);}@@ -27,6 +19,6 @@ export class CountBarController {}protected _getCoreObserver<T>(type: string) {- return this._plugin.getGlobalContext().getObserverManager().requiredObserver<UIObserver<T>>(type, 'core');+ return this._globalContext.getObserverManager().requiredObserver<UIObserver<T>>(type, 'core');}}diff --git a/packages/base-sheets/src/Controller/EditTooltipsController.ts b/packages/base-sheets/src/Controller/EditTooltipsController.tsindex 75dd85cf8c..5fcda13f3d 100644--- a/packages/base-sheets/src/Controller/EditTooltipsController.ts+++ b/packages/base-sheets/src/Controller/EditTooltipsController.ts@@ -1,17 +1,16 @@-import { CommandManager, SetWorkSheetActivateAction } from '@univerjs/core';-import { Layer } from '@univerjs/base-render';+import { CommandManager, SetWorkSheetActivateAction, SheetContext } from '@univerjs/core';+import { Engine, Layer } from '@univerjs/base-render';+import { EditTooltips, EditTooltipsProps } from '../View/Views';-import { SheetPlugin } from '../SheetPlugin';+import { IRenderingEngine, ISheetContext } from '../Services/tokens';+import { CANVAS_VIEW_KEY } from '../View';export class EditTooltipsController {_editTooltipsPage: Map<string, Map<string, EditTooltips>>;- _plugin: SheetPlugin;-_layer: Layer;- constructor(plugin: SheetPlugin) {- this._plugin = plugin;+ constructor(@IRenderingEngine private readonly _engine: Engine, @ISheetContext private readonly _sheetContext: SheetContext) {this._editTooltipsPage = new Map();CommandManager.getActionObservers().add((event) => {const data = event.data;@@ -62,7 +61,7 @@ export class EditTooltipsController {}setRowColumn(key: string, sheetId: string, row: number, column: number): void {- const sheet = this._plugin.getContext().getUniver().getCurrentUniverSheetInstance().getWorkBook().getSheetBySheetId(sheetId);+ const sheet = this._sheetContext.getUniver().getCurrentUniverSheetInstance().getWorkBook().getSheetBySheetId(sheetId);const editTooltips = this.createIfEditTooltips(key, sheetId);if (sheet) {let merges = sheet.getMerges().getByRowColumn(row, column);@@ -108,9 +107,9 @@ export class EditTooltipsController {}refreshEditTooltips(): void {- const sheet = this._plugin.getContext().getUniver().getCurrentUniverSheetInstance().getWorkBook().getActiveSheet();+ const sheet = this._sheetContext.getUniver().getCurrentUniverSheetInstance().getWorkBook().getActiveSheet();const sheetPage = this._editTooltipsPage.get(sheet.getSheetId());- const scene = this._plugin.getMainScene();+ const scene = this._engine.getScene(CANVAS_VIEW_KEY.MAIN_SCENE);if (scene) {if (this._layer == null) {this._layer = new Layer(scene, [], 3);diff --git a/packages/base-sheets/src/Controller/FormulaBarController.ts b/packages/base-sheets/src/Controller/FormulaBarController.tsindex 827d22dfc9..7c87cfb7cd 100644--- a/packages/base-sheets/src/Controller/FormulaBarController.ts+++ b/packages/base-sheets/src/Controller/FormulaBarController.ts@@ -1,25 +1,11 @@-import { SheetPlugin } from '../SheetPlugin';-export class FormulaBarController {- private _plugin: SheetPlugin;-- constructor(plugin: SheetPlugin) {- this._plugin = plugin;-- // this._initialize();- }-// private _initialize() {-// this._plugin.getObserver('onChangeSelectionObserver')?.add((selectionControl: SelectionControl) => {// const currentCell = selectionControl.model.currentCell;-// if (currentCell) {// let currentRangeData;-// if (currentCell.isMerged) {// const mergeInfo = currentCell.mergeInfo;-// currentRangeData = {// startRow: mergeInfo.startRow,// endRow: mergeInfo.endRow,@@ -35,19 +21,15 @@ export class FormulaBarController {// endColumn: column,// };// }-// const cellData = this._plugin.getWorkbook().getActiveSheet().getRange(currentRangeData).getObjectValue({ isIncludeStyle: true });-// if (cellData) {// let cellValue = String(cellData.m || cellData.v || '');-// // If the cell has a formula, it needs to be intercepted// const cell = this._cellInputExtensionManager.handle({// row: currentRangeData.startRow,// column: currentRangeData.startColumn,// value: cellValue,// });-// if (cell) {// cellValue = cell.value;// }@@ -59,6 +41,5 @@ export class FormulaBarController {// }// }// });-// }}diff --git a/packages/base-sheets/src/Controller/RightMenuController.ts b/packages/base-sheets/src/Controller/RightMenuController.tsindex 57b83e2f8a..723d70ce76 100644--- a/packages/base-sheets/src/Controller/RightMenuController.ts+++ b/packages/base-sheets/src/Controller/RightMenuController.ts@@ -1,20 +1,18 @@-import { UIObserver } from '@univerjs/core';-import { SheetPlugin } from '../SheetPlugin';-import { SelectionControl } from './Selection/SelectionController';+import { Context, SheetContext, UIObserver } from '@univerjs/core';+import { SelectionController } from './Selection/SelectionController';import { SelectionModel } from '../Model/SelectionModel';+import { IGlobalContext, ISelectionManager, ISheetContext } from '../Services/tokens';+import { SelectionManager } from './Selection';export class RightMenuController {- private _plugin: SheetPlugin;-- constructor(plugin: SheetPlugin) {- this._plugin = plugin;- }+ constructor(+ @ISelectionManager private readonly _selectionManager: SelectionManager,+ @ISheetContext private readonly _sheetContext: SheetContext,+ @IGlobalContext private readonly _globalContext: Context+ ) {}listenEventManager() {- this._plugin- .getContext()- .getUniver()- .getGlobalContext()+ this._globalContext.getObserverManager().requiredObserver<UIObserver<string>>('onUIChangeObservable', 'core').add((msg) => {@@ -53,7 +51,7 @@ export class RightMenuController {insertRow = () => {const selections = this._getSelections();if (selections?.length === 1) {- const sheet = this._plugin.getContext().getWorkBook().getActiveSheet();+ const sheet = this._sheetContext.getWorkBook().getActiveSheet();sheet?.insertRowBefore(selections[0].startRow, selections[0].endRow - selections[0].startRow + 1);}};@@ -61,7 +59,7 @@ export class RightMenuController {deleteRow = () => {const selections = this._getSelections();if (selections?.length === 1) {- const sheet = this._plugin.getContext().getWorkBook().getActiveSheet();+ const sheet = this._sheetContext.getWorkBook().getActiveSheet();sheet?.deleteRows(selections[0].startRow, selections[0].endRow - selections[0].startRow + 1);}};@@ -69,7 +67,7 @@ export class RightMenuController {insertColumn = () => {const selections = this._getSelections();if (selections?.length === 1) {- const sheet = this._plugin.getContext().getWorkBook().getActiveSheet();+ const sheet = this._sheetContext.getWorkBook().getActiveSheet();sheet.insertColumnBefore(selections[0].startColumn, selections[0].endColumn - selections[0].startColumn + 1);}};@@ -77,7 +75,7 @@ export class RightMenuController {deleteColumn = () => {const selections = this._getSelections();if (selections?.length === 1) {- const sheet = this._plugin.getContext().getWorkBook().getActiveSheet();+ const sheet = this._sheetContext.getWorkBook().getActiveSheet();sheet.deleteColumns(selections[0].startColumn, selections[0].endColumn - selections[0].startColumn + 1);}};@@ -85,7 +83,7 @@ export class RightMenuController {clearContent = () => {const selections = this._getSelections();if (selections?.length === 1) {- const sheet = this._plugin.getContext().getWorkBook().getActiveSheet();+ const sheet = this._sheetContext.getWorkBook().getActiveSheet();sheet.getRange(selections[0]).clear();}};@@ -93,7 +91,7 @@ export class RightMenuController {deleteCellLeft = () => {const selections = this._getSelections();if (selections?.length === 1) {- const sheet = this._plugin.getContext().getWorkBook().getActiveSheet();+ const sheet = this._sheetContext.getWorkBook().getActiveSheet();sheet.getRange(selections[0]).deleteCells(0);}};@@ -101,7 +99,7 @@ export class RightMenuController {deleteCellTop = () => {const selections = this._getSelections();if (selections?.length === 1) {- const sheet = this._plugin.getContext().getWorkBook().getActiveSheet();+ const sheet = this._sheetContext.getWorkBook().getActiveSheet();sheet.getRange(selections[0]).deleteCells(1);}};@@ -109,7 +107,7 @@ export class RightMenuController {setColumnWidth(width: string) {const selections = this._getSelections();if (selections?.length === 1) {- const sheet = this._plugin.getContext().getWorkBook().getActiveSheet();+ const sheet = this._sheetContext.getWorkBook().getActiveSheet();sheet.setColumnWidth(selections[0].startColumn, selections[0].endColumn - selections[0].startColumn + 1, Number(width));}}@@ -117,14 +115,14 @@ export class RightMenuController {setRowHeight(height: string) {const selections = this._getSelections();if (selections?.length === 1) {- const sheet = this._plugin.getContext().getWorkBook().getActiveSheet();+ const sheet = this._sheetContext.getWorkBook().getActiveSheet();sheet.setRowHeights(selections[0].startRow, selections[0].endRow - selections[0].startRow + 1, Number(height));}}private _getSelections() {- const controls = this._plugin?.getSelectionManager().getCurrentControls();- const selections = controls?.map((control: SelectionControl) => {+ const controls = this._selectionManager.getCurrentControls();+ const selections = controls?.map((control: SelectionController) => {const model: SelectionModel = control.model;return {startRow: model.startRow,diff --git a/packages/base-sheets/src/Controller/Selection/ColumnTitleController.ts b/packages/base-sheets/src/Controller/Selection/ColumnTitleController.tsindex 82243a3249..da423f5420 100644--- a/packages/base-sheets/src/Controller/Selection/ColumnTitleController.ts+++ b/packages/base-sheets/src/Controller/Selection/ColumnTitleController.ts@@ -1,11 +1,12 @@+import { Inject } from '@wendellhu/redi';import { CURSOR_TYPE, Group, IMouseEvent, IPointerEvent, Rect } from '@univerjs/base-render';-import { Nullable } from '@univerjs/core';-import { DragLineDirection } from './DragLineController';-import { SelectionManager } from './SelectionManager';+import { Nullable, SheetContext } from '@univerjs/core';+import { DragLineController, DragLineDirection } from './DragLineController';+import { CanvasView } from '../../View';+import { ISheetContext } from '../../Services/tokens';+import { IColumnTitleControllerHandlers } from './Shared';export class ColumnTitleController {- private _manager: SelectionManager;-private _leftTopWidth: number;private _startOffsetX: number = 0;@@ -22,26 +23,32 @@ export class ColumnTitleController {private _Item: Rect;- constructor(manager: SelectionManager) {- this._manager = manager;- this._leftTopWidth = this._manager.getSheetView().getSpreadsheetLeftTopPlaceholder().getState().width;+ private handlers: IColumnTitleControllerHandlers | null = null;++ constructor(+ @Inject(CanvasView) private readonly _canvasView: CanvasView,+ @Inject(DragLineController) private readonly _dragLineController: DragLineController,+ @ISheetContext private readonly _sheetContext: SheetContext+ ) {+ const sheetView = this._canvasView.getSheetView();+ this._leftTopWidth = sheetView.getSpreadsheetLeftTopPlaceholder().getState().width;// 创建高亮itemthis._content = new Rect('HighLightContent', {width: 0,- height: this._manager.getSheetView().getSpreadsheetSkeleton().columnTitleHeight,+ height: sheetView.getSpreadsheetSkeleton().columnTitleHeight,left: 0,fill: 'rgb(220,220,220,0.5)',});this._Item = new Rect('HighLightItem', {width: 5,- height: this._manager.getSheetView().getSpreadsheetSkeleton().columnTitleHeight,+ height: sheetView.getSpreadsheetSkeleton().columnTitleHeight,left: 0,fill: 'rgb(220,220,220,0.5)',});this._highlightItem = new Group('HighLightColumnTitle', this._content, this._Item);this._highlightItem.hide();- const scene = this._manager.getScene();+ const scene = sheetView.getScene();scene.addObject(this._highlightItem, 3);@@ -49,7 +56,7 @@ export class ColumnTitleController {}pointerDown(e: IPointerEvent | IMouseEvent) {- const main = this._manager.getMainComponent();+ const main = this._canvasView.getSheetView().getSpreadsheet();const { offsetX: evtOffsetX, offsetY: evtOffsetY } = e;this._startOffsetX = evtOffsetX;this._startOffsetY = evtOffsetY;@@ -77,7 +84,7 @@ export class ColumnTitleController {const end = columnWidthAccumulation[this._index] + this._leftTopWidth;const start = (this._index ? columnWidthAccumulation[this._index - 1] : 0) + this._leftTopWidth;- this._manager.getDragLineControl().create({+ this._dragLineController.create({direction: DragLineDirection.VERTICAL,end,start,@@ -86,15 +93,14 @@ export class ColumnTitleController {this.highlightColumnTitle(e);},});- this._manager.getDragLineControl().dragDown(e);+ this._dragLineController.dragDown(e);}// 高亮当前列this.highlightColumn();}setColumnWidth(width: Nullable<number>) {- const plugin = this._manager.getPlugin();- const sheet = plugin.getContext().getWorkBook().getActiveSheet();+ const sheet = this._sheetContext.getWorkBook().getActiveSheet();if (width === null) {sheet.setColumnWidth(this._index, 1, 5);} else {@@ -103,10 +109,14 @@ export class ColumnTitleController {this.highlightColumn();}+ setHandlers(handlers: IColumnTitleControllerHandlers): void {+ this.handlers = handlers;+ }+highlightColumn() {- this._manager.clearSelectionControls();- const sheet = this._manager.getPlugin().getWorkbook().getActiveSheet();- this._manager.addControlToCurrentByRangeData(+ this.handlers?.clearSelectionControls();+ const sheet = this._sheetContext.getWorkBook().getActiveSheet();+ this.handlers?.addControlToCurrentByRangeData({startRow: 0,startColumn: this._index,@@ -121,7 +131,7 @@ export class ColumnTitleController {}highlightColumnTitle(e: IPointerEvent | IMouseEvent) {- const main = this._manager.getMainComponent();+ const main = this._canvasView.getSheetView().getSpreadsheet();const { offsetX: evtOffsetX, offsetY: evtOffsetY } = e;this._startOffsetX = evtOffsetX;this._startOffsetY = evtOffsetY;diff --git a/packages/base-sheets/src/Controller/Selection/DragLineController.ts b/packages/base-sheets/src/Controller/Selection/DragLineController.tsindex 58ded14a91..b93b896d46 100644--- a/packages/base-sheets/src/Controller/Selection/DragLineController.ts+++ b/packages/base-sheets/src/Controller/Selection/DragLineController.ts@@ -1,6 +1,7 @@import { CURSOR_TYPE, Group, IMouseEvent, IPointerEvent, Rect } from '@univerjs/base-render';import { Nullable, Observer } from '@univerjs/core';-import { SelectionManager } from './SelectionManager';+import { Inject } from '@wendellhu/redi';+import { CanvasView } from '../../View';enum DRAG_LINE_KEY {lineMain = '__SpreadsheetDragLineMain__',@@ -39,8 +40,6 @@ export class DragLineController {private _dragLine: Group;- private _manager: SelectionManager;-private _moveObserver: Nullable<Observer<IPointerEvent | IMouseEvent>>;private _upObserver: Nullable<Observer<IPointerEvent | IMouseEvent>>;@@ -55,9 +54,7 @@ export class DragLineController {private _dragUp: (distance: Nullable<number>, e: IPointerEvent | IMouseEvent) => void;- constructor(manager: SelectionManager) {- this._manager = manager;- }+ constructor(@Inject(CanvasView) private readonly _canvasView: CanvasView) {}getDragLine() {return this._dragLine;@@ -70,7 +67,7 @@ export class DragLineController {this._start = start;this._dragUp = dragUp;- const skeleton = this._manager.getSheetView().getSpreadsheetColumnTitle().getSkeleton();+ const skeleton = this._canvasView.getSheetView().getSpreadsheetColumnTitle().getSkeleton();if (direction) {const width = skeleton?.rowTitleWidth;const contentWidth = skeleton?.columnTotalWidth;@@ -113,13 +110,13 @@ export class DragLineController {this._dragLine.evented = false;- const scene = this._manager.getScene();+ const scene = this._canvasView.getSheetView().getScene();scene.addObject(this._dragLine, 3);}dragDown(e: IPointerEvent | IMouseEvent) {- const scene = this._manager.getScene();+ const scene = this._canvasView.getSheetView().getScene();scene.disableEvent();diff --git a/packages/base-sheets/src/Controller/Selection/RowTitleController.ts b/packages/base-sheets/src/Controller/Selection/RowTitleController.tsindex e19300855f..d5767cd112 100644--- a/packages/base-sheets/src/Controller/Selection/RowTitleController.ts+++ b/packages/base-sheets/src/Controller/Selection/RowTitleController.ts@@ -1,11 +1,12 @@import { CURSOR_TYPE, Group, IMouseEvent, IPointerEvent, Rect } from '@univerjs/base-render';-import { Nullable } from '@univerjs/core';-import { DragLineDirection } from './DragLineController';-import { SelectionManager } from './SelectionManager';+import { Nullable, SheetContext } from '@univerjs/core';+import { Inject } from '@wendellhu/redi';+import { DragLineController, DragLineDirection } from './DragLineController';+import { CanvasView } from '../../View';+import { ISheetContext } from '../../Services/tokens';+import { IColumnTitleControllerHandlers } from './Shared';export class RowTitleController {- private _manager: SelectionManager;-private _leftTopHeight: number;private _startOffsetX: number = 0;@@ -22,11 +23,17 @@ export class RowTitleController {private _Item: Rect;- constructor(manager: SelectionManager) {- this._manager = manager;- this._leftTopHeight = this._manager.getSheetView().getSpreadsheetLeftTopPlaceholder().getState().height;+ private handlers: IColumnTitleControllerHandlers | null = null;++ constructor(+ @ISheetContext private readonly _sheetContext: SheetContext,+ @Inject(CanvasView) private readonly _canvasView: CanvasView,+ @Inject(DragLineController) private readonly _dragLineController: DragLineController+ ) {+ const sheetView = this._canvasView.getSheetView();+ this._leftTopHeight = sheetView.getSpreadsheetLeftTopPlaceholder().getState().height;- const width = this._manager.getSheetView().getSpreadsheetSkeleton().rowTitleWidth;+ const width = sheetView.getSpreadsheetSkeleton().rowTitleWidth;// 创建高亮itemthis._content = new Rect('RowTitleContent', {width,@@ -43,15 +50,19 @@ export class RowTitleController {this._highlightItem = new Group('RowTitleGroup', this._content, this._Item);this._highlightItem.hide();- const scene = this._manager.getScene();+ const scene = sheetView.getScene();scene.addObject(this._highlightItem, 3);this._initialize();}+ setHandlers(handlers: IColumnTitleControllerHandlers): void {+ this.handlers = handlers;+ }+pointerDown(e: IPointerEvent | IMouseEvent) {- const main = this._manager.getMainComponent();+ const main = this._canvasView.getSheetView().getSpreadsheet();const { offsetX: evtOffsetX, offsetY: evtOffsetY } = e;this._startOffsetX = evtOffsetX;this._startOffsetY = evtOffsetY;@@ -80,21 +91,20 @@ export class RowTitleController {const end = rowHeightAccumulation[this._index] + this._leftTopHeight;const start = (this._index ? rowHeightAccumulation[this._index - 1] : 0) + this._leftTopHeight;- this._manager.getDragLineControl().create({+ this._dragLineController.create({direction: DragLineDirection.HORIZONTAL,end,start,dragUp: this.setRowHeight.bind(this),});- this._manager.getDragLineControl().dragDown(e);+ this._dragLineController.dragDown(e);}// 高亮当前行this.highlightRow();}setRowHeight(height: Nullable<number>) {- const plugin = this._manager.getPlugin();- const sheet = plugin.getContext().getWorkBook().getActiveSheet();+ const sheet = this._sheetContext.getWorkBook().getActiveSheet();if (height === null) {sheet.setRowHeights(this._index, 1, 5);} else {@@ -104,9 +114,9 @@ export class RowTitleController {}highlightRow() {- this._manager.clearSelectionControls();- const sheet = this._manager.getPlugin().getWorkbook().getActiveSheet();- this._manager.addControlToCurrentByRangeData(+ this.handlers?.clearSelectionControls();+ const sheet = this._sheetContext.getWorkBook().getActiveSheet();+ this.handlers?.addControlToCurrentByRangeData({startRow: this._index,startColumn: 0,@@ -121,7 +131,7 @@ export class RowTitleController {}highlightRowTitle(e: IPointerEvent | IMouseEvent) {- const main = this._manager.getMainComponent();+ const main = this._canvasView.getSheetView().getSpreadsheet();const { offsetX: evtOffsetX, offsetY: evtOffsetY } = e;this._startOffsetX = evtOffsetX;this._startOffsetY = evtOffsetY;diff --git a/packages/base-sheets/src/Controller/Selection/SelectionControlDragDrop.ts b/packages/base-sheets/src/Controller/Selection/SelectionControlDragDrop.tsindex e325028161..08a7c41aec 100644--- a/packages/base-sheets/src/Controller/Selection/SelectionControlDragDrop.ts+++ b/packages/base-sheets/src/Controller/Selection/SelectionControlDragDrop.ts@@ -1,356 +1,375 @@-import { CURSOR_TYPE, Group, IMouseEvent, IPointerEvent, Rect, ScrollTimer } from '@univerjs/base-render';-import { Direction, ISelection, makeCellToSelection, Nullable, Observer } from '@univerjs/core';-import { SelectionModel } from '../../Model';-import { DEFAULT_SELECTION_CONFIG, SelectionControl, SELECTION_TYPE } from './SelectionController';--enum SELECTION_DRAG_KEY {- Selection = '__SelectionDragShape__',- top = '__TopDragControl__',- bottom = '__BottomDragControl__',- left = '__LeftDragControl__',- right = '__RightDragControl__',-}--interface IPositionOffset {- left: number;- right: number;- top: number;- bottom: number;-}--export class SelectionControlDragAndDrop {- private _leftDragControl: Rect;-- private _rightDragControl: Rect;-- private _topDragControl: Rect;-- private _bottomDragControl: Rect;-- private _selectionDragShape: Group;-- private _zIndex: number;-- private _model: SelectionModel;-- private _oldSelectionRange: ISelection;-- private _startOffsetX: number = 0;-- private _startOffsetY: number = 0;-- private _cellPositionOffset: IPositionOffset;-- private _moveObserver: Nullable<Observer<IPointerEvent | IMouseEvent>>;-- private _upObserver: Nullable<Observer<IPointerEvent | IMouseEvent>>;-- constructor(private _control: SelectionControl) {- this._zIndex = _control.zIndex + 1;- this._model = _control.model;- this._initialize();- }-- static create(control: SelectionControl) {- return new SelectionControlDragAndDrop(control);- }-- dragEventInitial() {- // TODO ...- }-- dragDown(evt: IPointerEvent | IMouseEvent, direction: Direction) {- const main = this._control.getPlugin().getMainComponent();-- // reset model- const selection = this._model.getValue().selection;- this._model = new SelectionModel(SELECTION_TYPE.NORMAL, this._control.getPlugin());- this._model.setValue(selection);-- // update control- this._updateControl();-- const { offsetX: evtOffsetX, offsetY: evtOffsetY } = evt;- this._startOffsetX = evtOffsetX;- this._startOffsetY = evtOffsetY;- const scrollXY = main.getAncestorScrollXY(this._startOffsetX, this._startOffsetY);-- // Subtract the border width to make the calculation of selected cells more accurate- let cellInfo = null;- switch (direction) {- case Direction.LEFT:- cellInfo = main.calculateCellIndexByPosition(evtOffsetX + DEFAULT_SELECTION_CONFIG.strokeWidth, evtOffsetY, scrollXY);- break;- case Direction.TOP:- cellInfo = main.calculateCellIndexByPosition(evtOffsetX, evtOffsetY + DEFAULT_SELECTION_CONFIG.strokeWidth, scrollXY);- break;- case Direction.RIGHT:- cellInfo = main.calculateCellIndexByPosition(evtOffsetX - DEFAULT_SELECTION_CONFIG.strokeWidth, evtOffsetY, scrollXY);- break;- case Direction.BOTTOM:- cellInfo = main.calculateCellIndexByPosition(evtOffsetX, evtOffsetY - DEFAULT_SELECTION_CONFIG.strokeWidth, scrollXY);- break;-- default:- break;- }-- const actualSelection = makeCellToSelection(cellInfo);- if (!actualSelection) {- return false;- }-- const { startRow, startColumn, endColumn, endRow, startY, endY, startX, endX } = actualSelection;-- const startSelectionRange = {- startColumn,- startRow,- endColumn,- endRow,- startY,- endY,- startX,- endX,- };-- this._oldSelectionRange = startSelectionRange;-- // calculate active cell in selection position- this._cellPositionOffset = {- top: startSelectionRange.startRow - this._model.startRow,- bottom: this._model.endRow - startSelectionRange.endRow,- left: startSelectionRange.startColumn - this._model.startColumn,- right: this._model.endColumn - startSelectionRange.endColumn,- };-- const scene = this._control.getScene();-- scene.disableEvent();-- const scrollTimer = ScrollTimer.create(scene);- scrollTimer.startScroll(evtOffsetX, evtOffsetY);-- this._moveObserver = scene.onPointerMoveObserver.add((moveEvt: IPointerEvent | IMouseEvent) => {- this.dragMoving(moveEvt);- const { offsetX: moveOffsetX, offsetY: moveOffsetY } = moveEvt;- scrollTimer.scrolling(moveOffsetX, moveOffsetY, () => {- this.dragMoving(moveEvt);- });- });-- this._upObserver = scene.onPointerUpObserver.add((upEvt: IPointerEvent | IMouseEvent) => {- this.dragUp();- scene.onPointerMoveObserver.remove(this._moveObserver);- scene.onPointerUpObserver.remove(this._upObserver);- scene.enableEvent();- scrollTimer.stopScroll();- });- }-- dragMoving(moveEvt: IPointerEvent | IMouseEvent) {- const main = this._control.getPlugin().getMainComponent();- const { offsetX: moveOffsetX, offsetY: moveOffsetY, clientX, clientY } = moveEvt;-- const scrollXY = main.getAncestorScrollXY(this._startOffsetX, this._startOffsetY);- const moveCellInfo = main.calculateCellIndexByPosition(moveOffsetX, moveOffsetY, scrollXY);- const moveActualSelection = makeCellToSelection(moveCellInfo);-- if (!moveActualSelection) {- return false;- }- const { startRow: moveStartRow, startColumn: moveStartColumn, endColumn: moveEndColumn, endRow: moveEndRow, startX, startY, endX, endY } = moveActualSelection;-- const newSelectionRange: ISelection = {- startColumn: moveStartColumn,- startRow: moveStartRow,- endColumn: moveEndColumn,- endRow: moveEndRow,- startY: startY || 0,- endY: endY || 0,- startX: startX || 0,- endX: endX || 0,- };- // when the selection changes- const { startRow: oldStartRow, endRow: oldEndRow, startColumn: oldStartColumn, endColumn: oldEndColumn } = this._oldSelectionRange;-- if (oldStartColumn !== moveStartColumn || oldStartRow !== moveStartRow || oldEndColumn !== moveEndColumn || oldEndRow !== moveEndRow) {- this._oldSelectionRange = newSelectionRange;-- // Calculate the position of the selection based on the position of the cell selected when clicking- const { left, right, top, bottom } = this._cellPositionOffset;-- const startRowTop = moveStartRow - top;- const endRowBottom = moveEndRow + bottom;- const startColumnLeft = moveStartColumn - left;- const endColumnRight = moveEndColumn + right;-- // Boundary detection- if (startRowTop < 0 || endRowBottom < 0 || startColumnLeft < 0 || endColumnRight < 0) {- return;- }- const newSelection = {- startRow: startRowTop,- endRow: endRowBottom,- startColumn: startColumnLeft,- endColumn: endColumnRight,- };-- const startCell = main.getNoMergeCellPositionByIndex(newSelection.startRow, newSelection.startColumn);- const endCell = main.getNoMergeCellPositionByIndex(newSelection.endRow, newSelection.endColumn);-- const newSelectionPosition = Object.assign(newSelection, {- startY: startCell?.startY || 0,- endY: endCell?.endY || 0,- startX: startCell?.startX || 0,- endX: endCell?.endX || 0,- });-- this._model.setValue(newSelectionPosition);-- this._updateControl();- }- }-- dragUp() {- const main = this._control.getPlugin().getMainComponent();-- this.hide();-- const { selection } = this._model.getValue();-- // By default, the upper left corner is the active cell- const cell = main.getCellByIndex(selection.startRow, selection.startColumn);- this._control.update(selection, cell);- }-- _updateControl() {- const { startX, startY, endX, endY } = this._model;-- this._leftDragControl.resize(undefined, endY - startY);- this._rightDragControl.transformByState({- height: endY - startY,- left: endX - startX - DEFAULT_SELECTION_CONFIG.strokeWidth / 2,- });- this._topDragControl.resize(endX - startX + DEFAULT_SELECTION_CONFIG.strokeWidth);- this._bottomDragControl.transformByState({- width: endX - startX + DEFAULT_SELECTION_CONFIG.strokeWidth,- top: endY - startY - DEFAULT_SELECTION_CONFIG.strokeWidth / 2,- });-- this._selectionDragShape.show();- this._selectionDragShape.translate(startX, startY);-- this._selectionDragShape.makeDirty(true);- }-- hide() {- this._selectionDragShape.hide();- this._selectionDragShape.makeDirty(true);- }-- dispose() {- this._leftDragControl.dispose();- this._rightDragControl.dispose();- this._topDragControl.dispose();- this._bottomDragControl.dispose();- this._selectionDragShape.dispose();- }-- remove() {- const { leftControl, rightControl, topControl, bottomControl } = this._control;- leftControl.onPointerEnterObserver.clear();- leftControl.onPointerLeaveObserver.clear();- rightControl.onPointerEnterObserver.clear();- rightControl.onPointerLeaveObserver.clear();- topControl.onPointerEnterObserver.clear();- topControl.onPointerLeaveObserver.clear();- bottomControl.onPointerEnterObserver.clear();- bottomControl.onPointerLeaveObserver.clear();- }-- private _initialize() {- const plugin = this._control.getPlugin();-- const main = plugin.getMainComponent();-- const { leftControl, rightControl, topControl, bottomControl, fillControl } = this._control;- leftControl.onPointerEnterObserver.add((evt: IPointerEvent | IMouseEvent) => {- leftControl.cursor = CURSOR_TYPE.MOVE;- });-- leftControl.onPointerLeaveObserver.add((evt: IPointerEvent | IMouseEvent) => {- leftControl.resetCursor();- });-- rightControl.onPointerEnterObserver.add((evt: IPointerEvent | IMouseEvent) => {- rightControl.cursor = CURSOR_TYPE.MOVE;- });-- rightControl.onPointerLeaveObserver.add((evt: IPointerEvent | IMouseEvent) => {- rightControl.resetCursor();- });-- topControl.onPointerEnterObserver.add((evt: IPointerEvent | IMouseEvent) => {- topControl.cursor = CURSOR_TYPE.MOVE;- });-- topControl.onPointerLeaveObserver.add((evt: IPointerEvent | IMouseEvent) => {- topControl.resetCursor();- });-- bottomControl.onPointerEnterObserver.add((evt: IPointerEvent | IMouseEvent) => {- bottomControl.cursor = CURSOR_TYPE.MOVE;- });-- bottomControl.onPointerLeaveObserver.add((evt: IPointerEvent | IMouseEvent) => {- bottomControl.resetCursor();- });-- bottomControl.onPointerDownObserver.add((evt: IPointerEvent | IMouseEvent) => {- this.dragDown(evt, Direction.BOTTOM);- });-- bottomControl.onPointerUpObserver.add((evt: IPointerEvent | IMouseEvent) => {- bottomControl.resetCursor();- });-- // init drag render box- const zIndex = this._zIndex;- this._leftDragControl = new Rect(SELECTION_DRAG_KEY.left + zIndex, {- top: 0,- left: -DEFAULT_SELECTION_CONFIG.strokeWidth / 2,- width: DEFAULT_SELECTION_CONFIG.strokeWidth * 2,- fill: DEFAULT_SELECTION_CONFIG.strokeColor,- zIndex,- });- this._rightDragControl = new Rect(SELECTION_DRAG_KEY.right + zIndex, {- width: DEFAULT_SELECTION_CONFIG.strokeWidth * 2,- fill: DEFAULT_SELECTION_CONFIG.strokeColor,- zIndex,- });- this._topDragControl = new Rect(SELECTION_DRAG_KEY.top + zIndex, {- top: -DEFAULT_SELECTION_CONFIG.strokeWidth / 2,- left: -DEFAULT_SELECTION_CONFIG.strokeWidth / 2,- height: DEFAULT_SELECTION_CONFIG.strokeWidth * 2,- fill: DEFAULT_SELECTION_CONFIG.strokeColor,- zIndex,- });- this._bottomDragControl = new Rect(SELECTION_DRAG_KEY.bottom + zIndex, {- height: DEFAULT_SELECTION_CONFIG.strokeWidth * 2,- fill: DEFAULT_SELECTION_CONFIG.strokeColor,- left: -DEFAULT_SELECTION_CONFIG.strokeWidth / 2,- zIndex,- });-- this._selectionDragShape = new Group(SELECTION_DRAG_KEY.Selection + zIndex, this._leftDragControl, this._rightDragControl, this._topDragControl, this._bottomDragControl);-- // this._selectionDragShape.visible = false;-- this._selectionDragShape.evented = false;-- this._selectionDragShape.zIndex = zIndex;-- const scene = this._control.getScene();- scene.addObject(this._selectionDragShape);- }-}+import { CURSOR_TYPE, Group, IMouseEvent, IPointerEvent, Rect, ScrollTimer } from '@univerjs/base-render';+import { Direction, ICellInfo, ISelection, makeCellToSelection, Nullable, Observer } from '@univerjs/core';+import { Inject, Injector } from '@wendellhu/redi';+import { SelectionModel } from '../../Model';+import { DEFAULT_SELECTION_CONFIG, SELECTION_TYPE } from './SelectionController';+import { CanvasView } from '../../View';++enum SELECTION_DRAG_KEY {+ Selection = '__SelectionDragShape__',+ top = '__TopDragControl__',+ bottom = '__BottomDragControl__',+ left = '__LeftDragControl__',+ right = '__RightDragControl__',+}++interface IPositionOffset {+ left: number;+ right: number;+ top: number;+ bottom: number;+}++export interface ISelectionControlDragDropHandler {+ leftControl: Rect;+ rightControl: Rect;+ topControl: Rect;+ bottomControl: Rect;+ fillControl: Rect;++ update(newSelectionRange: ISelection, highlight: Nullable<ICellInfo>): void;+}++export class SelectionControlDragAndDrop {+ private _leftDragControl: Rect;++ private _rightDragControl: Rect;++ private _topDragControl: Rect;++ private _bottomDragControl: Rect;++ private _selectionDragShape: Group;++ private _zIndex: number;++ private _model: SelectionModel;++ private _oldSelectionRange: ISelection;++ private _startOffsetX: number = 0;++ private _startOffsetY: number = 0;++ private _cellPositionOffset: IPositionOffset;++ private _moveObserver: Nullable<Observer<IPointerEvent | IMouseEvent>>;++ private _upObserver: Nullable<Observer<IPointerEvent | IMouseEvent>>;++ constructor(+ zIndex: number,+ model: SelectionModel,+ private readonly _handlers: ISelectionControlDragDropHandler,+ @Inject(Injector) private readonly _injector: Injector,+ @Inject(CanvasView) private readonly _canvasView: CanvasView+ ) {+ this._zIndex = zIndex + 1;+ this._model = model;++ this._initialize();+ }++ static create(injector: Injector, zIndex: number, model: SelectionModel, handler: ISelectionControlDragDropHandler) {+ return injector.createInstance(SelectionControlDragAndDrop, zIndex, model, handler);+ }++ dragEventInitial() {+ // TODO ...+ }++ dragDown(evt: IPointerEvent | IMouseEvent, direction: Direction) {+ const main = this._canvasView.getSheetView().getSpreadsheet();++ // reset model+ const selection = this._model.getValue().selection;+ this._model = this._injector.createInstance(SelectionModel, SELECTION_TYPE.NORMAL);+ this._model.setValue(selection);++ // update control+ this._updateControl();++ const { offsetX: evtOffsetX, offsetY: evtOffsetY } = evt;+ this._startOffsetX = evtOffsetX;+ this._startOffsetY = evtOffsetY;+ const scrollXY = main.getAncestorScrollXY(this._startOffsetX, this._startOffsetY);++ // Subtract the border width to make the calculation of selected cells more accurate+ let cellInfo = null;+ switch (direction) {+ case Direction.LEFT:+ cellInfo = main.calculateCellIndexByPosition(evtOffsetX + DEFAULT_SELECTION_CONFIG.strokeWidth, evtOffsetY, scrollXY);+ break;+ case Direction.TOP:+ cellInfo = main.calculateCellIndexByPosition(evtOffsetX, evtOffsetY + DEFAULT_SELECTION_CONFIG.strokeWidth, scrollXY);+ break;+ case Direction.RIGHT:+ cellInfo = main.calculateCellIndexByPosition(evtOffsetX - DEFAULT_SELECTION_CONFIG.strokeWidth, evtOffsetY, scrollXY);+ break;+ case Direction.BOTTOM:+ cellInfo = main.calculateCellIndexByPosition(evtOffsetX, evtOffsetY - DEFAULT_SELECTION_CONFIG.strokeWidth, scrollXY);+ break;++ default:+ break;+ }++ const actualSelection = makeCellToSelection(cellInfo);+ if (!actualSelection) {+ return false;+ }++ const { startRow, startColumn, endColumn, endRow, startY, endY, startX, endX } = actualSelection;++ const startSelectionRange = {+ startColumn,+ startRow,+ endColumn,+ endRow,+ startY,+ endY,+ startX,+ endX,+ };++ this._oldSelectionRange = startSelectionRange;++ // calculate active cell in selection position+ this._cellPositionOffset = {+ top: startSelectionRange.startRow - this._model.startRow,+ bottom: this._model.endRow - startSelectionRange.endRow,+ left: startSelectionRange.startColumn - this._model.startColumn,+ right: this._model.endColumn - startSelectionRange.endColumn,+ };++ const scene = this._canvasView.getSheetView().getScene();++ scene.disableEvent();++ const scrollTimer = ScrollTimer.create(scene);+ scrollTimer.startScroll(evtOffsetX, evtOffsetY);++ this._moveObserver = scene.onPointerMoveObserver.add((moveEvt: IPointerEvent | IMouseEvent) => {+ this.dragMoving(moveEvt);+ const { offsetX: moveOffsetX, offsetY: moveOffsetY } = moveEvt;+ scrollTimer.scrolling(moveOffsetX, moveOffsetY, () => {+ this.dragMoving(moveEvt);+ });+ });++ this._upObserver = scene.onPointerUpObserver.add((upEvt: IPointerEvent | IMouseEvent) => {+ this.dragUp();+ scene.onPointerMoveObserver.remove(this._moveObserver);+ scene.onPointerUpObserver.remove(this._upObserver);+ scene.enableEvent();+ scrollTimer.stopScroll();+ });+ }++ dragMoving(moveEvt: IPointerEvent | IMouseEvent) {+ const main = this._canvasView.getSheetView().getSpreadsheet();+ const { offsetX: moveOffsetX, offsetY: moveOffsetY, clientX, clientY } = moveEvt;++ const scrollXY = main.getAncestorScrollXY(this._startOffsetX, this._startOffsetY);+ const moveCellInfo = main.calculateCellIndexByPosition(moveOffsetX, moveOffsetY, scrollXY);+ const moveActualSelection = makeCellToSelection(moveCellInfo);++ if (!moveActualSelection) {+ return false;+ }+ const { startRow: moveStartRow, startColumn: moveStartColumn, endColumn: moveEndColumn, endRow: moveEndRow, startX, startY, endX, endY } = moveActualSelection;++ const newSelectionRange: ISelection = {+ startColumn: moveStartColumn,+ startRow: moveStartRow,+ endColumn: moveEndColumn,+ endRow: moveEndRow,+ startY: startY || 0,+ endY: endY || 0,+ startX: startX || 0,+ endX: endX || 0,+ };+ // when the selection changes+ const { startRow: oldStartRow, endRow: oldEndRow, startColumn: oldStartColumn, endColumn: oldEndColumn } = this._oldSelectionRange;++ if (oldStartColumn !== moveStartColumn || oldStartRow !== moveStartRow || oldEndColumn !== moveEndColumn || oldEndRow !== moveEndRow) {+ this._oldSelectionRange = newSelectionRange;++ // Calculate the position of the selection based on the position of the cell selected when clicking+ const { left, right, top, bottom } = this._cellPositionOffset;++ const startRowTop = moveStartRow - top;+ const endRowBottom = moveEndRow + bottom;+ const startColumnLeft = moveStartColumn - left;+ const endColumnRight = moveEndColumn + right;++ // Boundary detection+ if (startRowTop < 0 || endRowBottom < 0 || startColumnLeft < 0 || endColumnRight < 0) {+ return;+ }+ const newSelection = {+ startRow: startRowTop,+ endRow: endRowBottom,+ startColumn: startColumnLeft,+ endColumn: endColumnRight,+ };++ const startCell = main.getNoMergeCellPositionByIndex(newSelection.startRow, newSelection.startColumn);+ const endCell = main.getNoMergeCellPositionByIndex(newSelection.endRow, newSelection.endColumn);++ const newSelectionPosition = Object.assign(newSelection, {+ startY: startCell?.startY || 0,+ endY: endCell?.endY || 0,+ startX: startCell?.startX || 0,+ endX: endCell?.endX || 0,+ });++ this._model.setValue(newSelectionPosition);++ this._updateControl();+ }+ }++ dragUp() {+ const main = this._canvasView.getSheetView().getSpreadsheet();++ this.hide();++ const { selection } = this._model.getValue();++ // By default, the upper left corner is the active cell+ const cell = main.getCellByIndex(selection.startRow, selection.startColumn);++ // TODO@huwenzhao: add a handler here+ this._handlers.update(selection, cell);+ }++ _updateControl() {+ const { startX, startY, endX, endY } = this._model;++ this._leftDragControl.resize(undefined, endY - startY);+ this._rightDragControl.transformByState({+ height: endY - startY,+ left: endX - startX - DEFAULT_SELECTION_CONFIG.strokeWidth / 2,+ });+ this._topDragControl.resize(endX - startX + DEFAULT_SELECTION_CONFIG.strokeWidth);+ this._bottomDragControl.transformByState({+ width: endX - startX + DEFAULT_SELECTION_CONFIG.strokeWidth,+ top: endY - startY - DEFAULT_SELECTION_CONFIG.strokeWidth / 2,+ });++ this._selectionDragShape.show();+ this._selectionDragShape.translate(startX, startY);++ this._selectionDragShape.makeDirty(true);+ }++ hide() {+ this._selectionDragShape.hide();+ this._selectionDragShape.makeDirty(true);+ }++ dispose() {+ this._leftDragControl.dispose();+ this._rightDragControl.dispose();+ this._topDragControl.dispose();+ this._bottomDragControl.dispose();+ this._selectionDragShape.dispose();+ }++ remove() {+ const { leftControl, rightControl, topControl, bottomControl } = this._handlers;++ leftControl.onPointerEnterObserver.clear();+ leftControl.onPointerLeaveObserver.clear();+ rightControl.onPointerEnterObserver.clear();+ rightControl.onPointerLeaveObserver.clear();+ topControl.onPointerEnterObserver.clear();+ topControl.onPointerLeaveObserver.clear();+ bottomControl.onPointerEnterObserver.clear();+ bottomControl.onPointerLeaveObserver.clear();+ }++ private _initialize() {+ const { leftControl, rightControl, topControl, bottomControl, fillControl } = this._handlers;++ leftControl.onPointerEnterObserver.add((evt: IPointerEvent | IMouseEvent) => {+ leftControl.cursor = CURSOR_TYPE.MOVE;+ });++ leftControl.onPointerLeaveObserver.add((evt: IPointerEvent | IMouseEvent) => {+ leftControl.resetCursor();+ });++ rightControl.onPointerEnterObserver.add((evt: IPointerEvent | IMouseEvent) => {+ rightControl.cursor = CURSOR_TYPE.MOVE;+ });++ rightControl.onPointerLeaveObserver.add((evt: IPointerEvent | IMouseEvent) => {+ rightControl.resetCursor();+ });++ topControl.onPointerEnterObserver.add((evt: IPointerEvent | IMouseEvent) => {+ topControl.cursor = CURSOR_TYPE.MOVE;+ });++ topControl.onPointerLeaveObserver.add((evt: IPointerEvent | IMouseEvent) => {+ topControl.resetCursor();+ });++ bottomControl.onPointerEnterObserver.add((evt: IPointerEvent | IMouseEvent) => {+ bottomControl.cursor = CURSOR_TYPE.MOVE;+ });++ bottomControl.onPointerLeaveObserver.add((evt: IPointerEvent | IMouseEvent) => {+ bottomControl.resetCursor();+ });++ bottomControl.onPointerDownObserver.add((evt: IPointerEvent | IMouseEvent) => {+ this.dragDown(evt, Direction.BOTTOM);+ });++ bottomControl.onPointerUpObserver.add((evt: IPointerEvent | IMouseEvent) => {+ bottomControl.resetCursor();+ });++ // init drag render box+ const zIndex = this._zIndex;+ this._leftDragControl = new Rect(SELECTION_DRAG_KEY.left + zIndex, {+ top: 0,+ left: -DEFAULT_SELECTION_CONFIG.strokeWidth / 2,+ width: DEFAULT_SELECTION_CONFIG.strokeWidth * 2,+ fill: DEFAULT_SELECTION_CONFIG.strokeColor,+ zIndex,+ });+ this._rightDragControl = new Rect(SELECTION_DRAG_KEY.right + zIndex, {+ width: DEFAULT_SELECTION_CONFIG.strokeWidth * 2,+ fill: DEFAULT_SELECTION_CONFIG.strokeColor,+ zIndex,+ });+ this._topDragControl = new Rect(SELECTION_DRAG_KEY.top + zIndex, {+ top: -DEFAULT_SELECTION_CONFIG.strokeWidth / 2,+ left: -DEFAULT_SELECTION_CONFIG.strokeWidth / 2,+ height: DEFAULT_SELECTION_CONFIG.strokeWidth * 2,+ fill: DEFAULT_SELECTION_CONFIG.strokeColor,+ zIndex,+ });+ this._bottomDragControl = new Rect(SELECTION_DRAG_KEY.bottom + zIndex, {+ height: DEFAULT_SELECTION_CONFIG.strokeWidth * 2,+ fill: DEFAULT_SELECTION_CONFIG.strokeColor,+ left: -DEFAULT_SELECTION_CONFIG.strokeWidth / 2,+ zIndex,+ });++ this._selectionDragShape = new Group(SELECTION_DRAG_KEY.Selection + zIndex, this._leftDragControl, this._rightDragControl, this._topDragControl, this._bottomDragControl);++ // this._selectionDragShape.visible = false;++ this._selectionDragShape.evented = false;++ this._selectionDragShape.zIndex = zIndex;++ const scene = this._canvasView.getSheetView().getScene();+ scene.addObject(this._selectionDragShape);+ }+}diff --git a/packages/base-sheets/src/Controller/Selection/SelectionControlFill.ts b/packages/base-sheets/src/Controller/Selection/SelectionControlFill.tsindex 1ca19bcd33..ae8f72fa10 100644--- a/packages/base-sheets/src/Controller/Selection/SelectionControlFill.ts+++ b/packages/base-sheets/src/Controller/Selection/SelectionControlFill.ts@@ -1,30 +1,33 @@-import { CURSOR_TYPE, IMouseEvent, IPointerEvent } from '@univerjs/base-render';-import { SelectionControl } from './SelectionController';--export class SelectionControlFill {- constructor(private _control: SelectionControl) {- this._initialize();- }-- static create(control: SelectionControl) {- return new SelectionControlFill(control);- }-- remove() {- const { fillControl } = this._control;- fillControl.onPointerEnterObserver.clear();- fillControl.onPointerLeaveObserver.clear();- }-- private _initialize() {- const { fillControl } = this._control;- const plugin = this._control.getPlugin();- fillControl.onPointerEnterObserver.add((evt: IPointerEvent | IMouseEvent) => {- fillControl.cursor = CURSOR_TYPE.CROSSHAIR;- });-- fillControl.onPointerLeaveObserver.add((evt: IPointerEvent | IMouseEvent) => {- fillControl.resetCursor();- });- }-}+import { CURSOR_TYPE, IMouseEvent, IPointerEvent, Rect } from '@univerjs/base-render';+import { Injector } from '@wendellhu/redi';++export interface ISelectionControlHandler {+ fillControl: Rect;+}++export class SelectionControlFill {+ constructor(private readonly _handler: ISelectionControlHandler) {+ this._initialize();+ }++ static create(injector: Injector, handler: ISelectionControlHandler) {+ return injector.createInstance(SelectionControlFill, handler);+ }++ remove() {+ const { fillControl } = this._handler;+ fillControl.onPointerEnterObserver.clear();+ fillControl.onPointerLeaveObserver.clear();+ }++ private _initialize() {+ const { fillControl } = this._handler;+ fillControl.onPointerEnterObserver.add((evt: IPointerEvent | IMouseEvent) => {+ fillControl.cursor = CURSOR_TYPE.CROSSHAIR;+ });++ fillControl.onPointerLeaveObserver.add((evt: IPointerEvent | IMouseEvent) => {+ fillControl.resetCursor();+ });+ }+}diff --git a/packages/base-sheets/src/Controller/Selection/SelectionController.ts b/packages/base-sheets/src/Controller/Selection/SelectionController.tsindex 8e3a0e9dca..321776bf09 100644--- a/packages/base-sheets/src/Controller/Selection/SelectionController.ts+++ b/packages/base-sheets/src/Controller/Selection/SelectionController.ts@@ -1,458 +1,457 @@-import { Rect, Group, Spreadsheet } from '@univerjs/base-render';-import { Nullable, ISelection, ICellInfo } from '@univerjs/core';-import { SelectionModel } from '../../Model/SelectionModel';-import { SelectionControlDragAndDrop } from './SelectionControlDragDrop';-import { SelectionControlFill } from './SelectionControlFill';-import { SelectionManager } from './SelectionManager';--// export enum DEFAULT_SELECTION_CONFIG {-// strokeColor = 'rgb(1,136,251)',-// backgroundColor = 'rgba(1,136,251, 0.1)',-// strokeWidth = 2,-// fillSideLength = 6,-// fillStrokeLength = 1,-// fillStrokeColor = 'rgb(255,255,255)',-// }-export const DEFAULT_SELECTION_CONFIG = {- strokeColor: 'rgb(1,136,251)',- backgroundColor: 'rgba(1,136,251, 0.1)',- strokeWidth: 2,- fillSideLength: 6,- fillStrokeLength: 1,- fillStrokeColor: 'rgb(255,255,255)',-};--export enum SELECTION_TYPE {- NORMAL,- ROW,- COLUMN,-}--enum SELECTION_MANAGER_KEY {- Selection = '__SpreadsheetSelectionShape__',- top = '__SpreadsheetSelectionTopControl__',- bottom = '__SpreadsheetSelectionBottomControl__',- left = '__SpreadsheetSelectionShapeLeftControl__',- right = '__SpreadsheetSelectionShapeRightControl__',- backgroundTop = '__SpreadsheetSelectionBackgroundControlTop__',- backgroundMiddleLeft = '__SpreadsheetSelectionBackgroundControlMiddleLeft__',- backgroundMiddleRight = '__SpreadsheetSelectionBackgroundControlMiddleRight__',- backgroundBottom = '__SpreadsheetSelectionBackgroundControlBottom__',- fill = '__SpreadsheetSelectionFillControl__',- lineMain = '__SpreadsheetDragLineMainControl__',- lineContent = '__SpreadsheetDragLineContentControl__',- line = '__SpreadsheetDragLineControl__',-}--/**- * The main selection canvas component- */-export class SelectionControl {- private _mainComponent: Spreadsheet;-- private _leftControl: Rect;-- private _rightControl: Rect;-- private _topControl: Rect;-- private _bottomControl: Rect;-- private _backgroundControlTop: Rect;-- private _backgroundControlBottom: Rect;-- private _backgroundControlMiddleLeft: Rect;-- private _backgroundControlMiddleRight: Rect;-- private _fillControl: Rect;-- private _selectionShape: Group;-- private _selectionModel: SelectionModel;-- private _selectionDragAndDrop: SelectionControlDragAndDrop;-- private _selectionControlFill: SelectionControlFill;-- constructor(private _manager: SelectionManager, private _zIndex: number) {- this._initialize();- }-- get zIndex() {- return this._zIndex;- }-- get leftControl() {- return this._leftControl;- }-- get rightControl() {- return this._rightControl;- }-- get topControl() {- return this._topControl;- }-- get bottomControl() {- return this._bottomControl;- }-- get fillControl() {- return this._fillControl;- }-- get backgroundControlTop() {- return this._backgroundControlTop;- }-- get backgroundControlBottom() {- return this._backgroundControlBottom;- }-- get backgroundControlMiddleLeft() {- return this._backgroundControlMiddleLeft;- }-- get backgroundControlMiddleRight() {- return this._backgroundControlMiddleRight;- }-- get selectionShape() {- return this._selectionShape;- }-- get model() {- return this._selectionModel;- }-- static create(manager: SelectionManager, zIndex: number) {- return new this(manager, zIndex);- }-- static fromJson(manager: SelectionManager, zIndex: number, newSelectionRange: ISelection) {- const control = SelectionControl.create(manager, zIndex);- control.update(newSelectionRange);- return control;- }-- /**- * just handle the view- *- * inner update- */- _updateControl() {- const { startX, startY, endX, endY } = this._selectionModel;-- this.leftControl.resize(undefined, endY - startY);- this.rightControl.transformByState({- height: endY - startY,- left: endX - startX - DEFAULT_SELECTION_CONFIG.strokeWidth / 2,- });- this.topControl.resize(endX - startX + DEFAULT_SELECTION_CONFIG.strokeWidth);- this.bottomControl.transformByState({- width: endX - startX + DEFAULT_SELECTION_CONFIG.strokeWidth,- top: endY - startY - DEFAULT_SELECTION_CONFIG.strokeWidth / 2,- });-- this.fillControl.translate(endX - startX - DEFAULT_SELECTION_CONFIG.fillSideLength / 2, endY - startY - DEFAULT_SELECTION_CONFIG.fillSideLength / 2);-- this._updateBackgroundControl();- this._updateDragAndFill();-- this.selectionShape.show();- this.selectionShape.translate(startX, startY);-- this.selectionShape.makeDirty(true);- }-- update(newSelectionRange: ISelection, highlight: Nullable<ICellInfo>) {- this._selectionModel.setValue(newSelectionRange, highlight);- this._updateControl();- }-- // /**- // *When switching to the current sheet- // *- // * 1. Reinitialize the rendering component- // * 2. Calculate the position based on the current skeleton- // * 3. Update data- // * 4. Trigger rendering- // */- // render() {- // this._initialize();-- // let cellInfo = null;- // const main = this._manager.getMainComponent();- // const curCellRange = this._selectionModel.currentCell;-- // if (curCellRange) {- // cellInfo = main.getCellByIndex(curCellRange.row, curCellRange.column);- // }-- // const { startRow: finalStartRow, startColumn: finalStartColumn, endRow: finalEndRow, endColumn: finalEndColumn } = this._selectionModel;- // const startCell = main.getNoMergeCellPositionByIndex(finalStartRow, finalStartColumn);- // const endCell = main.getNoMergeCellPositionByIndex(finalEndRow, finalEndColumn);-- // this._manager.updateSelectionValue(- // this,- // {- // startColumn: finalStartColumn,- // startRow: finalStartRow,- // endColumn: finalEndColumn,- // endRow: finalEndRow,- // startY: startCell?.startY || 0,- // endY: endCell?.endY || 0,- // startX: startCell?.startX || 0,- // endX: endCell?.endX || 0,- // },- // cellInfo- // );-- // this._updateControl();- // }-- clearHighlight() {- this._selectionModel.clearCurrentCell();- this._updateControl();- }-- dispose() {- this._leftControl?.dispose();- this._rightControl?.dispose();- this._topControl?.dispose();- this._bottomControl?.dispose();- this._backgroundControlTop?.dispose();- this._backgroundControlMiddleLeft?.dispose();- this._backgroundControlMiddleRight?.dispose();- this._backgroundControlBottom?.dispose();- this._fillControl?.dispose();- this._selectionShape?.dispose();-- this._selectionDragAndDrop.dispose();- }-- getScene() {- return this._manager.getScene();- }-- getPlugin() {- return this._manager.getPlugin();- }-- /**- * Get the cell information of the current selection, considering the case of merging cells- */- getCurrentCellInfo(): Nullable<ISelection> {- const currentCell = this.model.currentCell;-- if (currentCell) {- let currentRangeData;-- if (currentCell.isMerged) {- const mergeInfo = currentCell.mergeInfo;-- currentRangeData = {- startRow: mergeInfo.startRow,- endRow: mergeInfo.endRow,- startColumn: mergeInfo.startColumn,- endColumn: mergeInfo.endColumn,- startX: mergeInfo.startX,- endX: mergeInfo.endX,- startY: mergeInfo.startY,- endY: mergeInfo.endY,- };- } else {- const { row, column, startX, endX, startY, endY } = currentCell;- currentRangeData = {- startRow: row,- endRow: row,- startColumn: column,- endColumn: column,- startX,- endX,- startY,- endY,- };- }-- return currentRangeData;- }- }-- private _initialize() {- this._selectionModel = new SelectionModel(SELECTION_TYPE.NORMAL, this._manager.getPlugin());- const zIndex = this._zIndex;- this._leftControl = new Rect(SELECTION_MANAGER_KEY.left + zIndex, {- top: 0,- left: -DEFAULT_SELECTION_CONFIG.strokeWidth / 2,- width: DEFAULT_SELECTION_CONFIG.strokeWidth,- fill: DEFAULT_SELECTION_CONFIG.strokeColor,- zIndex,- });- this._rightControl = new Rect(SELECTION_MANAGER_KEY.right + zIndex, {- width: DEFAULT_SELECTION_CONFIG.strokeWidth,- fill: DEFAULT_SELECTION_CONFIG.strokeColor,- zIndex,- });- this._topControl = new Rect(SELECTION_MANAGER_KEY.top + zIndex, {- top: -DEFAULT_SELECTION_CONFIG.strokeWidth / 2,- left: -DEFAULT_SELECTION_CONFIG.strokeWidth / 2,- height: DEFAULT_SELECTION_CONFIG.strokeWidth,- fill: DEFAULT_SELECTION_CONFIG.strokeColor,- zIndex,- });- this._bottomControl = new Rect(SELECTION_MANAGER_KEY.bottom + zIndex, {- height: DEFAULT_SELECTION_CONFIG.strokeWidth,- fill: DEFAULT_SELECTION_CONFIG.strokeColor,- left: -DEFAULT_SELECTION_CONFIG.strokeWidth / 2,- zIndex,- });- this._backgroundControlTop = new Rect(SELECTION_MANAGER_KEY.backgroundTop + zIndex, {- fill: DEFAULT_SELECTION_CONFIG.backgroundColor,- zIndex: zIndex - 1,- evented: false,- });- this._backgroundControlBottom = new Rect(SELECTION_MANAGER_KEY.backgroundBottom + zIndex, {- fill: DEFAULT_SELECTION_CONFIG.backgroundColor,- zIndex: zIndex - 1,- evented: false,- });- this._backgroundControlMiddleLeft = new Rect(SELECTION_MANAGER_KEY.backgroundMiddleLeft + zIndex, {- fill: DEFAULT_SELECTION_CONFIG.backgroundColor,- zIndex: zIndex - 1,- evented: false,- });- this._backgroundControlMiddleRight = new Rect(SELECTION_MANAGER_KEY.backgroundMiddleRight + zIndex, {- fill: DEFAULT_SELECTION_CONFIG.backgroundColor,- zIndex: zIndex - 1,- evented: false,- });- const fillSideLength = DEFAULT_SELECTION_CONFIG.fillSideLength - DEFAULT_SELECTION_CONFIG.fillStrokeLength;- this._fillControl = new Rect(SELECTION_MANAGER_KEY.fill + zIndex, {- width: fillSideLength,- height: fillSideLength,- fill: DEFAULT_SELECTION_CONFIG.strokeColor,- strokeWidth: DEFAULT_SELECTION_CONFIG.fillStrokeLength,- stroke: DEFAULT_SELECTION_CONFIG.fillStrokeColor,- zIndex: zIndex + 1,- });- this._selectionShape = new Group(- SELECTION_MANAGER_KEY.Selection + zIndex,- this._fillControl,- this._leftControl,- this._rightControl,- this._topControl,- this._bottomControl,- this._backgroundControlTop,- this._backgroundControlMiddleLeft,- this._backgroundControlMiddleRight,- this._backgroundControlBottom- );-- this._selectionShape.hide();-- this._selectionShape.evented = false;-- this._selectionShape.zIndex = zIndex;-- this._selectionDragAndDrop = SelectionControlDragAndDrop.create(this);-- this._selectionControlFill = SelectionControlFill.create(this);-- const scene = this.getScene();- scene.addObject(this._selectionShape);- }-- private _updateBackgroundControl() {- const {- startColumn,- startRow,- endColumn,- endRow,-- startX,- startY,- endX,- endY,- } = this._selectionModel;-- const highlightSelection = this._selectionModel.highlightToSelection();-- if (!highlightSelection) {- this._backgroundControlTop.resize(endX - startX, endY - startY);- this._backgroundControlBottom.resize(0, 0);- this._backgroundControlMiddleLeft.resize(0, 0);- this._backgroundControlMiddleRight.resize(0, 0);- return;- }-- const { startX: h_startX, startY: h_startY, endX: h_endX, endY: h_endY } = highlightSelection;-- const strokeOffset = DEFAULT_SELECTION_CONFIG.strokeWidth / 2;-- const topConfig = {- left: -strokeOffset,- top: -strokeOffset,- width: endX - startX + strokeOffset * 2,- height: h_startY - startY + strokeOffset,- };- if (topConfig.height < 0) {- topConfig.width = 0;- topConfig.height = 0;- }- this._backgroundControlTop.transformByState(topConfig);-- const middleLeftConfig = {- left: -strokeOffset,- top: h_startY - startY,- width: h_startX - startX + strokeOffset,- height: h_endY - h_startY,- };- if (middleLeftConfig.width < 0) {- middleLeftConfig.width = 0;- middleLeftConfig.height = 0;- }- this._backgroundControlMiddleLeft.transformByState(middleLeftConfig);-- const middleRightConfig = {- left: h_endX - startX - strokeOffset,- top: h_startY - startY,- width: endX - h_endX + strokeOffset * 2,- height: h_endY - h_startY,- };- if (middleRightConfig.width < 0) {- middleRightConfig.width = 0;- middleRightConfig.height = 0;- }- this._backgroundControlMiddleRight.transformByState(middleRightConfig);-- const middleBottomConfig = {- left: -strokeOffset,- top: h_endY - startY,- width: endX - startX + strokeOffset * 2,- height: endY - h_endY + strokeOffset,- };- if (middleBottomConfig.height < 0) {- middleBottomConfig.width = 0;- middleBottomConfig.height = 0;- }- this._backgroundControlBottom.transformByState(middleBottomConfig);- }-- /**- * Updated DragAndDrop and fill controls, inactive selections need to hide them- */- private _updateDragAndFill() {- const highlightSelection = this._selectionModel.highlightToSelection();-- if (!highlightSelection) {- this._selectionDragAndDrop.remove();-- this._fillControl.resize(0, 0);- this._selectionControlFill.remove();- }- }-}+import { Rect, Group } from '@univerjs/base-render';+import { Nullable, ISelection, ICellInfo } from '@univerjs/core';+import { Inject, Injector } from '@wendellhu/redi';+import { SelectionModel } from '../../Model/SelectionModel';+import { SelectionControlDragAndDrop } from './SelectionControlDragDrop';+import { SelectionControlFill } from './SelectionControlFill';+import { CanvasView } from '../../View';++// export enum DEFAULT_SELECTION_CONFIG {+// strokeColor = 'rgb(1,136,251)',+// backgroundColor = 'rgba(1,136,251, 0.1)',+// strokeWidth = 2,+// fillSideLength = 6,+// fillStrokeLength = 1,+// fillStrokeColor = 'rgb(255,255,255)',+// }+export const DEFAULT_SELECTION_CONFIG = {+ strokeColor: 'rgb(1,136,251)',+ backgroundColor: 'rgba(1,136,251, 0.1)',+ strokeWidth: 2,+ fillSideLength: 6,+ fillStrokeLength: 1,+ fillStrokeColor: 'rgb(255,255,255)',+};++export enum SELECTION_TYPE {+ NORMAL,+ ROW,+ COLUMN,+}++enum SELECTION_MANAGER_KEY {+ Selection = '__SpreadsheetSelectionShape__',+ top = '__SpreadsheetSelectionTopControl__',+ bottom = '__SpreadsheetSelectionBottomControl__',+ left = '__SpreadsheetSelectionShapeLeftControl__',+ right = '__SpreadsheetSelectionShapeRightControl__',+ backgroundTop = '__SpreadsheetSelectionBackgroundControlTop__',+ backgroundMiddleLeft = '__SpreadsheetSelectionBackgroundControlMiddleLeft__',+ backgroundMiddleRight = '__SpreadsheetSelectionBackgroundControlMiddleRight__',+ backgroundBottom = '__SpreadsheetSelectionBackgroundControlBottom__',+ fill = '__SpreadsheetSelectionFillControl__',+ lineMain = '__SpreadsheetDragLineMainControl__',+ lineContent = '__SpreadsheetDragLineContentControl__',+ line = '__SpreadsheetDragLineControl__',+}++/**+ * The main selection canvas component+ */+export class SelectionController {+ private _leftControl: Rect;++ private _rightControl: Rect;++ private _topControl: Rect;++ private _bottomControl: Rect;++ private _backgroundControlTop: Rect;++ private _backgroundControlBottom: Rect;++ private _backgroundControlMiddleLeft: Rect;++ private _backgroundControlMiddleRight: Rect;++ private _fillControl: Rect;++ private _selectionShape: Group;++ private _selectionModel: SelectionModel;++ private _selectionDragAndDrop: SelectionControlDragAndDrop;++ private _selectionControlFill: SelectionControlFill;++ constructor(private _zIndex: number, @Inject(Injector) private readonly _injector: Injector, @Inject(CanvasView) private readonly _canvasView: CanvasView) {+ this._initialize();+ }++ get zIndex() {+ return this._zIndex;+ }++ get leftControl() {+ return this._leftControl;+ }++ get rightControl() {+ return this._rightControl;+ }++ get topControl() {+ return this._topControl;+ }++ get bottomControl() {+ return this._bottomControl;+ }++ get fillControl() {+ return this._fillControl;+ }++ get backgroundControlTop() {+ return this._backgroundControlTop;+ }++ get backgroundControlBottom() {+ return this._backgroundControlBottom;+ }++ get backgroundControlMiddleLeft() {+ return this._backgroundControlMiddleLeft;+ }++ get backgroundControlMiddleRight() {+ return this._backgroundControlMiddleRight;+ }++ get selectionShape() {+ return this._selectionShape;+ }++ get model() {+ return this._selectionModel;+ }++ static create(injector: Injector, zIndex: number) {+ return injector.createInstance(this, zIndex);+ }++ // static fromJson(zIndex: number, newSelectionRange: ISelection) {+ // const control = SelectionController.create(zIndex);+ // control.update(newSelectionRange);+ // return control;+ // }++ /**+ * just handle the view+ *+ * inner update+ */+ _updateControl() {+ const { startX, startY, endX, endY } = this._selectionModel;++ this.leftControl.resize(undefined, endY - startY);+ this.rightControl.transformByState({+ height: endY - startY,+ left: endX - startX - DEFAULT_SELECTION_CONFIG.strokeWidth / 2,+ });+ this.topControl.resize(endX - startX + DEFAULT_SELECTION_CONFIG.strokeWidth);+ this.bottomControl.transformByState({+ width: endX - startX + DEFAULT_SELECTION_CONFIG.strokeWidth,+ top: endY - startY - DEFAULT_SELECTION_CONFIG.strokeWidth / 2,+ });++ this.fillControl.translate(endX - startX - DEFAULT_SELECTION_CONFIG.fillSideLength / 2, endY - startY - DEFAULT_SELECTION_CONFIG.fillSideLength / 2);++ this._updateBackgroundControl();+ this._updateDragAndFill();++ this.selectionShape.show();+ this.selectionShape.translate(startX, startY);++ this.selectionShape.makeDirty(true);+ }++ update(newSelectionRange: ISelection, highlight: Nullable<ICellInfo>) {+ this._selectionModel.setValue(newSelectionRange, highlight);+ this._updateControl();+ }++ // /**+ // *When switching to the current sheet+ // *+ // * 1. Reinitialize the rendering component+ // * 2. Calculate the position based on the current skeleton+ // * 3. Update data+ // * 4. Trigger rendering+ // */+ // render() {+ // this._initialize();++ // let cellInfo = null;+ // const main = this._manager.getMainComponent();+ // const curCellRange = this._selectionModel.currentCell;++ // if (curCellRange) {+ // cellInfo = main.getCellByIndex(curCellRange.row, curCellRange.column);+ // }++ // const { startRow: finalStartRow, startColumn: finalStartColumn, endRow: finalEndRow, endColumn: finalEndColumn } = this._selectionModel;+ // const startCell = main.getNoMergeCellPositionByIndex(finalStartRow, finalStartColumn);+ // const endCell = main.getNoMergeCellPositionByIndex(finalEndRow, finalEndColumn);++ // this._manager.updateSelectionValue(+ // this,+ // {+ // startColumn: finalStartColumn,+ // startRow: finalStartRow,+ // endColumn: finalEndColumn,+ // endRow: finalEndRow,+ // startY: startCell?.startY || 0,+ // endY: endCell?.endY || 0,+ // startX: startCell?.startX || 0,+ // endX: endCell?.endX || 0,+ // },+ // cellInfo+ // );++ // this._updateControl();+ // }++ clearHighlight() {+ this._selectionModel.clearCurrentCell();+ this._updateControl();+ }++ dispose() {+ this._leftControl?.dispose();+ this._rightControl?.dispose();+ this._topControl?.dispose();+ this._bottomControl?.dispose();+ this._backgroundControlTop?.dispose();+ this._backgroundControlMiddleLeft?.dispose();+ this._backgroundControlMiddleRight?.dispose();+ this._backgroundControlBottom?.dispose();+ this._fillControl?.dispose();+ this._selectionShape?.dispose();++ this._selectionDragAndDrop.dispose();+ }++ /**+ * Get the cell information of the current selection, considering the case of merging cells+ */+ getCurrentCellInfo(): Nullable<ISelection> {+ const currentCell = this.model.currentCell;++ if (currentCell) {+ let currentRangeData;++ if (currentCell.isMerged) {+ const mergeInfo = currentCell.mergeInfo;++ currentRangeData = {+ startRow: mergeInfo.startRow,+ endRow: mergeInfo.endRow,+ startColumn: mergeInfo.startColumn,+ endColumn: mergeInfo.endColumn,+ startX: mergeInfo.startX,+ endX: mergeInfo.endX,+ startY: mergeInfo.startY,+ endY: mergeInfo.endY,+ };+ } else {+ const { row, column, startX, endX, startY, endY } = currentCell;+ currentRangeData = {+ startRow: row,+ endRow: row,+ startColumn: column,+ endColumn: column,+ startX,+ endX,+ startY,+ endY,+ };+ }++ return currentRangeData;+ }+ }++ private _initialize() {+ this._selectionModel = this._injector.createInstance(SelectionModel, SELECTION_TYPE.NORMAL);+ const zIndex = this._zIndex;+ this._leftControl = new Rect(SELECTION_MANAGER_KEY.left + zIndex, {+ top: 0,+ left: -DEFAULT_SELECTION_CONFIG.strokeWidth / 2,+ width: DEFAULT_SELECTION_CONFIG.strokeWidth,+ fill: DEFAULT_SELECTION_CONFIG.strokeColor,+ zIndex,+ });+ this._rightControl = new Rect(SELECTION_MANAGER_KEY.right + zIndex, {+ width: DEFAULT_SELECTION_CONFIG.strokeWidth,+ fill: DEFAULT_SELECTION_CONFIG.strokeColor,+ zIndex,+ });+ this._topControl = new Rect(SELECTION_MANAGER_KEY.top + zIndex, {+ top: -DEFAULT_SELECTION_CONFIG.strokeWidth / 2,+ left: -DEFAULT_SELECTION_CONFIG.strokeWidth / 2,+ height: DEFAULT_SELECTION_CONFIG.strokeWidth,+ fill: DEFAULT_SELECTION_CONFIG.strokeColor,+ zIndex,+ });+ this._bottomControl = new Rect(SELECTION_MANAGER_KEY.bottom + zIndex, {+ height: DEFAULT_SELECTION_CONFIG.strokeWidth,+ fill: DEFAULT_SELECTION_CONFIG.strokeColor,+ left: -DEFAULT_SELECTION_CONFIG.strokeWidth / 2,+ zIndex,+ });+ this._backgroundControlTop = new Rect(SELECTION_MANAGER_KEY.backgroundTop + zIndex, {+ fill: DEFAULT_SELECTION_CONFIG.backgroundColor,+ zIndex: zIndex - 1,+ evented: false,+ });+ this._backgroundControlBottom = new Rect(SELECTION_MANAGER_KEY.backgroundBottom + zIndex, {+ fill: DEFAULT_SELECTION_CONFIG.backgroundColor,+ zIndex: zIndex - 1,+ evented: false,+ });+ this._backgroundControlMiddleLeft = new Rect(SELECTION_MANAGER_KEY.backgroundMiddleLeft + zIndex, {+ fill: DEFAULT_SELECTION_CONFIG.backgroundColor,+ zIndex: zIndex - 1,+ evented: false,+ });+ this._backgroundControlMiddleRight = new Rect(SELECTION_MANAGER_KEY.backgroundMiddleRight + zIndex, {+ fill: DEFAULT_SELECTION_CONFIG.backgroundColor,+ zIndex: zIndex - 1,+ evented: false,+ });+ const fillSideLength = DEFAULT_SELECTION_CONFIG.fillSideLength - DEFAULT_SELECTION_CONFIG.fillStrokeLength;+ this._fillControl = new Rect(SELECTION_MANAGER_KEY.fill + zIndex, {+ width: fillSideLength,+ height: fillSideLength,+ fill: DEFAULT_SELECTION_CONFIG.strokeColor,+ strokeWidth: DEFAULT_SELECTION_CONFIG.fillStrokeLength,+ stroke: DEFAULT_SELECTION_CONFIG.fillStrokeColor,+ zIndex: zIndex + 1,+ });+ this._selectionShape = new Group(+ SELECTION_MANAGER_KEY.Selection + zIndex,+ this._fillControl,+ this._leftControl,+ this._rightControl,+ this._topControl,+ this._bottomControl,+ this._backgroundControlTop,+ this._backgroundControlMiddleLeft,+ this._backgroundControlMiddleRight,+ this._backgroundControlBottom+ );++ this._selectionShape.hide();++ this._selectionShape.evented = false;++ this._selectionShape.zIndex = zIndex;++ this._selectionDragAndDrop = SelectionControlDragAndDrop.create(this._injector, this._zIndex, this._selectionModel, {+ leftControl: this.leftControl,+ rightControl: this.rightControl,+ topControl: this.topControl,+ bottomControl: this.bottomControl,+ fillControl: this.fillControl,+ update: this.update.bind(this),+ });++ this._selectionControlFill = SelectionControlFill.create(this._injector, {+ fillControl: this.fillControl,+ });++ this._canvasView.getSheetView().getScene().addObject(this._selectionShape);+ }++ private _updateBackgroundControl() {+ const {+ startColumn,+ startRow,+ endColumn,+ endRow,++ startX,+ startY,+ endX,+ endY,+ } = this._selectionModel;++ const highlightSelection = this._selectionModel.highlightToSelection();++ if (!highlightSelection) {+ this._backgroundControlTop.resize(endX - startX, endY - startY);+ this._backgroundControlBottom.resize(0, 0);+ this._backgroundControlMiddleLeft.resize(0, 0);+ this._backgroundControlMiddleRight.resize(0, 0);+ return;+ }++ const { startX: h_startX, startY: h_startY, endX: h_endX, endY: h_endY } = highlightSelection;++ const strokeOffset = DEFAULT_SELECTION_CONFIG.strokeWidth / 2;++ const topConfig = {+ left: -strokeOffset,+ top: -strokeOffset,+ width: endX - startX + strokeOffset * 2,+ height: h_startY - startY + strokeOffset,+ };+ if (topConfig.height < 0) {+ topConfig.width = 0;+ topConfig.height = 0;+ }+ this._backgroundControlTop.transformByState(topConfig);++ const middleLeftConfig = {+ left: -strokeOffset,+ top: h_startY - startY,+ width: h_startX - startX + strokeOffset,+ height: h_endY - h_startY,+ };+ if (middleLeftConfig.width < 0) {+ middleLeftConfig.width = 0;+ middleLeftConfig.height = 0;+ }+ this._backgroundControlMiddleLeft.transformByState(middleLeftConfig);++ const middleRightConfig = {+ left: h_endX - startX - strokeOffset,+ top: h_startY - startY,+ width: endX - h_endX + strokeOffset * 2,+ height: h_endY - h_startY,+ };+ if (middleRightConfig.width < 0) {+ middleRightConfig.width = 0;+ middleRightConfig.height = 0;+ }+ this._backgroundControlMiddleRight.transformByState(middleRightConfig);++ const middleBottomConfig = {+ left: -strokeOffset,+ top: h_endY - startY,+ width: endX - startX + strokeOffset * 2,+ height: endY - h_endY + strokeOffset,+ };+ if (middleBottomConfig.height < 0) {+ middleBottomConfig.width = 0;+ middleBottomConfig.height = 0;+ }+ this._backgroundControlBottom.transformByState(middleBottomConfig);+ }++ /**+ * Updated DragAndDrop and fill controls, inactive selections need to hide them+ */+ private _updateDragAndFill() {+ const highlightSelection = this._selectionModel.highlightToSelection();++ if (!highlightSelection) {+ this._selectionDragAndDrop.remove();++ this._fillControl.resize(0, 0);+ this._selectionControlFill.remove();+ }+ }+}diff --git a/packages/base-sheets/src/Controller/Selection/SelectionManager.ts b/packages/base-sheets/src/Controller/Selection/SelectionManager.tsindex 81b4a4157a..3d2232072a 100644--- a/packages/base-sheets/src/Controller/Selection/SelectionManager.ts+++ b/packages/base-sheets/src/Controller/Selection/SelectionManager.ts@@ -1,1063 +1,1070 @@-import { IMouseEvent, IPointerEvent, Rect, Spreadsheet, SpreadsheetColumnTitle, SpreadsheetRowTitle, ScrollTimer } from '@univerjs/base-render';-import {- Nullable,- Observer,- Worksheet,- ISelection,- makeCellToSelection,- IRangeData,- RangeList,- Range,- IRangeCellData,- ICellInfo,- Command,- Direction,- ActionOperation,- ISelectionData,- DEFAULT_SELECTION,- DEFAULT_CELL,- IGridRange,-} from '@univerjs/core';-import { ACTION_NAMES, ISelectionsConfig } from '../../Basics';-import { ISelectionModelValue, ISetSelectionValueActionData, SetSelectionValueAction } from '../../Model/Action/SetSelectionValueAction';-import { SelectionModel } from '../../Model/SelectionModel';-import { SheetPlugin } from '../../SheetPlugin';-import { SheetView } from '../../View/Views/SheetView';-import { ColumnTitleController } from './ColumnTitleController';-import { DragLineController } from './DragLineController';-import { RowTitleController } from './RowTitleController';-import { SelectionControl, SELECTION_TYPE } from './SelectionController';--/**- * TODO 注册selection拦截,可能在有公式ArrayObject时,fx公式栏显示不同- *- * SelectionManager 维护model数据list,action也是修改这一层数据,obs监听到数据变动后,自动刷新(control仍然可以持有数据)- */-export class SelectionManager {- hasSelection: boolean = false;-- private _mainComponent: Spreadsheet;-- private _rowComponent: SpreadsheetRowTitle;-- private _columnComponent: SpreadsheetColumnTitle;-- private _leftTopComponent: Rect;-- private _moveObserver: Nullable<Observer<IPointerEvent | IMouseEvent>>;-- private _upObserver: Nullable<Observer<IPointerEvent | IMouseEvent>>;-- private _selectionControls: SelectionControl[] = []; // sheetID:Controls-- private _selectionModels = new Map<string, SelectionModel[]>(); // sheetID:Models-- private _plugin: SheetPlugin;-- private _startSelectionRange: ISelection;-- private _startOffsetX: number = 0;-- private _startOffsetY: number = 0;-- private _worksheet: Nullable<Worksheet>;-- private _columnTitleControl: ColumnTitleController;-- private _rowTitleControl: RowTitleController;-- private _dragLineControl: DragLineController;-- private _previousSelection: ISelectionData;-- constructor(private _sheetView: SheetView) {- this._plugin = this._sheetView.getPlugin() as SheetPlugin;- this._initialize();- this._initializeObserver();- }-- getSheetView() {- return this._sheetView;- }-- getScene() {- return this._sheetView.getScene();- }-- getContext() {- return this._sheetView.getContext();- }-- getMainComponent() {- return this._mainComponent;- }-- updateToSheet(worksheet: Worksheet) {- this._worksheet = worksheet;- const worksheetId = this.getWorksheetId();- if (worksheetId) {- const models = this._selectionModels.get(worksheetId);- if (!models) {- this._selectionModels.set(worksheetId, []);- }- }- }-- getCurrentControls() {- return this._selectionControls;- }-- getCurrentControl() {- const controls = this.getCurrentControls();- if (controls && controls.length > 0) {- for (const control of controls) {- const currentCell = control.model.currentCell;- if (currentCell) {- return control;- }- }- }- }-- getCurrentModels() {- const worksheetId = this.getWorksheetId();- if (!worksheetId) {- return;- }-- const models = this._selectionModels.get(worksheetId);-- if (!models) {- this._selectionModels.set(worksheetId, []);- }- return this._selectionModels.get(worksheetId);- }-- getCurrentCellModel(): Nullable<ICellInfo> {- const models = this.getCurrentModels();- if (models && models.length > 0) {- for (const model of models) {- const currentCell = model.currentCell;- if (currentCell) {- return currentCell;- }- }- }- }-- getCurrentModel(): Nullable<SelectionModel> {- const models = this.getCurrentModels();- if (models && models.length > 0) {- for (const model of models) {- const currentCell = model.currentCell;- if (currentCell) {- return model;- }- }- }- }-- getCurrentModelsValue(): ISelectionModelValue[] {- const models = this.getCurrentModels();- if (!models) {- return [];- }- const selectionModelsValue = [];- for (let model of models) {- selectionModelsValue.push(model.getValue());- }- return selectionModelsValue;- }-- /**- * Renders all controls of the currently active sheet- * @returns- */- renderCurrentControls(command: boolean = true, models?: SelectionModel[]) {- const worksheetId = this.getWorksheetId();- if (worksheetId) {- if (this._selectionControls) {- // clear old controls- for (let control of this._selectionControls) {- control.dispose();- }- }-- // render current control- const selectionModels = models || this._selectionModels.get(worksheetId);- this._selectionControls = [];- selectionModels?.forEach((model) => {- const curCellRange = model.currentCell;- const main = this._mainComponent;-- const control = SelectionControl.create(this, this._selectionControls.length);-- let cellInfo = null;- if (curCellRange) {- cellInfo = main.getCellByIndex(curCellRange.row, curCellRange.column);- }-- const { startRow, startColumn, endRow, endColumn } = model;- const startCell = main.getNoMergeCellPositionByIndex(startRow, startColumn);- const endCell = main.getNoMergeCellPositionByIndex(endRow, endColumn);-- // update control model and view- control.update(- {- startColumn,- startRow,- endColumn,- endRow,- startY: startCell?.startY || 0,- endY: endCell?.endY || 0,- startX: startCell?.startX || 0,- endX: endCell?.endX || 0,- },- cellInfo- );- this._selectionControls.push(control);- });-- command && this.setSelectionModel();- }- }-- getPlugin() {- return this._plugin;- }-- getWorksheetId() {- return this._worksheet?.getSheetId();- }-- /**- * add a selection- * @param selectionRange- * @param curCellRange- * @returns- */- addControlToCurrentByRangeData(selectionRange: IRangeData, curCellRange: Nullable<IRangeCellData>, command: boolean = true) {- const currentControls = this.getCurrentControls();- if (!currentControls) {- return;- }- const main = this._mainComponent;-- const control = SelectionControl.create(this, currentControls.length);-- let cellInfo = null;- if (curCellRange) {- cellInfo = main.getCellByIndex(curCellRange.row, curCellRange.column);- }-- const { startRow, startColumn, endRow, endColumn } = selectionRange;- const startCell = main.getNoMergeCellPositionByIndex(startRow, startColumn);- const endCell = main.getNoMergeCellPositionByIndex(endRow, endColumn);-- // update control- control.update(- {- startColumn,- startRow,- endColumn,- endRow,- startY: startCell?.startY || 0,- endY: endCell?.endY || 0,- startX: startCell?.startX || 0,- endX: endCell?.endX || 0,- },- cellInfo- );-- currentControls.push(control);-- // this.setSelectionModel();-- if (command) {- this.setSelectionModel();- } else {- const models = this._selectionControls.map((control) => control.model.getValue());- return models;- }- }-- clearSelectionControls() {- let curControls = this.getCurrentControls();-- if (curControls.length > 0) {- for (let control of curControls) {- control.dispose();- }-- curControls.length = 0; // clear currentSelectionControls- }- }-- /**- * update all current controls data in model- */- setSelectionModel(models?: ISelectionModelValue[]) {- if (!this._worksheet) return;-- // get models from current control- if (!models) {- models = this._selectionControls.map((control) => control.model.getValue());- }-- const workbook = this._worksheet.getContext().getWorkBook();- const commandManager = workbook.getCommandManager();-- let action: ISetSelectionValueActionData = {- sheetId: this._worksheet.getSheetId(),- actionName: SetSelectionValueAction.NAME,- selections: models,- };-- action = ActionOperation.make<ISetSelectionValueActionData>(action).removeUndo().getAction();-- const command = new Command(- {- WorkBookUnit: workbook,- },- action- );- commandManager.invoke(command);- }-- /**- * update current control in model- */- updateSelectionModel(selection: ISelection, cell: Nullable<ICellInfo>, index: number) {- const worksheetId = this.getWorksheetId();-- if (!this._worksheet || !worksheetId) return;-- // Collect constituency data for the entire current sheet- const selectionModels = this._selectionModels.get(worksheetId);- const selectionModelsValue: ISelectionModelValue[] = [];- selectionModels?.forEach((model, i) => {- if (i === index) {- selectionModelsValue.push({ selection, cell });- } else {- selectionModelsValue.push(model.getValue());- }- });-- const workbook = this._worksheet.getContext().getWorkBook();- const commandManager = workbook.getCommandManager();-- let action: ISetSelectionValueActionData = {- sheetId: this._worksheet.getSheetId(),- actionName: ACTION_NAMES.SET_SELECTION_VALUE_ACTION,- selections: selectionModelsValue,- };-- action = ActionOperation.make<ISetSelectionValueActionData>(action).removeUndo().getAction();-- const command = new Command(- {- WorkBookUnit: workbook,- },- action- );- commandManager.invoke(command);- }-- setModels(selections: ISelectionModelValue[]) {- const worksheetId = this.getWorksheetId();- if (!worksheetId) {- return;- }-- const models = selections.map(({ selection, cell }) => {- const model = new SelectionModel(SELECTION_TYPE.NORMAL, this._plugin);- model.setValue(selection, cell);- return model;- });-- this._selectionModels.set(worksheetId, models);- }-- // recreateControlsByRangeData() { }-- /**- * Move the selection according to different directions, usually used for the shortcut key operation of ↑ ↓ ← →- * @param direction- * @returns- */- move(direction: Direction): void {- const currentCell = this.getCurrentCellModel();-- if (!currentCell) return;-- let { startRow: mergeStartRow, startColumn: mergeStartColumn, endRow: mergeEndRow, endColumn: mergeEndColumn } = currentCell.mergeInfo;-- let { row, column } = currentCell;- const rowCount = this._worksheet?.getRowCount() || 1000;- const columnCount = this._worksheet?.getColumnCount() || 50;- switch (direction) {- case Direction.TOP:- if (currentCell.isMerged || currentCell.isMergedMainCell) {- row = --mergeStartRow;- } else {- row--;- }- if (row < 0) {- row = 0;- }- break;- case Direction.BOTTOM:- if (currentCell.isMerged || currentCell.isMergedMainCell) {- row = ++mergeEndRow;- } else {- row++;- }-- if (row > rowCount) {- row = rowCount;- }- break;- case Direction.LEFT:- if (currentCell.isMerged || currentCell.isMergedMainCell) {- column = --mergeStartColumn;- } else {- column--;- }-- if (column < 0) {- column = 0;- }- break;- case Direction.RIGHT:- if (currentCell.isMerged || currentCell.isMergedMainCell) {- column = ++mergeEndColumn;- } else {- column++;- }-- if (column > columnCount) {- column = columnCount;- }- break;-- default:- break;- }-- const cellInfo = this._mainComponent.getCellByIndex(row, column);-- const selectionData = makeCellToSelection(cellInfo);-- if (!selectionData) return;-- const { startRow, endRow, startColumn, endColumn } = selectionData;-- const main = this._mainComponent;- const newBounding = main.getSelectionBounding(startRow, startColumn, endRow, endColumn);-- if (!newBounding) {- return;- }-- const { startRow: finalStartRow, startColumn: finalStartColumn, endRow: finalEndRow, endColumn: finalEndColumn } = newBounding;-- let rangeData: IRangeData = {- startRow: finalStartRow,- endRow: finalEndRow,- startColumn: finalStartColumn,- endColumn: finalEndColumn,- };- let currentCellData: IRangeCellData = {- row: startRow,- column: startColumn,- };-- this.clearSelectionControls();- this.addControlToCurrentByRangeData(rangeData, currentCellData);- this.updatePreviousSelection();- }-- setCurrentCell(gridData: IGridRange): void {- const { rangeData: girdRangeData, sheetId } = gridData;- const { startRow: row, startColumn: column } = girdRangeData;-- // active new target sheet- const currentSheetId = this.getWorksheetId();- if (sheetId !== currentSheetId) {- const sheetIndex = this._worksheet?.getIndex();- if (sheetIndex == null) return;- this._plugin.getWorkbook().activateSheetByIndex(sheetIndex);- }-- const cellInfo = this._mainComponent.getCellByIndex(row, column);-- const selectionData = makeCellToSelection(cellInfo);-- if (!selectionData) return;-- const { startRow, endRow, startColumn, endColumn } = selectionData;-- const main = this._mainComponent;- const newBounding = main.getSelectionBounding(startRow, startColumn, endRow, endColumn);-- if (!newBounding) {- return;- }-- const { startRow: finalStartRow, startColumn: finalStartColumn, endRow: finalEndRow, endColumn: finalEndColumn } = newBounding;-- let rangeData: IRangeData = {- startRow: finalStartRow,- endRow: finalEndRow,- startColumn: finalStartColumn,- endColumn: finalEndColumn,- };- let currentCellData: IRangeCellData = {- row: startRow,- column: startColumn,- };-- this.clearSelectionControls();- this.addControlToCurrentByRangeData(rangeData, currentCellData);- this.updatePreviousSelection();- }-- /**- * 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- * @param moveEvt- * @param selectionControl- * @returns- */- moving(moveEvt: IPointerEvent | IMouseEvent, selectionControl: Nullable<SelectionControl>, setModel: boolean = false) {- // console.log('moving');- const main = this._mainComponent;- const { offsetX: moveOffsetX, offsetY: moveOffsetY, clientX, clientY } = moveEvt;- const { startRow, startColumn, endRow, endColumn } = this._startSelectionRange;-- // moveOffsetX and moveOffsetY is relative to the top left corner of the canvas- const scrollXY = main.getAncestorScrollXY(this._startOffsetX, this._startOffsetY);- const moveCellInfo = main.calculateCellIndexByPosition(moveOffsetX, moveOffsetY, scrollXY); // scrollXY is canvas content scrolling- const moveActualSelection = makeCellToSelection(moveCellInfo);-- if (!moveActualSelection) {- return false;- }- const { startRow: moveStartRow, startColumn: moveStartColumn, endColumn: moveEndColumn, endRow: moveEndRow } = moveActualSelection;-- const newStartRow = Math.min(moveStartRow, startRow);- const newStartColumn = Math.min(moveStartColumn, startColumn);- const newEndRow = Math.max(moveEndRow, endRow);- const newEndColumn = Math.max(moveEndColumn, endColumn);- const newBounding = main.getSelectionBounding(newStartRow, newStartColumn, newEndRow, newEndColumn);-- if (!newBounding) {- return false;- }- const { startRow: finalStartRow, startColumn: finalStartColumn, endRow: finalEndRow, endColumn: finalEndColumn } = newBounding;-- const startCell = main.getNoMergeCellPositionByIndex(finalStartRow, finalStartColumn);- const endCell = main.getNoMergeCellPositionByIndex(finalEndRow, finalEndColumn);-- const newSelectionRange: ISelection = {- 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- const { startRow: oldStartRow, endRow: oldEndRow, startColumn: oldStartColumn, endColumn: oldEndColumn } = selectionControl?.model || DEFAULT_SELECTION;- const { row: oldRow, column: oldColumn } = selectionControl?.model.currentCell || DEFAULT_CELL;-- if (oldStartColumn !== finalStartColumn || oldStartRow !== finalStartRow || oldEndColumn !== finalEndColumn || oldEndRow !== finalEndRow) {- selectionControl && selectionControl.update(newSelectionRange);- selectionControl && this._plugin.getObserver('onChangeSelectionObserver')?.notifyObservers(selectionControl);- }-- if (setModel) {- if (!this._previousSelection) {- this.setSelectionModel();- } else {- // If it is different from the range when clicked, you need to update the model- const {- startRow: mouseDownStartRow,- endRow: mouseDownEndRow,- startColumn: mouseDownStartColumn,- endColumn: mouseDownEndColumn,- } = (this._previousSelection.selection as IRangeData) || DEFAULT_SELECTION;- const { row: mouseDownRow, column: mouseDownColumn } = (this._previousSelection.cell as IRangeCellData) || DEFAULT_CELL;- if (- mouseDownStartColumn !== finalStartColumn ||- mouseDownStartRow !== finalStartRow ||- mouseDownEndColumn !== finalEndColumn ||- mouseDownEndRow !== finalEndRow ||- mouseDownRow !== oldRow ||- mouseDownColumn !== oldColumn- ) {- this.setSelectionModel();- }- }-- this.updatePreviousSelection();- }- }-- /**- * pointer up event- * @param moveEvt- * @param selectionControl- * @returns- */- up(upEvt: IPointerEvent | IMouseEvent, selectionControl: Nullable<SelectionControl>) {- // update model-- this.moving(upEvt, selectionControl, true);- }-- updatePreviousSelection() {- let selectionControl: Nullable<SelectionControl> = this.getCurrentControl();-- if (!selectionControl) return;-- // this.setSelectionModel();- const { startRow, endRow, startColumn, endColumn } = selectionControl.model;- const { row, column } = selectionControl.model.currentCell || DEFAULT_CELL;- this._previousSelection = {- selection: {- startRow,- endRow,- startColumn,- endColumn,- },- cell: {- row,- column,- },- };- }-- /**- * Get all range data of the current selection- * @returns- */- getActiveRangeListData(): Nullable<IRangeData[]> {- const models = this.getCurrentModels();- if (models && models.length > 0) {- const selections = models?.map((model: SelectionModel) => ({- startRow: model.startRow,- startColumn: model.startColumn,- endRow: model.endRow,- endColumn: model.endColumn,- }));-- return selections;- }- }-- /**- * 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- */- getActiveRangeList(): Nullable<RangeList> {- const rangeListData = this.getActiveRangeListData();- return rangeListData && this._worksheet?.getRangeList(rangeListData);- }-- /**- * Get the range of the currently active cell- * @returns- */- getActiveRangeData(): Nullable<IRangeData> {- const models = this.getCurrentModels();- if (models && models.length > 0) {- for (const model of models) {- if (model.currentCell) {- return {- startRow: model.startRow,- startColumn: model.startColumn,- endRow: model.endRow,- endColumn: model.endColumn,- };- }- }- }- }-- /**- * 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.- * @returns- */- getActiveRange(): Nullable<Range> {- const rangeData = this.getActiveRangeData();- return rangeData && this._worksheet?.getRange(rangeData);- }-- /**- * get active selection control- * @returns- */- getCurrentCellData(): Nullable<IRangeData> {- const models = this.getCurrentModels();- if (models && models.length > 0) {- for (const model of models) {- const currentCell = model.currentCell;- if (currentCell) {- return {- startRow: currentCell.row,- startColumn: currentCell.column,- endRow: currentCell.row,- endColumn: currentCell.column,- };- }- }- }- }-- /**- * get active selection control- * @returns- */- getCurrentCell(): Nullable<Range> {- const rangeData = this.getCurrentCellData();- return rangeData && this._worksheet?.getRange(rangeData);- }-- getDragLineControl() {- return this._dragLineControl;- }-- private _initialize() {- this._mainComponent = this._sheetView.getSpreadsheet();- this._rowComponent = this._sheetView.getSpreadsheetRowTitle();- this._columnComponent = this._sheetView.getSpreadsheetColumnTitle();- this._leftTopComponent = this._sheetView.getSpreadsheetLeftTopPlaceholder();-- this._mainEventInitial();-- this._rowEventInitial();-- this._columnEventInitial();-- this._leftTopEventInitial();-- this._worksheet = this.getContext().getWorkBook().getActiveSheet();-- this._initModels();-- this._dragLineControl = new DragLineController(this);-- this._columnTitleControl = new ColumnTitleController(this);-- this._rowTitleControl = new RowTitleController(this);- }-- private _mainEventInitial() {- const main = this._mainComponent;- main.onPointerDownObserver.add((evt: IPointerEvent | IMouseEvent) => {- const { offsetX: evtOffsetX, offsetY: evtOffsetY } = evt;- this._startOffsetX = evtOffsetX;- this._startOffsetY = evtOffsetY;- const scrollXY = main.getAncestorScrollXY(this._startOffsetX, this._startOffsetY);- const cellInfo = main.calculateCellIndexByPosition(evtOffsetX, evtOffsetY, scrollXY);- const actualSelection = makeCellToSelection(cellInfo);- if (!actualSelection || !this._worksheet) {- return false;- }-- const { startRow, startColumn, endColumn, endRow, startY, endY, startX, endX } = actualSelection;-- const startSelectionRange = {- startColumn,- startRow,- endColumn,- endRow,- startY,- endY,- startX,- endX,- };-- this._startSelectionRange = startSelectionRange;-- let selectionControl: Nullable<SelectionControl> = this.getCurrentControl();-- let curControls = this.getCurrentControls();-- if (!curControls) {- return false;- }-- for (let control of curControls) {- // right click- if (evt.button === 2 && control.model.isInclude(startSelectionRange)) {- selectionControl = control;- return;- }- // 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) {- for (let control of curControls) {- control.dispose();- }-- curControls.length = 0; // clear currentSelectionControls- }-- const currentCell = selectionControl && selectionControl.model.currentCell;-- if (selectionControl && evt.shiftKey && currentCell) {- const { row, column } = currentCell;-- // TODO startCell position calculate error- const startCell = main.getNoMergeCellPositionByIndex(row, column);- const endCell = main.getNoMergeCellPositionByIndex(endRow, endColumn);-- const newSelectionRange = {- startColumn: column,- startRow: row,- endColumn: startSelectionRange.startColumn,- endRow: startSelectionRange.startRow,- startY: startCell?.startY || 0,- endY: endCell?.endY || 0,- startX: startCell?.startX || 0,- endX: endCell?.endX || 0,- };- selectionControl.update(newSelectionRange, currentCell);- } else {- selectionControl = SelectionControl.create(this, curControls.length);- selectionControl.update(startSelectionRange, cellInfo);- curControls.push(selectionControl);- }-- this.hasSelection = true;-- const scene = this.getScene();-- scene.disableEvent();-- const scrollTimer = ScrollTimer.create(this.getScene());- scrollTimer.startScroll(evtOffsetX, evtOffsetY);-- // In edit mode, click other cells, you need to update the current model, otherwise when updating the cell value, the old active range will be redrawn- const currentModel = selectionControl.getCurrentCellInfo();- if (!this._previousSelection) {- // this.setSelectionModel();- const models = this._selectionControls.map((control) => control.model.getValue());- this.setModels(models);- } else {- // If it is different from the range when clicked, you need to update the model- const {- startRow: mouseDownStartRow,- endRow: mouseDownEndRow,- startColumn: mouseDownStartColumn,- endColumn: mouseDownEndColumn,- } = (this._previousSelection.selection as IRangeData) || DEFAULT_SELECTION;- const { row: mouseDownRow, column: mouseDownColumn } = (this._previousSelection.cell as IRangeCellData) || DEFAULT_CELL;- if (- mouseDownStartColumn !== currentModel?.startColumn ||- mouseDownStartRow !== currentModel?.startRow ||- mouseDownEndColumn !== currentModel?.endColumn ||- mouseDownEndRow !== currentModel?.endRow ||- mouseDownRow !== currentModel?.startRow ||- mouseDownColumn !== currentModel?.startColumn- ) {- // this.setSelectionModel();- const models = this._selectionControls.map((control) => control.model.getValue());- this.setModels(models);- }- }-- // Notification toolbar updates button state and value- this._plugin.getObserver('onChangeSelectionObserver')?.notifyObservers(selectionControl);-- this._moveObserver = scene.onPointerMoveObserver.add((moveEvt: IPointerEvent | IMouseEvent) => {- this.moving(moveEvt, selectionControl);- const { offsetX: moveOffsetX, offsetY: moveOffsetY } = moveEvt;-- scrollTimer.scrolling(moveOffsetX, moveOffsetY, () => {- this.moving(moveEvt, selectionControl);- });- });-- this._upObserver = scene.onPointerUpObserver.add((upEvt: IPointerEvent | IMouseEvent) => {- this.up(upEvt, selectionControl);- scene.onPointerMoveObserver.remove(this._moveObserver);- scene.onPointerUpObserver.remove(this._upObserver);- scene.enableEvent();-- scrollTimer.stopScroll();- });-- // document.addEventListener('pointerup', () => {- // this.up();- // scene.onPointerMoveObserver.remove(this._moveObserver);- // scene.onPointerUpObserver.remove(this._upObserver);- // scene.enableEvent();-- // scrollTimer.stopScroll();- // });- });- }-- private _rowEventInitial() {- const row = this._rowComponent;- row.onPointerEnterObserver.add((evt: IPointerEvent | IMouseEvent) => {- // this._rowTitleControl.highlightRowTitle(evt);- });- }-- private _columnEventInitial() {- const column = this._columnComponent;- column.onPointerEnterObserver.add((evt: IPointerEvent | IMouseEvent) => {- // this._columnTitleControl.highlightColumnTitle(evt);- });- }-- private _leftTopEventInitial() {- const leftTop = this._leftTopComponent;- leftTop.onPointerDownObserver.add((evt: IPointerEvent | IMouseEvent) => {- // console.log('leftTop_moveObserver', evt);- });- }-- /**- * Initialize selection model based on user configuration- * @param selections- */- private _initModels() {- const selections: ISelectionsConfig = this._plugin.getConfig().selections;-- Object.keys(selections).forEach((worksheetId) => {- const selectionsList = selections[worksheetId];- const currentModels: SelectionModel[] = [];-- selectionsList.forEach((selectionConfig) => {- const { startColumn, startRow, endColumn, endRow } = selectionConfig.selection;- const cell = selectionConfig.cell;-- const model = new SelectionModel(SELECTION_TYPE.NORMAL, this._plugin);-- const cellInfo = cell- ? {- row: cell.row,- column: cell.column,- isMerged: false,- isMergedMainCell: false,- startY: 0,- endY: 0,- startX: 0,- endX: 0,- mergeInfo: {- startColumn,- startRow,- endColumn,- endRow,- startY: 0,- endY: 0,- startX: 0,- endX: 0,- },- }- : null;-- // Only update data, not render- model.setValue(- {- startColumn,- startRow,- endColumn,- endRow,- startY: 0,- endY: 0,- startX: 0,- endX: 0,- },- cellInfo- );- currentModels.push(model);- });-- this._selectionModels.set(worksheetId, currentModels);- });- }-- /**- * Initialize selection based on user configuration- * @param selections- */- private _initControls() {- const selections: ISelectionsConfig = this._plugin.getConfig().selections;- Object.keys(selections).forEach((worksheetId) => {- const selectionsList = selections[worksheetId];- const currentControls: SelectionControl[] = [];-- selectionsList.forEach((selectionConfig) => {- const selectionRange = selectionConfig.selection;- const curCellRange = selectionConfig.cell;- const main = this._mainComponent;-- const control = SelectionControl.create(this, currentControls.length);-- let cellInfo = null;- if (curCellRange) {- cellInfo = main.getCellByIndex(curCellRange.row, curCellRange.column);- }-- const { startRow: finalStartRow, startColumn: finalStartColumn, endRow: finalEndRow, endColumn: finalEndColumn } = selectionRange;- const startCell = main.getNoMergeCellPositionByIndex(finalStartRow, finalStartColumn);- const endCell = main.getNoMergeCellPositionByIndex(finalEndRow, finalEndColumn);-- // Only update data, not render- control.model.setValue(- {- startColumn: finalStartColumn,- startRow: finalStartRow,- endColumn: finalEndColumn,- endRow: finalEndRow,- startY: startCell?.startY || 0,- endY: endCell?.endY || 0,- startX: startCell?.startX || 0,- endX: endCell?.endX || 0,- },- cellInfo- );- currentControls.push(control);- });-- // this._selectionControls.set(worksheetId, currentControls);- });- }-- /**- * Initialize the observer- */- private _initializeObserver() {- const context = this._plugin.getContext();- context.getContextObserver('onAfterChangeActiveSheetObservable').add(() => {- this.renderCurrentControls();- });-- this._worksheet- ?.getContext()- .getContextObserver('onSheetRenderDidMountObservable')- .add(() => {- this.renderCurrentControls();- });- }-}+import { IMouseEvent, IPointerEvent, Rect, Spreadsheet, SpreadsheetColumnTitle, SpreadsheetRowTitle, ScrollTimer } from '@univerjs/base-render';+import {+ Nullable,+ Observer,+ Worksheet,+ ISelection,+ makeCellToSelection,+ IRangeData,+ RangeList,+ Range,+ IRangeCellData,+ ICellInfo,+ Command,+ Direction,+ ActionOperation,+ ISelectionData,+ DEFAULT_SELECTION,+ DEFAULT_CELL,+ IGridRange,+ SheetContext,+} from '@univerjs/core';+import { Inject, Injector } from '@wendellhu/redi';+import { ACTION_NAMES, ISelectionsConfig } from '../../Basics';+import { ISelectionModelValue, ISetSelectionValueActionData, SetSelectionValueAction } from '../../Model/Action/SetSelectionValueAction';+import { SelectionModel } from '../../Model/SelectionModel';+import { SheetPlugin } from '../../SheetPlugin';+import { SheetView } from '../../View/Views/SheetView';+import { ColumnTitleController } from './ColumnTitleController';+import { DragLineController } from './DragLineController';+import { RowTitleController } from './RowTitleController';+import { SelectionController, SELECTION_TYPE } from './SelectionController';+import { ISheetContext, ISheetPlugin } from '../../Services/tokens';++/**+ * TODO 注册selection拦截,可能在有公式ArrayObject时,fx公式栏显示不同+ *+ * SelectionManager 维护model数据list,action也是修改这一层数据,obs监听到数据变动后,自动刷新(control仍然可以持有数据)+ */+export class SelectionManager {+ hasSelection: boolean = false;++ private _mainComponent: Spreadsheet;++ private _rowComponent: SpreadsheetRowTitle;++ private _columnComponent: SpreadsheetColumnTitle;++ private _leftTopComponent: Rect;++ private _moveObserver: Nullable<Observer<IPointerEvent | IMouseEvent>>;++ private _upObserver: Nullable<Observer<IPointerEvent | IMouseEvent>>;++ private _selectionControls: SelectionController[] = []; // sheetID:Controls++ private _selectionModels = new Map<string, SelectionModel[]>(); // sheetID:Models++ private _startSelectionRange: ISelection;++ private _startOffsetX: number = 0;++ private _startOffsetY: number = 0;++ private _worksheet: Nullable<Worksheet>;++ private _previousSelection: ISelectionData;++ constructor(+ /** @deprecated this should be divided into smaller pieces */+ private readonly _sheetView: SheetView,+ @Inject(Injector) private readonly _injector: Injector,+ /** @deprecated this should be divided into smaller pieces */+ @Inject(ISheetPlugin) private readonly _plugin: SheetPlugin,+ @Inject(DragLineController) private readonly _dragLineController: DragLineController,+ @Inject(ColumnTitleController) private readonly _columnTitleController: ColumnTitleController,+ @Inject(RowTitleController) private readonly _rowTitleController: RowTitleController,+ @ISheetContext private readonly _sheetContext: SheetContext+ ) {+ this._initialize();+ this._initializeObserver();+ }++ /** @deprecated */+ getSheetView() {+ return this._sheetView;+ }++ /** @deprecated */+ getScene() {+ return this._sheetView.getScene();+ }++ /** @deprecated */+ getContext() {+ return this._sheetView.getContext();+ }++ /** @deprecated */+ getMainComponent() {+ return this._mainComponent;+ }++ updateToSheet(worksheet: Worksheet) {+ this._worksheet = worksheet;+ const worksheetId = this.getWorksheetId();+ if (worksheetId) {+ const models = this._selectionModels.get(worksheetId);+ if (!models) {+ this._selectionModels.set(worksheetId, []);+ }+ }+ }++ getCurrentControls() {+ return this._selectionControls;+ }++ getCurrentControl() {+ const controls = this.getCurrentControls();+ if (controls && controls.length > 0) {+ for (const control of controls) {+ const currentCell = control.model.currentCell;+ if (currentCell) {+ return control;+ }+ }+ }+ }++ getCurrentModels() {+ const worksheetId = this.getWorksheetId();+ if (!worksheetId) {+ return;+ }++ const models = this._selectionModels.get(worksheetId);++ if (!models) {+ this._selectionModels.set(worksheetId, []);+ }+ return this._selectionModels.get(worksheetId);+ }++ getCurrentCellModel(): Nullable<ICellInfo> {+ const models = this.getCurrentModels();+ if (models && models.length > 0) {+ for (const model of models) {+ const currentCell = model.currentCell;+ if (currentCell) {+ return currentCell;+ }+ }+ }+ }++ getCurrentModel(): Nullable<SelectionModel> {+ const models = this.getCurrentModels();+ if (models && models.length > 0) {+ for (const model of models) {+ const currentCell = model.currentCell;+ if (currentCell) {+ return model;+ }+ }+ }+ }++ getCurrentModelsValue(): ISelectionModelValue[] {+ const models = this.getCurrentModels();+ if (!models) {+ return [];+ }+ const selectionModelsValue = [];+ for (let model of models) {+ selectionModelsValue.push(model.getValue());+ }+ return selectionModelsValue;+ }++ /**+ * Renders all controls of the currently active sheet+ * @returns+ */+ renderCurrentControls(command: boolean = true, models?: SelectionModel[]) {+ const worksheetId = this.getWorksheetId();+ if (worksheetId) {+ if (this._selectionControls) {+ // clear old controls+ for (let control of this._selectionControls) {+ control.dispose();+ }+ }++ // render current control+ const selectionModels = models || this._selectionModels.get(worksheetId);+ this._selectionControls = [];+ selectionModels?.forEach((model) => {+ const curCellRange = model.currentCell;+ const main = this._mainComponent;++ const control = SelectionController.create(this._injector, this._selectionControls.length);++ let cellInfo = null;+ if (curCellRange) {+ cellInfo = main.getCellByIndex(curCellRange.row, curCellRange.column);+ }++ const { startRow, startColumn, endRow, endColumn } = model;+ const startCell = main.getNoMergeCellPositionByIndex(startRow, startColumn);+ const endCell = main.getNoMergeCellPositionByIndex(endRow, endColumn);++ // update control model and view+ control.update(+ {+ startColumn,+ startRow,+ endColumn,+ endRow,+ startY: startCell?.startY || 0,+ endY: endCell?.endY || 0,+ startX: startCell?.startX || 0,+ endX: endCell?.endX || 0,+ },+ cellInfo+ );+ this._selectionControls.push(control);+ });++ command && this.setSelectionModel();+ }+ }++ getPlugin() {+ return this._plugin;+ }++ getWorksheetId() {+ return this._worksheet?.getSheetId();+ }++ /**+ * add a selection+ * @param selectionRange+ * @param curCellRange+ * @returns+ */+ addControlToCurrentByRangeData(selectionRange: IRangeData, curCellRange: Nullable<IRangeCellData>, command: boolean = true) {+ const currentControls = this.getCurrentControls();+ if (!currentControls) {+ return;+ }+ const main = this._mainComponent;++ const control = SelectionController.create(this._injector, currentControls.length);++ let cellInfo = null;+ if (curCellRange) {+ cellInfo = main.getCellByIndex(curCellRange.row, curCellRange.column);+ }++ const { startRow, startColumn, endRow, endColumn } = selectionRange;+ const startCell = main.getNoMergeCellPositionByIndex(startRow, startColumn);+ const endCell = main.getNoMergeCellPositionByIndex(endRow, endColumn);++ // update control+ control.update(+ {+ startColumn,+ startRow,+ endColumn,+ endRow,+ startY: startCell?.startY || 0,+ endY: endCell?.endY || 0,+ startX: startCell?.startX || 0,+ endX: endCell?.endX || 0,+ },+ cellInfo+ );++ currentControls.push(control);++ // this.setSelectionModel();++ if (command) {+ this.setSelectionModel();+ } else {+ const models = this._selectionControls.map((control) => control.model.getValue());+ return models;+ }+ }++ clearSelectionControls() {+ let curControls = this.getCurrentControls();++ if (curControls.length > 0) {+ for (let control of curControls) {+ control.dispose();+ }++ curControls.length = 0; // clear currentSelectionControls+ }+ }++ /**+ * update all current controls data in model+ */+ setSelectionModel(models?: ISelectionModelValue[]) {+ if (!this._worksheet) return;++ // get models from current control+ if (!models) {+ models = this._selectionControls.map((control) => control.model.getValue());+ }++ const workbook = this._worksheet.getContext().getWorkBook();+ const commandManager = workbook.getCommandManager();++ let action: ISetSelectionValueActionData = {+ sheetId: this._worksheet.getSheetId(),+ actionName: SetSelectionValueAction.NAME,+ selections: models,+ };++ action = ActionOperation.make<ISetSelectionValueActionData>(action).removeUndo().getAction();++ const command = new Command(+ {+ WorkBookUnit: workbook,+ },+ action+ );+ commandManager.invoke(command);+ }++ /**+ * update current control in model+ */+ updateSelectionModel(selection: ISelection, cell: Nullable<ICellInfo>, index: number) {+ const worksheetId = this.getWorksheetId();++ if (!this._worksheet || !worksheetId) return;++ // Collect constituency data for the entire current sheet+ const selectionModels = this._selectionModels.get(worksheetId);+ const selectionModelsValue: ISelectionModelValue[] = [];+ selectionModels?.forEach((model, i) => {+ if (i === index) {+ selectionModelsValue.push({ selection, cell });+ } else {+ selectionModelsValue.push(model.getValue());+ }+ });++ const workbook = this._worksheet.getContext().getWorkBook();+ const commandManager = workbook.getCommandManager();++ let action: ISetSelectionValueActionData = {+ sheetId: this._worksheet.getSheetId(),+ actionName: ACTION_NAMES.SET_SELECTION_VALUE_ACTION,+ selections: selectionModelsValue,+ };++ action = ActionOperation.make<ISetSelectionValueActionData>(action).removeUndo().getAction();++ const command = new Command(+ {+ WorkBookUnit: workbook,+ },+ action+ );+ commandManager.invoke(command);+ }++ setModels(selections: ISelectionModelValue[]) {+ const worksheetId = this.getWorksheetId();+ if (!worksheetId) {+ return;+ }++ const models = selections.map(({ selection, cell }) => {+ const model = this._injector.createInstance(SelectionModel, SELECTION_TYPE.NORMAL);+ model.setValue(selection, cell);+ return model;+ });++ this._selectionModels.set(worksheetId, models);+ }++ // recreateControlsByRangeData() { }++ /**+ * Move the selection according to different directions, usually used for the shortcut key operation of ↑ ↓ ← →+ * @param direction+ * @returns+ */+ move(direction: Direction): void {+ const currentCell = this.getCurrentCellModel();++ if (!currentCell) return;++ let { startRow: mergeStartRow, startColumn: mergeStartColumn, endRow: mergeEndRow, endColumn: mergeEndColumn } = currentCell.mergeInfo;++ let { row, column } = currentCell;+ const rowCount = this._worksheet?.getRowCount() || 1000;+ const columnCount = this._worksheet?.getColumnCount() || 50;+ switch (direction) {+ case Direction.TOP:+ if (currentCell.isMerged || currentCell.isMergedMainCell) {+ row = --mergeStartRow;+ } else {+ row--;+ }+ if (row < 0) {+ row = 0;+ }+ break;+ case Direction.BOTTOM:+ if (currentCell.isMerged || currentCell.isMergedMainCell) {+ row = ++mergeEndRow;+ } else {+ row++;+ }++ if (row > rowCount) {+ row = rowCount;+ }+ break;+ case Direction.LEFT:+ if (currentCell.isMerged || currentCell.isMergedMainCell) {+ column = --mergeStartColumn;+ } else {+ column--;+ }++ if (column < 0) {+ column = 0;+ }+ break;+ case Direction.RIGHT:+ if (currentCell.isMerged || currentCell.isMergedMainCell) {+ column = ++mergeEndColumn;+ } else {+ column++;+ }++ if (column > columnCount) {+ column = columnCount;+ }+ break;++ default:+ break;+ }++ const cellInfo = this._mainComponent.getCellByIndex(row, column);++ const selectionData = makeCellToSelection(cellInfo);++ if (!selectionData) return;++ const { startRow, endRow, startColumn, endColumn } = selectionData;++ const main = this._mainComponent;+ const newBounding = main.getSelectionBounding(startRow, startColumn, endRow, endColumn);++ if (!newBounding) {+ return;+ }++ const { startRow: finalStartRow, startColumn: finalStartColumn, endRow: finalEndRow, endColumn: finalEndColumn } = newBounding;++ let rangeData: IRangeData = {+ startRow: finalStartRow,+ endRow: finalEndRow,+ startColumn: finalStartColumn,+ endColumn: finalEndColumn,+ };+ let currentCellData: IRangeCellData = {+ row: startRow,+ column: startColumn,+ };++ this.clearSelectionControls();+ this.addControlToCurrentByRangeData(rangeData, currentCellData);+ this.updatePreviousSelection();+ }++ setCurrentCell(gridData: IGridRange): void {+ const { rangeData: girdRangeData, sheetId } = gridData;+ const { startRow: row, startColumn: column } = girdRangeData;++ // active new target sheet+ const currentSheetId = this.getWorksheetId();+ if (sheetId !== currentSheetId) {+ const sheetIndex = this._worksheet?.getIndex();+ if (sheetIndex == null) return;+ this._sheetContext.getWorkBook().activateSheetByIndex(sheetIndex);+ }++ const cellInfo = this._mainComponent.getCellByIndex(row, column);++ const selectionData = makeCellToSelection(cellInfo);++ if (!selectionData) return;++ const { startRow, endRow, startColumn, endColumn } = selectionData;++ const main = this._mainComponent;+ const newBounding = main.getSelectionBounding(startRow, startColumn, endRow, endColumn);++ if (!newBounding) {+ return;+ }++ const { startRow: finalStartRow, startColumn: finalStartColumn, endRow: finalEndRow, endColumn: finalEndColumn } = newBounding;++ let rangeData: IRangeData = {+ startRow: finalStartRow,+ endRow: finalEndRow,+ startColumn: finalStartColumn,+ endColumn: finalEndColumn,+ };+ let currentCellData: IRangeCellData = {+ row: startRow,+ column: startColumn,+ };++ this.clearSelectionControls();+ this.addControlToCurrentByRangeData(rangeData, currentCellData);+ this.updatePreviousSelection();+ }++ /**+ * 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+ * @param moveEvt+ * @param selectionControl+ * @returns+ */+ moving(moveEvt: IPointerEvent | IMouseEvent, selectionControl: Nullable<SelectionController>, setModel: boolean = false) {+ // console.log('moving');+ const main = this._mainComponent;+ const { offsetX: moveOffsetX, offsetY: moveOffsetY, clientX, clientY } = moveEvt;+ const { startRow, startColumn, endRow, endColumn } = this._startSelectionRange;++ // moveOffsetX and moveOffsetY is relative to the top left corner of the canvas+ const scrollXY = main.getAncestorScrollXY(this._startOffsetX, this._startOffsetY);+ const moveCellInfo = main.calculateCellIndexByPosition(moveOffsetX, moveOffsetY, scrollXY); // scrollXY is canvas content scrolling+ const moveActualSelection = makeCellToSelection(moveCellInfo);++ if (!moveActualSelection) {+ return false;+ }+ const { startRow: moveStartRow, startColumn: moveStartColumn, endColumn: moveEndColumn, endRow: moveEndRow } = moveActualSelection;++ const newStartRow = Math.min(moveStartRow, startRow);+ const newStartColumn = Math.min(moveStartColumn, startColumn);+ const newEndRow = Math.max(moveEndRow, endRow);+ const newEndColumn = Math.max(moveEndColumn, endColumn);+ const newBounding = main.getSelectionBounding(newStartRow, newStartColumn, newEndRow, newEndColumn);++ if (!newBounding) {+ return false;+ }+ const { startRow: finalStartRow, startColumn: finalStartColumn, endRow: finalEndRow, endColumn: finalEndColumn } = newBounding;++ const startCell = main.getNoMergeCellPositionByIndex(finalStartRow, finalStartColumn);+ const endCell = main.getNoMergeCellPositionByIndex(finalEndRow, finalEndColumn);++ const newSelectionRange: ISelection = {+ 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+ const { startRow: oldStartRow, endRow: oldEndRow, startColumn: oldStartColumn, endColumn: oldEndColumn } = selectionControl?.model || DEFAULT_SELECTION;+ const { row: oldRow, column: oldColumn } = selectionControl?.model.currentCell || DEFAULT_CELL;++ if (oldStartColumn !== finalStartColumn || oldStartRow !== finalStartRow || oldEndColumn !== finalEndColumn || oldEndRow !== finalEndRow) {+ selectionControl && selectionControl.update(newSelectionRange);+ selectionControl && this._plugin.getObserver('onChangeSelectionObserver')?.notifyObservers(selectionControl);+ }++ if (setModel) {+ if (!this._previousSelection) {+ this.setSelectionModel();+ } else {+ // If it is different from the range when clicked, you need to update the model+ const {+ startRow: mouseDownStartRow,+ endRow: mouseDownEndRow,+ startColumn: mouseDownStartColumn,+ endColumn: mouseDownEndColumn,+ } = (this._previousSelection.selection as IRangeData) || DEFAULT_SELECTION;+ const { row: mouseDownRow, column: mouseDownColumn } = (this._previousSelection.cell as IRangeCellData) || DEFAULT_CELL;+ if (+ mouseDownStartColumn !== finalStartColumn ||+ mouseDownStartRow !== finalStartRow ||+ mouseDownEndColumn !== finalEndColumn ||+ mouseDownEndRow !== finalEndRow ||+ mouseDownRow !== oldRow ||+ mouseDownColumn !== oldColumn+ ) {+ this.setSelectionModel();+ }+ }++ this.updatePreviousSelection();+ }+ }++ /**+ * pointer up event+ * @param moveEvt+ * @param selectionControl+ * @returns+ */+ up(upEvt: IPointerEvent | IMouseEvent, selectionControl: Nullable<SelectionController>) {+ // update model++ this.moving(upEvt, selectionControl, true);+ }++ updatePreviousSelection() {+ let selectionControl: Nullable<SelectionController> = this.getCurrentControl();++ if (!selectionControl) return;++ // this.setSelectionModel();+ const { startRow, endRow, startColumn, endColumn } = selectionControl.model;+ const { row, column } = selectionControl.model.currentCell || DEFAULT_CELL;+ this._previousSelection = {+ selection: {+ startRow,+ endRow,+ startColumn,+ endColumn,+ },+ cell: {+ row,+ column,+ },+ };+ }++ /**+ * Get all range data of the current selection+ * @returns+ */+ getActiveRangeListData(): Nullable<IRangeData[]> {+ const models = this.getCurrentModels();+ if (models && models.length > 0) {+ const selections = models?.map((model: SelectionModel) => ({+ startRow: model.startRow,+ startColumn: model.startColumn,+ endRow: model.endRow,+ endColumn: model.endColumn,+ }));++ return selections;+ }+ }++ /**+ * 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+ */+ getActiveRangeList(): Nullable<RangeList> {+ const rangeListData = this.getActiveRangeListData();+ return rangeListData && this._worksheet?.getRangeList(rangeListData);+ }++ /**+ * Get the range of the currently active cell+ * @returns+ */+ getActiveRangeData(): Nullable<IRangeData> {+ const models = this.getCurrentModels();+ if (models && models.length > 0) {+ for (const model of models) {+ if (model.currentCell) {+ return {+ startRow: model.startRow,+ startColumn: model.startColumn,+ endRow: model.endRow,+ endColumn: model.endColumn,+ };+ }+ }+ }+ }++ /**+ * 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.+ * @returns+ */+ getActiveRange(): Nullable<Range> {+ const rangeData = this.getActiveRangeData();+ return rangeData && this._worksheet?.getRange(rangeData);+ }++ /**+ * get active selection control+ * @returns+ */+ getCurrentCellData(): Nullable<IRangeData> {+ const models = this.getCurrentModels();+ if (models && models.length > 0) {+ for (const model of models) {+ const currentCell = model.currentCell;+ if (currentCell) {+ return {+ startRow: currentCell.row,+ startColumn: currentCell.column,+ endRow: currentCell.row,+ endColumn: currentCell.column,+ };+ }+ }+ }+ }++ /**+ * get active selection control+ * @returns+ */+ getCurrentCell(): Nullable<Range> {+ const rangeData = this.getCurrentCellData();+ return rangeData && this._worksheet?.getRange(rangeData);+ }++ getDragLineControl() {+ return this._dragLineController;+ }++ private _initialize() {+ this._mainComponent = this._sheetView.getSpreadsheet();+ this._rowComponent = this._sheetView.getSpreadsheetRowTitle();+ this._columnComponent = this._sheetView.getSpreadsheetColumnTitle();+ this._leftTopComponent = this._sheetView.getSpreadsheetLeftTopPlaceholder();++ this._mainEventInitial();++ this._rowEventInitial();++ this._columnEventInitial();++ this._leftTopEventInitial();++ this._worksheet = this.getContext().getWorkBook().getActiveSheet();++ this._initModels();++ const handler = {+ clearSelectionControls: () => this.clearSelectionControls(),+ addControlToCurrentByRangeData: (selectionRange: IRangeData, curCellRange: Nullable<IRangeCellData>, command: boolean = true) =>+ this.addControlToCurrentByRangeData(selectionRange, curCellRange, command),+ };++ this._columnTitleController.setHandlers(handler);+ this._rowTitleController.setHandlers(handler);+ }++ private _mainEventInitial() {+ const main = this._mainComponent;+ main.onPointerDownObserver.add((evt: IPointerEvent | IMouseEvent) => {+ const { offsetX: evtOffsetX, offsetY: evtOffsetY } = evt;+ this._startOffsetX = evtOffsetX;+ this._startOffsetY = evtOffsetY;+ const scrollXY = main.getAncestorScrollXY(this._startOffsetX, this._startOffsetY);+ const cellInfo = main.calculateCellIndexByPosition(evtOffsetX, evtOffsetY, scrollXY);+ const actualSelection = makeCellToSelection(cellInfo);+ if (!actualSelection || !this._worksheet) {+ return false;+ }++ const { startRow, startColumn, endColumn, endRow, startY, endY, startX, endX } = actualSelection;++ const startSelectionRange = {+ startColumn,+ startRow,+ endColumn,+ endRow,+ startY,+ endY,+ startX,+ endX,+ };++ this._startSelectionRange = startSelectionRange;++ let selectionControl: Nullable<SelectionController> = this.getCurrentControl();++ let curControls = this.getCurrentControls();++ if (!curControls) {+ return false;+ }++ for (let control of curControls) {+ // right click+ if (evt.button === 2 && control.model.isInclude(startSelectionRange)) {+ selectionControl = control;+ return;+ }+ // 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) {+ for (let control of curControls) {+ control.dispose();+ }++ curControls.length = 0; // clear currentSelectionControls+ }++ const currentCell = selectionControl && selectionControl.model.currentCell;++ if (selectionControl && evt.shiftKey && currentCell) {+ const { row, column } = currentCell;++ // TODO startCell position calculate error+ const startCell = main.getNoMergeCellPositionByIndex(row, column);+ const endCell = main.getNoMergeCellPositionByIndex(endRow, endColumn);++ const newSelectionRange = {+ startColumn: column,+ startRow: row,+ endColumn: startSelectionRange.startColumn,+ endRow: startSelectionRange.startRow,+ startY: startCell?.startY || 0,+ endY: endCell?.endY || 0,+ startX: startCell?.startX || 0,+ endX: endCell?.endX || 0,+ };+ selectionControl.update(newSelectionRange, currentCell);+ } else {+ selectionControl = SelectionController.create(this._injector, curControls.length);+ selectionControl.update(startSelectionRange, cellInfo);+ curControls.push(selectionControl);+ }++ this.hasSelection = true;++ const scene = this.getScene();++ scene.disableEvent();++ const scrollTimer = ScrollTimer.create(this.getScene());+ scrollTimer.startScroll(evtOffsetX, evtOffsetY);++ // In edit mode, click other cells, you need to update the current model, otherwise when updating the cell value, the old active range will be redrawn+ const currentModel = selectionControl.getCurrentCellInfo();+ if (!this._previousSelection) {+ // this.setSelectionModel();+ const models = this._selectionControls.map((control) => control.model.getValue());+ this.setModels(models);+ } else {+ // If it is different from the range when clicked, you need to update the model+ const {+ startRow: mouseDownStartRow,+ endRow: mouseDownEndRow,+ startColumn: mouseDownStartColumn,+ endColumn: mouseDownEndColumn,+ } = (this._previousSelection.selection as IRangeData) || DEFAULT_SELECTION;+ const { row: mouseDownRow, column: mouseDownColumn } = (this._previousSelection.cell as IRangeCellData) || DEFAULT_CELL;+ if (+ mouseDownStartColumn !== currentModel?.startColumn ||+ mouseDownStartRow !== currentModel?.startRow ||+ mouseDownEndColumn !== currentModel?.endColumn ||+ mouseDownEndRow !== currentModel?.endRow ||+ mouseDownRow !== currentModel?.startRow ||+ mouseDownColumn !== currentModel?.startColumn+ ) {+ // this.setSelectionModel();+ const models = this._selectionControls.map((control) => control.model.getValue());+ this.setModels(models);+ }+ }++ // Notification toolbar updates button state and value+ this._plugin.getObserver('onChangeSelectionObserver')?.notifyObservers(selectionControl);++ this._moveObserver = scene.onPointerMoveObserver.add((moveEvt: IPointerEvent | IMouseEvent) => {+ this.moving(moveEvt, selectionControl);+ const { offsetX: moveOffsetX, offsetY: moveOffsetY } = moveEvt;++ scrollTimer.scrolling(moveOffsetX, moveOffsetY, () => {+ this.moving(moveEvt, selectionControl);+ });+ });++ this._upObserver = scene.onPointerUpObserver.add((upEvt: IPointerEvent | IMouseEvent) => {+ this.up(upEvt, selectionControl);+ scene.onPointerMoveObserver.remove(this._moveObserver);+ scene.onPointerUpObserver.remove(this._upObserver);+ scene.enableEvent();++ scrollTimer.stopScroll();+ });++ // document.addEventListener('pointerup', () => {+ // this.up();+ // scene.onPointerMoveObserver.remove(this._moveObserver);+ // scene.onPointerUpObserver.remove(this._upObserver);+ // scene.enableEvent();++ // scrollTimer.stopScroll();+ // });+ });+ }++ private _rowEventInitial() {+ const row = this._rowComponent;+ row.onPointerEnterObserver.add((evt: IPointerEvent | IMouseEvent) => {+ // this._rowTitleControl.highlightRowTitle(evt);+ });+ }++ private _columnEventInitial() {+ const column = this._columnComponent;+ column.onPointerEnterObserver.add((evt: IPointerEvent | IMouseEvent) => {+ // this._columnTitleControl.highlightColumnTitle(evt);+ });+ }++ private _leftTopEventInitial() {+ const leftTop = this._leftTopComponent;+ leftTop.onPointerDownObserver.add((evt: IPointerEvent | IMouseEvent) => {+ // console.log('leftTop_moveObserver', evt);+ });+ }++ /**+ * Initialize selection model based on user configuration+ * @param selections+ */+ private _initModels() {+ const selections: ISelectionsConfig = this._plugin.getConfig().selections;++ Object.keys(selections).forEach((worksheetId) => {+ const selectionsList = selections[worksheetId];+ const currentModels: SelectionModel[] = [];++ selectionsList.forEach((selectionConfig) => {+ const { startColumn, startRow, endColumn, endRow } = selectionConfig.selection;+ const cell = selectionConfig.cell;++ const model = this._injector.createInstance(SelectionModel, SELECTION_TYPE.NORMAL);++ const cellInfo = cell+ ? {+ row: cell.row,+ column: cell.column,+ isMerged: false,+ isMergedMainCell: false,+ startY: 0,+ endY: 0,+ startX: 0,+ endX: 0,+ mergeInfo: {+ startColumn,+ startRow,+ endColumn,+ endRow,+ startY: 0,+ endY: 0,+ startX: 0,+ endX: 0,+ },+ }+ : null;++ // Only update data, not render+ model.setValue(+ {+ startColumn,+ startRow,+ endColumn,+ endRow,+ startY: 0,+ endY: 0,+ startX: 0,+ endX: 0,+ },+ cellInfo+ );+ currentModels.push(model);+ });++ this._selectionModels.set(worksheetId, currentModels);+ });+ }++ /**+ * Initialize selection based on user configuration+ * @param selections+ */+ private _initControls() {+ const selections: ISelectionsConfig = this._plugin.getConfig().selections;+ Object.keys(selections).forEach((worksheetId) => {+ const selectionsList = selections[worksheetId];+ const currentControls: SelectionController[] = [];++ selectionsList.forEach((selectionConfig) => {+ const selectionRange = selectionConfig.selection;+ const curCellRange = selectionConfig.cell;+ const main = this._mainComponent;++ const control = SelectionController.create(this._injector, currentControls.length);++ let cellInfo = null;+ if (curCellRange) {+ cellInfo = main.getCellByIndex(curCellRange.row, curCellRange.column);+ }++ const { startRow: finalStartRow, startColumn: finalStartColumn, endRow: finalEndRow, endColumn: finalEndColumn } = selectionRange;+ const startCell = main.getNoMergeCellPositionByIndex(finalStartRow, finalStartColumn);+ const endCell = main.getNoMergeCellPositionByIndex(finalEndRow, finalEndColumn);++ // Only update data, not render+ control.model.setValue(+ {+ startColumn: finalStartColumn,+ startRow: finalStartRow,+ endColumn: finalEndColumn,+ endRow: finalEndRow,+ startY: startCell?.startY || 0,+ endY: endCell?.endY || 0,+ startX: startCell?.startX || 0,+ endX: endCell?.endX || 0,+ },+ cellInfo+ );+ currentControls.push(control);+ });++ // this._selectionControls.set(worksheetId, currentControls);+ });+ }++ /**+ * Initialize the observer+ */+ private _initializeObserver() {+ this._sheetContext.getContextObserver('onAfterChangeActiveSheetObservable').add(() => {+ this.renderCurrentControls();+ });++ this._sheetContext.getContextObserver('onSheetRenderDidMountObservable').add(() => {+ this.renderCurrentControls();+ });+ }+}diff --git a/packages/base-sheets/src/Controller/Selection/Shared.ts b/packages/base-sheets/src/Controller/Selection/Shared.tsnew file mode 100644index 0000000000..3ec40f8c91--- /dev/null+++ b/packages/base-sheets/src/Controller/Selection/Shared.ts@@ -0,0 +1,6 @@+import { IRangeCellData, IRangeData, Nullable } from '@univerjs/core';++export interface IColumnTitleControllerHandlers {+ clearSelectionControls: () => void;+ addControlToCurrentByRangeData: (selectionRange: IRangeData, curCellRange: Nullable<IRangeCellData>, command?: boolean) => any;+}diff --git a/packages/base-sheets/src/Controller/SheetBarController.ts b/packages/base-sheets/src/Controller/SheetBarController.tsindex 315d4a4b5d..517a281175 100644--- a/packages/base-sheets/src/Controller/SheetBarController.ts+++ b/packages/base-sheets/src/Controller/SheetBarController.ts@@ -1,29 +1,27 @@-import { UIObserver } from '@univerjs/core';-import { SheetPlugin } from '../SheetPlugin';+import { Context, SheetContext, UIObserver } from '@univerjs/core';-export class SheetBarControl {- protected _plugin: SheetPlugin;+import { IGlobalContext, ISheetContext } from '../Services/tokens';- constructor(plugin: SheetPlugin) {- this._plugin = plugin;- }+export class SheetBarController {+ constructor(@IGlobalContext private readonly _globalContext: Context, @ISheetContext private readonly _context: SheetContext) {}listenEventManager(): void {this._getCoreObserver('onUIChangeObservable').add(({ name, value }) => {+ const context = this._context;switch (name) {case 'deleteSheet': {- const workbook = this._plugin.getContext().getWorkBook();+ const workbook = context.getWorkBook();if (workbook) {workbook.removeSheetBySheetId(value as string);}break;}case 'copySheet': {- const workbook = this._plugin.getContext().getWorkBook();+ const workbook = context.getWorkBook();const activeSheet = workbook.getActiveSheet();- const sheetContext = this._plugin.getContext();+ const sheetContext = context;const genName = sheetContext.getGenName();- const locale = this._plugin.getGlobalContext().getLocale();+ const locale = this._globalContext.getLocale();const copySheet = activeSheet.copy(genName.onlyName(`${activeSheet.getName()} ${locale.get('BaseSheetLocale.CopyName')}`));if (workbook) {workbook.insertSheet(workbook.getActiveSheetIndex() + 1, copySheet.getConfig());@@ -32,7 +30,7 @@ export class SheetBarControl {}case 'renameSheet': {const { sheetId, sheetName } = value as { sheetId: string; sheetName: string };- const workbook = this._plugin.getContext().getUniver().getCurrentUniverSheetInstance().getWorkBook();+ const workbook = context.getUniver().getCurrentUniverSheetInstance().getWorkBook();const worksheet = workbook.getSheetBySheetId(sheetId);if (worksheet && sheetName !== worksheet.getName()) {worksheet.setName(sheetName);@@ -40,7 +38,7 @@ export class SheetBarControl {break;}case 'addSheet': {- const workbook = this._plugin.getContext().getWorkBook();+ const workbook = context.getWorkBook();workbook.insertSheet();const size = workbook.getSheetSize();@@ -52,7 +50,7 @@ export class SheetBarControl {break;}case 'unHideSheet': {- const workbook = this._plugin.getContext().getWorkBook();+ const workbook = context.getWorkBook();const worksheet = workbook.getSheetBySheetId(value as string);if (worksheet) {worksheet.showSheet();@@ -60,7 +58,7 @@ export class SheetBarControl {break;}case 'hideSheet': {- const workbook = this._plugin.getContext().getWorkBook();+ const workbook = context.getWorkBook();const worksheet = workbook.getSheetBySheetId(value as string);if (worksheet) {worksheet.hideSheet();@@ -69,7 +67,7 @@ export class SheetBarControl {}case 'changeSheetColor': {const { color, sheetId } = value as { color: string; sheetId: string };- const workbook = this._plugin.getContext().getWorkBook();+ const workbook = context.getWorkBook();const worksheet = workbook.getSheetBySheetId(sheetId);if (worksheet) {worksheet.setTabColor(color);@@ -81,6 +79,6 @@ export class SheetBarControl {}protected _getCoreObserver<T>(type: string) {- return this._plugin.getGlobalContext().getObserverManager().requiredObserver<UIObserver<T>>(type, 'core');+ return this._globalContext.getObserverManager().requiredObserver<UIObserver<T>>(type, 'core');}}diff --git a/packages/base-sheets/src/Controller/SheetContainerController.ts b/packages/base-sheets/src/Controller/SheetContainerController.tsindex 2d155a4c44..4578eec423 100644--- a/packages/base-sheets/src/Controller/SheetContainerController.ts+++ b/packages/base-sheets/src/Controller/SheetContainerController.ts@@ -1,52 +1,53 @@-import { CommandManager, ISheetActionData, SheetActionBase } from '@univerjs/core';-import { SheetPlugin } from '../SheetPlugin';-// All skins' less file--export class SheetContainerController {- private _plugin: SheetPlugin;-- constructor(plugin: SheetPlugin) {- this._plugin = plugin;-- this._initialize();- }-- private _initialize() {- // Monitor all command changes and automatically trigger the refresh of the canvas- CommandManager.getCommandObservers().add(({ actions }) => {- const plugin: SheetPlugin = this._plugin;-- if (!plugin) return;- if (!actions || actions.length === 0) return;- const action = actions[0] as SheetActionBase<ISheetActionData, ISheetActionData, void>;-- const currentUnitId = plugin.context.getWorkBook().getUnitId();- // TODO not use try catch- try {- action.getWorkBook();- } catch (error) {- return;- }-- const actionUnitId = action.getWorkBook().getUnitId();-- if (currentUnitId !== actionUnitId) return;-- // Only the currently active worksheet needs to be refreshed- const worksheet = action.getWorkBook().getActiveSheet();- if (worksheet) {- try {- const canvasView = plugin.getCanvasView();- if (canvasView) {- canvasView.updateToSheet(worksheet);-- plugin.getMainComponent().makeDirty(true);- plugin.getSelectionManager().renderCurrentControls(false);- }- } catch (error) {- console.info(error);- }- }- });- }-}+import { CommandManager, ISheetActionData, SheetActionBase, SheetContext } from '@univerjs/core';+import { Inject } from '@wendellhu/redi';+import { ISelectionManager, ISheetContext } from '../Services/tokens';+import { SelectionManager } from './Selection';+import { CanvasView } from '../View';+// All skins' less file++export class SheetContainerController {+ constructor(+ @ISelectionManager private readonly _selectionManager: SelectionManager,+ @Inject(CanvasView) private readonly canvasView: CanvasView,+ @ISheetContext private readonly sheetContext: SheetContext+ ) {+ this._initialize();+ }++ private _initialize() {+ // Monitor all command changes and automatically trigger the refresh of the canvas+ CommandManager.getCommandObservers().add(({ actions }) => {+ if (!actions || actions.length === 0) return;++ const action = actions[0] as SheetActionBase<ISheetActionData, ISheetActionData, void>;++ const currentUnitId = this.sheetContext.getWorkBook().getUnitId();+ // TODO not use try catch+ try {+ action.getWorkBook();+ } catch (error) {+ return;+ }++ const actionUnitId = action.getWorkBook().getUnitId();++ if (currentUnitId !== actionUnitId) return;++ // Only the currently active worksheet needs to be refreshed+ const worksheet = action.getWorkBook().getActiveSheet();+ if (worksheet) {+ try {+ const canvasView = this.canvasView;+ if (canvasView) {+ this._selectionManager.updateToSheet(worksheet);+ canvasView.updateToSheet(worksheet);+ this.canvasView.getSheetView().getSpreadsheet().makeDirty(true);+ this._selectionManager.renderCurrentControls(false);+ }+ } catch (error) {+ console.info(error);+ }+ }+ });+ }+}diff --git a/packages/base-sheets/src/Controller/ToolbarController.ts b/packages/base-sheets/src/Controller/ToolbarController.tsindex d1a1be6a5c..bfafbc456e 100644--- a/packages/base-sheets/src/Controller/ToolbarController.ts+++ b/packages/base-sheets/src/Controller/ToolbarController.ts@@ -1,9 +1,12 @@-import { HorizontalAlign, VerticalAlign, WrapStrategy, BorderType, UIObserver } from '@univerjs/core';-import { SheetPlugin } from '../SheetPlugin';+import { Inject } from '@wendellhu/redi';+import { HorizontalAlign, VerticalAlign, WrapStrategy, BorderType, UIObserver, Context, SheetContext } from '@univerjs/core';-import { SelectionControl } from './Selection/SelectionController';+import { SelectionController } from './Selection/SelectionController';import { SelectionModel } from '../Model';+import { IGlobalContext, ISelectionManager, ISheetContext } from '../Services/tokens';+import { CellEditorController } from './CellEditorController';+import { SelectionManager } from './Selection';export interface BorderInfo {type: BorderType;@@ -15,20 +18,18 @@ export interface BorderInfo {**/export class ToolbarController {- private _plugin: SheetPlugin;-- constructor(plugin: SheetPlugin) {- this._plugin = plugin;-+ constructor(+ @ISelectionManager private readonly _selectionManager: SelectionManager,+ @IGlobalContext private readonly _globalContext: Context,+ @ISheetContext private readonly _sheetContext: SheetContext,+ @Inject(CellEditorController) private readonly _cellEditorController: CellEditorController+ ) {this._initialize();}listenEventManager() {- const cellEditorController = this._plugin.getCellEditorController();- this._plugin- .getContext()- .getUniver()- .getGlobalContext()+ const cellEditorController = this._cellEditorController;+ this._globalContext.getObserverManager().requiredObserver<UIObserver<number>>('onUIChangeObservable', 'core').add((msg) => {@@ -42,10 +43,7 @@ export class ToolbarController {}});- this._plugin- .getContext()- .getUniver()- .getGlobalContext()+ this._globalContext.getObserverManager().requiredObserver<UIObserver<number>>('onUIChangeObservable', 'core').add((msg) => {@@ -69,10 +67,7 @@ export class ToolbarController {}});- this._plugin- .getContext()- .getUniver()- .getGlobalContext()+ this._globalContext.getObserverManager().requiredObserver<UIObserver<BorderInfo>>('onUIChangeObservable', 'core').add((msg) => {@@ -84,10 +79,7 @@ export class ToolbarController {}});- this._plugin- .getContext()- .getUniver()- .getGlobalContext()+ this._globalContext.getObserverManager().requiredObserver<UIObserver<string>>('onUIChangeObservable', 'core').add((msg) => {@@ -108,10 +100,7 @@ export class ToolbarController {}});- this._plugin- .getContext()- .getUniver()- .getGlobalContext()+ this._globalContext.getObserverManager().requiredObserver<UIObserver<boolean>>('onUIChangeObservable', 'core').add((msg) => {@@ -155,47 +144,47 @@ export class ToolbarController {}setRedo() {- this._plugin.getContext().getCommandManager().redo();+ this._sheetContext.getCommandManager().redo();}setUndo() {- this._plugin.getContext().getCommandManager().undo();+ this._sheetContext.getCommandManager().undo();}setFontColor(value: string) {- this._plugin.getSelectionManager().getActiveRangeList()?.setFontColor(value);+ this._selectionManager.getActiveRangeList()?.setFontColor(value);}setBackground(value: string) {- this._plugin.getSelectionManager().getActiveRangeList()?.setBackground(value);+ this._selectionManager.getActiveRangeList()?.setBackground(value);}setFontSize(value: number) {- this._plugin.getSelectionManager().getActiveRangeList()?.setFontSize(value);+ this._selectionManager.getActiveRangeList()?.setFontSize(value);}setFontFamily(value: string) {- this._plugin.getSelectionManager().getActiveRangeList()?.setFontFamily(value);+ this._selectionManager.getActiveRangeList()?.setFontFamily(value);}setFontWeight(value: boolean) {- this._plugin.getSelectionManager().getActiveRangeList()?.setFontWeight(value);+ this._selectionManager.getActiveRangeList()?.setFontWeight(value);}setFontStyle(value: boolean) {- this._plugin.getSelectionManager().getActiveRangeList()?.setFontStyle(value);+ this._selectionManager.getActiveRangeList()?.setFontStyle(value);}setStrikeThrough(value: boolean) {- this._plugin.getSelectionManager().getActiveRangeList()?.setStrikeThrough(value);+ this._selectionManager.getActiveRangeList()?.setStrikeThrough(value);}setUnderline(value: boolean) {- this._plugin.getSelectionManager().getActiveRangeList()?.setUnderline(value);+ this._selectionManager.getActiveRangeList()?.setUnderline(value);}setMerge(value: string) {- const currentRange = this._plugin.getSelectionManager().getActiveRange();+ const currentRange = this._selectionManager.getActiveRange();switch (value) {case 'all':@@ -220,33 +209,30 @@ export class ToolbarController {}setHorizontalAlignment(value: HorizontalAlign) {- this._plugin.getSelectionManager().getActiveRangeList()?.setHorizontalAlignment(value);+ this._selectionManager.getActiveRangeList()?.setHorizontalAlignment(value);}setVerticalAlignment(value: VerticalAlign) {- this._plugin.getSelectionManager().getActiveRangeList()?.setVerticalAlignment(value);+ this._selectionManager.getActiveRangeList()?.setVerticalAlignment(value);}setWrapStrategy(value: WrapStrategy) {- this._plugin.getSelectionManager().getActiveRangeList()?.setWrapStrategy(value);+ this._selectionManager.getActiveRangeList()?.setWrapStrategy(value);}setTextRotation(value: number | string) {if (value === 'v') {- this._plugin.getSelectionManager().getActiveRangeList()?.setVerticalText(1);+ this._selectionManager.getActiveRangeList()?.setVerticalText(1);} else {- this._plugin- .getSelectionManager()- .getActiveRangeList()- ?.setTextRotation(value as number);+ this._selectionManager.getActiveRangeList()?.setTextRotation(value as number);}}setBorder(info: BorderInfo) {- const controls = this._plugin.getSelectionManager().getCurrentControls();+ const controls = this._selectionManager.getCurrentControls();if (controls && controls.length > 0) {- controls?.forEach((control: SelectionControl) => {+ controls?.forEach((control: SelectionController) => {const model: SelectionModel = control.model;const range = {startRow: model.startRow,@@ -255,7 +241,7 @@ export class ToolbarController {endColumn: model.endColumn,};- this._plugin.getContext().getWorkBook().getActiveSheet().getRange(range).setBorderByType(info.type, info.color, info.style);+ this._sheetContext.getWorkBook().getActiveSheet().getRange(range).setBorderByType(info.type, info.color, info.style);});}}diff --git a/packages/base-sheets/src/Model/SelectionModel.ts b/packages/base-sheets/src/Model/SelectionModel.tsindex 7d9b9b1065..097ae02f76 100644--- a/packages/base-sheets/src/Model/SelectionModel.ts+++ b/packages/base-sheets/src/Model/SelectionModel.ts@@ -1,6 +1,6 @@-import { ICellInfo, ISelection, Nullable, makeCellToSelection } from '@univerjs/core';+import { ICellInfo, ISelection, Nullable, SheetContext, makeCellToSelection } from '@univerjs/core';import { SELECTION_TYPE } from '../Controller/Selection/SelectionController';-import { SheetPlugin } from '../SheetPlugin';+import { ISheetContext } from '../Services/tokens';export class SelectionModel implements ISelection {private _startColumn: number;@@ -23,11 +23,8 @@ export class SelectionModel implements ISelection {private _currentCell: Nullable<ICellInfo>;- private _plugin: SheetPlugin;-- constructor(type: SELECTION_TYPE = SELECTION_TYPE.NORMAL, plugin: SheetPlugin) {+ constructor(type: SELECTION_TYPE = SELECTION_TYPE.NORMAL, @ISheetContext private readonly _sheetContext: SheetContext) {this._type = type;- this._plugin = plugin;}get startColumn() {@@ -165,8 +162,9 @@ export class SelectionModel implements ISelection {* Determine the type type based on the data*/setTypeByData() {- const rowCount = this._plugin.getWorkbook().getActiveSheet().getConfig().rowCount;- const columnCount = this._plugin.getWorkbook().getActiveSheet().getConfig().columnCount;+ const workbook = this._sheetContext.getWorkBook();+ const rowCount = workbook.getActiveSheet().getConfig().rowCount;+ const columnCount = workbook.getActiveSheet().getConfig().columnCount;if (this._startRow === 0 && this._endRow === rowCount - 1) {return (this._type = SELECTION_TYPE.COLUMN);diff --git a/packages/base-sheets/src/Services/tokens.ts b/packages/base-sheets/src/Services/tokens.tsnew file mode 100644index 0000000000..b0e0a5cd2d--- /dev/null+++ b/packages/base-sheets/src/Services/tokens.ts@@ -0,0 +1,22 @@+import { createIdentifier } from '@wendellhu/redi';++import { Engine } from '@univerjs/base-render';+import { Context, SheetContext } from '@univerjs/core';++import { SheetPlugin } from '../SheetPlugin';+import { SelectionManager } from '../Controller';+import { CanvasView } from '../View';++export const IGlobalContext = createIdentifier<Context>('univer.global.context');++export const ISheetContext = createIdentifier<SheetContext>('univer.sheet.context');++export const IRenderingEngine = createIdentifier<Engine>('univer.render-engine');++/** @deprecated temp solution */+export const ISheetPlugin = createIdentifier<SheetPlugin>('deprecated.univer.sheet.plugin');++/** @deprecated temporary solution, we should inject SelectionManager directly */+export const ISelectionManager = createIdentifier<SelectionManager>('deprecated.univer.sheet.selection-manager');++export const ICanvasView = createIdentifier<CanvasView>('univer.sheet.canvas-view');diff --git a/packages/base-sheets/src/SheetPlugin.ts b/packages/base-sheets/src/SheetPlugin.tsindex bd2b4c2f08..bd63a3a9e6 100644--- a/packages/base-sheets/src/SheetPlugin.ts+++ b/packages/base-sheets/src/SheetPlugin.ts@@ -1,35 +1,50 @@import { Engine, RenderEngine } from '@univerjs/base-render';import { SheetContext, Plugin, PLUGIN_NAMES, DEFAULT_SELECTION, UniverSheet, UIObserver } from '@univerjs/core';+import { Injector } from '@wendellhu/redi';import { SheetPluginObserve, uninstall } from './Basics/Observer';import { CANVAS_VIEW_KEY } from './View/BaseView';import { CanvasView } from './View/CanvasView';-import { RightMenuController, SheetBarControl, CellEditorController, SheetContainerController, ToolbarController, CountBarController, EditTooltipsController } from './Controller';+import {+ RightMenuController,+ SheetBarController,+ CellEditorController,+ SheetContainerController,+ ToolbarController,+ CountBarController,+ EditTooltipsController,+ SelectionManager,+} from './Controller';import { DEFAULT_SPREADSHEET_PLUGIN_DATA, install, ISheetPluginConfig } from './Basics';import { FormulaBarController } from './Controller/FormulaBarController';import { NamedRangeActionExtensionFactory } from './Basics/Register/NamedRangeActionExtension';import { en, zh } from './Locale';+import { IGlobalContext, IRenderingEngine, ISelectionManager, ISheetContext, ISheetPlugin } from './Services/tokens';+import { DragLineController } from './Controller/Selection/DragLineController';+import { ColumnTitleController } from './Controller/Selection/ColumnTitleController';+import { RowTitleController } from './Controller/Selection/RowTitleController';/*** The main sheet base, construct the sheet container and layout, mount the rendering engine*/-export class SheetPlugin extends Plugin<SheetPluginObserve, SheetContext> {+ private _injector: Injector;+private _config: ISheetPluginConfig;private _canvasEngine: Engine;- private _canvasView: CanvasView;+ // TODO@huwenzhao: these controllers should be removed finally after we completely refactored base-sheet plugin- private _rightMenuControl: RightMenuController;+ private _rightMenuController: RightMenuController;- private _toolbarControl: ToolbarController;+ private _toolbarController: ToolbarController;private _editTooltipsController: EditTooltipsController;private _formulaBarController: FormulaBarController;- private _sheetBarControl: SheetBarControl;+ private _sheetBarController: SheetBarController;private _cellEditorController: CellEditorController;@@ -41,7 +56,10 @@ export class SheetPlugin extends Plugin<SheetPluginObserve, SheetContext> {constructor(config?: Partial<ISheetPluginConfig>) {super(PLUGIN_NAMES.SPREADSHEET);+this._config = Object.assign(DEFAULT_SPREADSHEET_PLUGIN_DATA, config);++ this.initializeDependencies();}static create(config?: Partial<ISheetPluginConfig>) {@@ -85,32 +103,28 @@ export class SheetPlugin extends Plugin<SheetPluginObserve, SheetContext> {}}+ // TODO@huwenzhao: We don't need to init controllers manuallyinitController() {- this._sheetContainerController = new SheetContainerController(this);- this._cellEditorController = new CellEditorController(this);- this._formulaBarController = new FormulaBarController(this);- this._editTooltipsController = new EditTooltipsController(this);- this._sheetBarControl = new SheetBarControl(this);- this._toolbarControl = new ToolbarController(this);- this._rightMenuControl = new RightMenuController(this);- this._countBarController = new CountBarController(this);+ this._sheetContainerController = this._injector.get(SheetContainerController);+ this._cellEditorController = this._injector.get(CellEditorController);+ this._formulaBarController = this._injector.get(FormulaBarController);+ this._editTooltipsController = this._injector.get(EditTooltipsController);+ this._sheetBarController = this._injector.get(SheetBarController);+ this._toolbarController = this._injector.get(ToolbarController);+ this._rightMenuController = this._injector.get(RightMenuController);+ this._countBarController = this._injector.get(CountBarController);}initCanvasView() {const engine = this.getGlobalContext().getPluginManager().getRequirePluginByName<RenderEngine>(PLUGIN_NAMES.BASE_RENDER).getEngine();-this._canvasEngine = engine;-- if (this._canvasView == null) {- this._canvasView = new CanvasView(engine, this);- }}- onMounted(ctx: SheetContext): void {+ override onMounted(ctx: SheetContext): void {this.initialize(ctx);}- onDestroy(): void {+ override onDestroy(): void {super.onDestroy();uninstall(this);@@ -127,91 +141,102 @@ export class SheetPlugin extends Plugin<SheetPluginObserve, SheetContext> {listenEventManager() {// TODO: move to toolbarcontrollerthis._countBarController.listenEventManager();- this._sheetBarControl.listenEventManager();- this._toolbarControl.listenEventManager();- this._rightMenuControl.listenEventManager();+ this._sheetBarController.listenEventManager();+ this._toolbarController.listenEventManager();+ this._rightMenuController.listenEventManager();}+ /** @deprecated DI */getEditTooltipsController(): EditTooltipsController {return this._editTooltipsController;}+ /** @deprecated DI */getCanvasEngine() {return this._canvasEngine;}+ /** @deprecated DI */getCanvasView() {- return this._canvasView;+ return this._injector.get(CanvasView);}+ /** @deprecated DI */getMainScene() {return this._canvasEngine.getScene(CANVAS_VIEW_KEY.MAIN_SCENE);}+ /** @deprecated DI */getSheetView() {return this.getCanvasView().getSheetView();}+ /** @deprecated DI */getSelectionManager() {- return this.getSheetView()?.getSelectionManager();+ return this._injector.get(ISelectionManager);}+ /** @deprecated DI */getCurrentControls() {return this.getSelectionManager()?.getCurrentControls();}+ /** @deprecated DI */getSelectionShape() {return this._canvasEngine;}+ /** @deprecated DI */getMainComponent() {return this.getSheetView().getSpreadsheet();}+ /** @deprecated DI */getLeftTopComponent() {return this.getSheetView().getSpreadsheetLeftTopPlaceholder();}+ /** @deprecated DI */getRowComponent() {return this.getSheetView().getSpreadsheetRowTitle();}+ /** @deprecated DI */getColumnComponent() {return this.getSheetView().getSpreadsheetColumnTitle();}+ /** @deprecated DI */getSpreadsheetSkeleton() {return this.getSheetView().getSpreadsheetSkeleton();}+ /** @deprecated DI */getWorkbook() {return this.context.getWorkBook();}+ /** @deprecated DI */getRightMenuControl() {- return this._rightMenuControl;+ return this._rightMenuController;}+ /** @deprecated DI */getToolbarControl() {- return this._toolbarControl;+ return this._toolbarController;}+ /** @deprecated DI */getSheetBarControl() {- return this._sheetBarControl;+ return this._sheetBarController;}+ /** @deprecated DI */getCellEditorController() {return this._cellEditorController;}- getFormulaBarController() {- return this._formulaBarController;- }-- getSheetContainerControl() {- return this._sheetContainerController;- }-+ /** @deprecated DI */getCountBarController() {return this._countBarController;}@@ -219,4 +244,42 @@ export class SheetPlugin extends Plugin<SheetPluginObserve, SheetContext> {protected _getCoreObserver<T>(type: string) {return this.getGlobalContext().getObserverManager().requiredObserver<UIObserver<T>>(type, 'core');}++ private initializeDependencies() {+ const self = this;++ this._injector = new Injector([+ [IGlobalContext, { useFactory: () => this.getGlobalContext() }],+ [ISheetContext, { useFactory: () => this.getContext() }],+ [IRenderingEngine, { useFactory: () => this.getGlobalContext().getPluginManager().getRequirePluginByName<RenderEngine>(PLUGIN_NAMES.BASE_RENDER).getEngine() }],+ [ISheetPlugin, { useValue: self }],++ // Rendering Module+ [CanvasView],++ // #region Controllers+ [CellEditorController],+ [SheetContainerController],+ [FormulaBarController],+ [EditTooltipsController],+ [SheetBarController],+ [ToolbarController],+ [RightMenuController],+ [CountBarController],++ // TODO@huwenzhao: this is a temporary solution+ [+ ISelectionManager,+ {+ useFactory: (injector: Injector, canvasView: CanvasView, gLC: DragLineController, cTC: ColumnTitleController, rTC: RowTitleController, context: SheetContext) =>+ new SelectionManager(canvasView.getSheetView(), injector, self, gLC, cTC, rTC, context),+ deps: [Injector, CanvasView, DragLineController, ColumnTitleController, RowTitleController, ISheetContext],+ },+ ],+ [RowTitleController],+ [ColumnTitleController],+ [DragLineController],+ // #endregion Controllers+ ]);+ }}diff --git a/packages/base-sheets/src/View/BaseView.ts b/packages/base-sheets/src/View/BaseView.tsindex 0b928c00c9..6fff7bd456 100644--- a/packages/base-sheets/src/View/BaseView.ts+++ b/packages/base-sheets/src/View/BaseView.ts@@ -1,35 +1,31 @@import { Scene } from '@univerjs/base-render';-import { Registry, Worksheet } from '@univerjs/core';-import { SheetPlugin } from '../SheetPlugin';+import { Registry, SheetContext, Worksheet } from '@univerjs/core';+import { Injector } from '@wendellhu/redi';+import { ISheetContext } from '../Services/tokens';export class BaseView {viewKey = '';- private _scene: Scene;+ protected _injector: Injector;- private _plugin: SheetPlugin;+ private _scene: Scene;- // constructor(private _scene: Scene, private _plugin: Plugin) {- // this._initialize();- // }+ private _context: SheetContext;getScene() {return this._scene;}- getPlugin() {- return this._plugin;- }-getContext() {- return this._plugin.getContext();+ return this._context;}updateToSheet(worksheet: Worksheet) {}- initialize(scene: Scene, plugin: SheetPlugin) {+ initialize(scene: Scene, injector: Injector) {+ this._injector = injector;+ this._context = injector.get(ISheetContext);this._scene = scene;- this._plugin = plugin;this._initialize();return this;}diff --git a/packages/base-sheets/src/View/CanvasView.ts b/packages/base-sheets/src/View/CanvasView.tsindex fbf197e106..cf8f8ba007 100644--- a/packages/base-sheets/src/View/CanvasView.ts+++ b/packages/base-sheets/src/View/CanvasView.ts@@ -1,9 +1,11 @@+import { Inject, Injector } from '@wendellhu/redi';+import { Engine, EVENT_TYPE, IScrollObserverParam, IWheelEvent, Layer, Scene, ScrollBar, Viewport } from '@univerjs/base-render';-import { EventState, Worksheet } from '@univerjs/core';+import { EventState, SheetContext, Worksheet } from '@univerjs/core';import { BaseView, CANVAS_VIEW_KEY, CanvasViewRegistry } from './BaseView';import { SheetView } from './Views/SheetView';import './Views';-import { SheetPlugin } from '../index';+import { IRenderingEngine, ISheetContext } from '../Services/tokens';// workbookexport class CanvasView {@@ -11,7 +13,11 @@ export class CanvasView {private _views: BaseView[] = []; // worksheet- constructor(private _engine: Engine, private _plugin: SheetPlugin) {+ constructor(+ @Inject(Injector) private readonly _injector: Injector,+ @ISheetContext private readonly _sheetContext: SheetContext,+ @IRenderingEngine private readonly _engine: Engine+ ) {this._initialize();}@@ -35,9 +41,8 @@ export class CanvasView {private _initialize() {const engine = this._engine;- const context = this._plugin.getContext();- // const workbook = context.getWorkBook();- const workbook = this._plugin.getWorkbook();+ const context = this._sheetContext;+ const workbook = context.getWorkBook();let worksheet = workbook.getActiveSheet();if (!worksheet) {worksheet = workbook.getSheets()[0];@@ -102,7 +107,6 @@ export class CanvasView {// sheet zoom [0 ~ 1]context.getContextObserver('onZoomRatioSheetObservable').add((value) => {- const plugin = this._plugin;this._scene.scale(value.zoomRatio, value.zoomRatio);});@@ -139,7 +143,7 @@ export class CanvasView {scene.addLayer(Layer.create(scene, [], 0), Layer.create(scene, [], 2));- this._viewLoader(scene, this._plugin);+ this._viewLoader(scene);engine.runRenderLoop(() => {scene.render();@@ -150,9 +154,10 @@ export class CanvasView {});}- private _viewLoader(scene: Scene, plugin: SheetPlugin) {+ private _viewLoader(scene: Scene) {+ // FIXME: need a plugin hereCanvasViewRegistry.getData().forEach((viewFactory) => {- this._views.push(viewFactory.create(scene, plugin));+ this._views.push(viewFactory.create(scene, this._injector));});}}diff --git a/packages/base-sheets/src/View/Views/EditTooltipsView.ts b/packages/base-sheets/src/View/Views/EditTooltipsView.tsindex 56052770c9..3bc93562ae 100644--- a/packages/base-sheets/src/View/Views/EditTooltipsView.ts+++ b/packages/base-sheets/src/View/Views/EditTooltipsView.ts@@ -34,7 +34,7 @@ export class EditTooltips extends Rect<EditTooltipsProps> {this.translateLeft = 0;}- static drawWith(ctx: CanvasRenderingContext2D, props: EditTooltips): void {+ static override drawWith(ctx: CanvasRenderingContext2D, props: EditTooltips): void {if (props.text) {ctx.font = `${props.textSize}px Arial`;const metrics = ctx.measureText(props.text);@@ -97,7 +97,7 @@ export class EditTooltips extends Rect<EditTooltipsProps> {this.makeDirty(true);}- protected _draw(ctx: CanvasRenderingContext2D) {+ protected override _draw(ctx: CanvasRenderingContext2D) {super._draw(ctx);EditTooltips.drawWith(ctx, this);}diff --git a/packages/base-sheets/src/View/Views/SheetView.ts b/packages/base-sheets/src/View/Views/SheetView.tsindex bceb31ecec..f6817575b1 100644--- a/packages/base-sheets/src/View/Views/SheetView.ts+++ b/packages/base-sheets/src/View/Views/SheetView.ts@@ -1,8 +1,7 @@import { getColor, Rect, Scene, Spreadsheet, SpreadsheetColumnTitle, SpreadsheetRowTitle, SpreadsheetSkeleton } from '@univerjs/base-render';import { Worksheet } from '@univerjs/core';+import { Injector } from '@wendellhu/redi';import { BaseView, CANVAS_VIEW_KEY, CanvasViewRegistry } from '../BaseView';-import { SelectionManager } from '../../Controller/Selection/SelectionManager';-import { SheetPlugin } from '../../SheetPlugin';export enum SHEET_VIEW_KEY {MAIN = '__SpreadsheetRender__',@@ -12,9 +11,7 @@ export enum SHEET_VIEW_KEY {}export class SheetView extends BaseView {- viewKey = CANVAS_VIEW_KEY.SHEET_VIEW;-- private _selectionManager: SelectionManager;+ override viewKey = CANVAS_VIEW_KEY.SHEET_VIEW;private _spreadsheetSkeleton: SpreadsheetSkeleton;@@ -26,14 +23,6 @@ export class SheetView extends BaseView {private _spreadsheetLeftTopPlaceholder: Rect;- getSelectionManager() {- return this._selectionManager;- }-- getSelectionControls() {- return this._selectionManager.getCurrentControls();- }-getSpreadsheetSkeleton() {return this._spreadsheetSkeleton;}@@ -54,7 +43,7 @@ export class SheetView extends BaseView {return this._spreadsheetLeftTopPlaceholder;}- updateToSheet(worksheet: Worksheet) {+ override updateToSheet(worksheet: Worksheet) {const scene = this.getScene();const spreadsheetSkeleton = this._buildSkeleton(worksheet);const { rowTotalHeight, columnTotalWidth, rowTitleWidth, columnTitleHeight } = spreadsheetSkeleton;@@ -75,10 +64,9 @@ export class SheetView extends BaseView {// height: this._rowHeightByTitle(worksheet) + rowTotalHeight + 200,});this._updateViewport(rowTitleWidth, columnTitleHeight);- this._selectionManager.updateToSheet(worksheet);}- protected _initialize() {+ protected override _initialize() {const scene = this.getScene();const context = this.getContext();const workbook = context.getWorkBook();@@ -121,8 +109,6 @@ export class SheetView extends BaseView {});this._updateViewport(rowTitleWidth, columnTitleHeight);-- this._selectionManager = new SelectionManager(this);}private _updateViewport(rowTitleWidth: number, columnTitleHeight: number) {@@ -182,12 +168,13 @@ export class SheetView extends BaseView {export class SheetViewFactory {/*** Generate SheetView Instance- * @param scene- * @param plugin+ * @param injector* @returns*/- create(scene: Scene, plugin: SheetPlugin): SheetView {- return new SheetView().initialize(scene, plugin);+ create(scene: Scene, injector: Injector): SheetView {+ // TODO@huwenzhao: should be created from DI system and remove the initialize method+ return new SheetView().initialize(scene, injector);}}+CanvasViewRegistry.add(new SheetViewFactory());diff --git a/packages/base-sheets/src/View/Views/OtherViewTest.ts b/packages/base-sheets/src/View/Views/__testing__/OtherViewTest.tssimilarity index 99%rename from packages/base-sheets/src/View/Views/OtherViewTest.tsrename to packages/base-sheets/src/View/Views/__testing__/OtherViewTest.tsindex 12d7b6374c..56c63e7791 100644--- a/packages/base-sheets/src/View/Views/OtherViewTest.ts+++ b/packages/base-sheets/src/View/Views/__testing__/OtherViewTest.ts@@ -12,8 +12,8 @@ import {SectionType,WrapTextType,} from '@univerjs/core';-import { SheetPlugin } from '../../SheetPlugin';-import { BaseView } from '../BaseView';+import { SheetPlugin } from '../../../SheetPlugin';+import { BaseView } from '../../BaseView';const richTextTest: IDocumentData = {id: 'd',diff --git a/packages/base-sheets/src/View/Views/SceneViewerTestView.ts b/packages/base-sheets/src/View/Views/__testing__/SceneViewerTestView.tssimilarity index 98%rename from packages/base-sheets/src/View/Views/SceneViewerTestView.tsrename to packages/base-sheets/src/View/Views/__testing__/SceneViewerTestView.tsindex 2f25de7843..2acc3462b8 100644--- a/packages/base-sheets/src/View/Views/SceneViewerTestView.ts+++ b/packages/base-sheets/src/View/Views/__testing__/SceneViewerTestView.ts@@ -15,8 +15,8 @@ import {Viewport,} from '@univerjs/base-render';import { EventState, Worksheet } from '@univerjs/core';-import { SheetPlugin } from '../../SheetPlugin';-import { BaseView } from '../BaseView';+import { SheetPlugin } from '../../../SheetPlugin';+import { BaseView } from '../../BaseView';enum SHEET_VIEW_KEY {MAIN = '__SpreadsheetRender__Test',diff --git a/packages/base-sheets/src/View/Views/TestView.ts b/packages/base-sheets/src/View/Views/__testing__/TestView.tssimilarity index 96%rename from packages/base-sheets/src/View/Views/TestView.tsrename to packages/base-sheets/src/View/Views/__testing__/TestView.tsindex f5151e1b88..bbfcdc8678 100644--- a/packages/base-sheets/src/View/Views/TestView.ts+++ b/packages/base-sheets/src/View/Views/__testing__/TestView.ts@@ -1,6 +1,6 @@import { EVENT_TYPE, getColor, IRectProps, Rect, Scene } from '@univerjs/base-render';-import { SheetPlugin } from '../../SheetPlugin';-import { BaseView } from '../BaseView';+import { SheetPlugin } from '../../../SheetPlugin';+import { BaseView } from '../../BaseView';export class TestView extends BaseView {protected _initialize() {diff --git a/packages/base-sheets/src/View/Views/index.ts b/packages/base-sheets/src/View/Views/index.tsindex 88dccab263..f9bf6051e1 100644--- a/packages/base-sheets/src/View/Views/index.ts+++ b/packages/base-sheets/src/View/Views/index.ts@@ -1,5 +1,2 @@export * from './SheetView';-export * from './TestView';-export * from './SceneViewerTestView';-export * from './OtherViewTest';export * from './EditTooltipsView';diff --git a/packages/base-sheets/tsconfig.json b/packages/base-sheets/tsconfig.jsonindex fef4c5361d..97e7e48578 100644--- a/packages/base-sheets/tsconfig.json+++ b/packages/base-sheets/tsconfig.json@@ -29,6 +29,7 @@"jsx": "react-jsx","jsxImportSource": "preact","strictPropertyInitialization": false,+ "noImplicitOverride": true,"types": ["jest","node",diff --git a/packages/core/package.json b/packages/core/package.jsonindex bf955a25b4..05de99bef8 100644--- a/packages/core/package.json+++ b/packages/core/package.json@@ -57,6 +57,7 @@"url": "https://github.com/dream-num/univer.git"},"dependencies": {+ "@wendellhu/redi": "^0.6.5","dayjs": "^1.11.5","es6-proxy-polyfill": "^2.1.1","nanoid": "4.0.0",diff --git a/packages/core/src/Basics/ContextBase.ts b/packages/core/src/Basics/ContextBase.tsindex 4aa1948e01..a63486ea33 100644--- a/packages/core/src/Basics/ContextBase.ts+++ b/packages/core/src/Basics/ContextBase.ts@@ -1,76 +1,79 @@-import { CommandManager, UndoManager } from '../Command';-import { ObservableHooks, ObserverManager } from '../Observer';-import { HooksManager } from '../Observer/HooksManager';-import { Univer } from './Univer';-import { PluginManager } from '../Plugin';-import { Nullable } from '../Shared';-import { Environment } from './Environment';--/**- * Core context, mount important instances, managers- */-export abstract class ContextBase {- protected _commandManager: CommandManager;-- protected _pluginManager: PluginManager;-- protected _environment: Environment;-- protected _hooksManager: HooksManager;-- protected _undoManager: UndoManager;-- protected _observerManager: ObserverManager;-- protected _univer: Univer;-- constructor() {- this._hooksManager = new HooksManager();- this._pluginManager = new PluginManager(this);- this._environment = new Environment();- this._observerManager = new ObserverManager();- this._initialize();- }-- onUniver(univer: Univer): void {- const globalContext = univer.getGlobalContext();- this._univer = univer;- this._undoManager = globalContext.getUndoManager();- this._commandManager = globalContext.getCommandManager();- }-- getHook<T>(path: string): Nullable<ObservableHooks<T>> {- return this._hooksManager.getHooks<T>(path);- }-- getHooksManager(): HooksManager {- return this._hooksManager;- }-- getObserverManager(): ObserverManager {- return this._observerManager;- }-- getPluginManager(): PluginManager {- return this._pluginManager;- }-- getUndoManager(): UndoManager {- return this._undoManager;- }-- getCommandManager(): CommandManager {- return this._commandManager;- }-- getUniver(): Univer {- return this._univer;- }-- protected _initialize(): void {- this._undoManager = new UndoManager();- this._commandManager = new CommandManager(this);- }-- protected abstract _setObserver(): void;-}+import { CommandManager, UndoManager } from '../Command';+import { ObservableHooks, ObserverManager } from '../Observer';+import { HooksManager } from '../Observer/HooksManager';+import { Univer } from './Univer';+import { PluginManager } from '../Plugin';+import { Nullable } from '../Shared';+import { Environment } from './Environment';++/**+ * Core context, mount important instances, managers+ */+export abstract class ContextBase {+ protected _commandManager: CommandManager;++ protected _pluginManager: PluginManager;++ protected _environment: Environment;++ protected _hooksManager: HooksManager;++ protected _undoManager: UndoManager;++ protected _observerManager: ObserverManager;++ protected _univer: Univer;++ constructor() {+ this._hooksManager = new HooksManager();+ this._pluginManager = new PluginManager(this);+ this._environment = new Environment();+ this._observerManager = new ObserverManager();+ this._initialize();+ }++ onUniver(univer: Univer): void {+ const globalContext = univer.getGlobalContext();+ this._univer = univer;+ this._undoManager = globalContext.getUndoManager();+ this._commandManager = globalContext.getCommandManager();+ }++ getHook<T>(path: string): Nullable<ObservableHooks<T>> {+ return this._hooksManager.getHooks<T>(path);+ }++ getHooksManager(): HooksManager {+ return this._hooksManager;+ }++ getObserverManager(): ObserverManager {+ return this._observerManager;+ }++ /** @deprecated DI */+ getPluginManager(): PluginManager {+ return this._pluginManager;+ }++ /** @deprecated DI */+ getUndoManager(): UndoManager {+ return this._undoManager;+ }++ /** @deprecated DI */+ getCommandManager(): CommandManager {+ return this._commandManager;+ }++ getUniver(): Univer {+ return this._univer;+ }++ protected _initialize(): void {+ this._undoManager = new UndoManager();+ this._commandManager = new CommandManager(this);+ }++ protected abstract _setObserver(): void;+}diff --git a/packages/core/src/Command/ActionExtensionFactory.ts b/packages/core/src/Command/ActionExtensionFactory.tsindex c01c81c0e1..3268dbd003 100644--- a/packages/core/src/Command/ActionExtensionFactory.ts+++ b/packages/core/src/Command/ActionExtensionFactory.ts@@ -1,59 +1,59 @@-import { IActionData } from './index';-import { Plugin } from '../Plugin';--/**- * Manipulate the list of actions in a command- */-export class BaseActionExtension<T extends Plugin = Plugin> {- constructor(protected actionDataList: IActionData[], protected _plugin: T) {}-- getActionDataList(): IActionData[] {- return this.actionDataList;- }-- /**- * Must use internal method to add action- * @param actionData- */- push(actionData: IActionData) {- this.actionDataList.push(actionData);- }-- /**- * Modify the data of action- */- setValue() {}-- /**- * Execute the core logic after the check is successful- */- execute() {}-}--/**- * Determine whether to intercept and create BaseActionExtension- */-export class BaseActionExtensionFactory<T extends Plugin = Plugin> {- constructor(protected _plugin: T) {}-- get zIndex() {- return 0;- }-- /**- * Generate Action Extension- * @param actionDataList- * @returns- */- create(actionDataList: IActionData[]): BaseActionExtension<T> {- return new BaseActionExtension(actionDataList, this._plugin);- }-- /**- * Intercept actionDataList- * @returns- */- check(actionDataList: IActionData[]): false | BaseActionExtension<T> {- return this.create(actionDataList);- }-}+import { IActionData } from './index';+import { Plugin } from '../Plugin';++/**+ * Manipulate the list of actions in a command+ */+export class BaseActionExtension<T extends Plugin = Plugin> {+ constructor(protected actionDataList: IActionData[], protected _plugin: T) {}++ getActionDataList(): IActionData[] {+ return this.actionDataList;+ }++ /**+ * Must use internal method to add action+ * @param actionData+ */+ push(actionData: IActionData) {+ this.actionDataList.push(actionData);+ }++ /**+ * Modify the data of action+ */+ setValue() {}++ /**+ * Execute the core logic after the check is successful+ */+ execute() {}+}++/**+ * Determine whether to intercept and create BaseActionExtension+ */+export class BaseActionExtensionFactory<T extends Plugin = Plugin> {+ constructor(protected _plugin: T) {}++ get zIndex() {+ return 0;+ }++ /**+ * Generate Action Extension+ * @param actionDataList+ * @returns+ */+ create(actionDataList: IActionData[]): BaseActionExtension<T> {+ return new BaseActionExtension(actionDataList, this._plugin);+ }++ /**+ * Intercept actionDataList+ * @returns+ */+ check(actionDataList: IActionData[]): false | BaseActionExtension<T> {+ return this.create(actionDataList);+ }+}diff --git a/packages/core/src/IOC/accessor.ts b/packages/core/src/IOC/accessor.tsnew file mode 100644index 0000000000..4878e1c61a--- /dev/null+++ b/packages/core/src/IOC/accessor.ts@@ -0,0 +1,5 @@+import { Injector } from '@wendellhu/redi';++export interface Accessor {+ get: Injector['get'];+}