Skip to content

Build your own AI office with Univer Office SDK. Bring editing, calculation, collaboration, and file processing into your product for people and AI agents. Built on an extensible open-source core.

fix: selection expand with shift (#4166)

lumix22facae1557f
diff --git a/packages/sheets-formula-ui/src/controllers/prompt.controller.ts b/packages/sheets-formula-ui/src/controllers/prompt.controller.ts
index 4ae77684e7..1e2af01479 100644
--- a/packages/sheets-formula-ui/src/controllers/prompt.controller.ts
+++ b/packages/sheets-formula-ui/src/controllers/prompt.controller.ts
@@ -82,6 +82,7 @@ import {
DISABLE_NORMAL_SELECTIONS,
getPrimaryForRange,
IRefSelectionsService,
+ SelectionMoveType,
setEndForRange,
SheetsSelectionsService,
} from '@univerjs/sheets';
@@ -464,7 +465,7 @@ export class PromptController extends Disposable {
}
this._onSelectionControlChange(toRange, c);
}));
- d.add(merge(c.selectionMoved$, c.selectionScaled$).subscribe(() => {
+ d.add(merge(c.selectionMoveEnd$, c.selectionScaled$).subscribe(() => {
this._formulaPromptService.disableLockedSelectionChange();
}));
});
@@ -906,7 +907,7 @@ export class PromptController extends Disposable {
const bodyList = this._getFormulaAndCellEditorBody(unitIds).filter((b) => !!b);
- this._refSelectionsService.clear();
+ // this._refSelectionsService.clear();
if (sequenceNodes == null || sequenceNodes.length === 0) {
this._existsSequenceNode = false;
@@ -1004,9 +1005,9 @@ export class PromptController extends Disposable {
private _refreshSelectionForReference(refSelectionRenderService: RefSelectionsRenderService, refSelections: IRefSelection[]) {
// const [unitId, sheetId] = refSelectionRenderService.getLocation();
const { unitId, sheetId } = this._editorBridgeService.getEditCellState()!;
- const { unitId: selfUnitId, sheetId: selfSheetId } = this._getCurrentUnitIdAndSheetId();
+ const { unitId: selfUnitId, sheetId: currSheetId } = this._getCurrentUnitIdAndSheetId();
- const isSelfSheet = sheetId === selfSheetId;
+ const isSelfSheet = sheetId === currSheetId;
const workbook = this._univerInstanceService.getUniverSheetInstance(unitId)!;
const worksheet = workbook.getSheetBySheetId(sheetId)!;
@@ -1033,7 +1034,7 @@ export class PromptController extends Disposable {
const refSheetId = this._getSheetIdByName(unitId, sheetName.trim());
// Cross sheet operation
- if (!isSelfSheet && refSheetId !== selfSheetId) continue;
+ if (!isSelfSheet && refSheetId !== currSheetId) continue;
// Current sheet operation
if (isSelfSheet && sheetName.length !== 0 && refSheetId !== sheetId) continue;
@@ -1071,9 +1072,8 @@ export class PromptController extends Disposable {
// if (lastRange) {
// selectionWithStyle.push(lastRange);
// }
-
if (selectionWithStyle.length) {
- this._refSelectionsService.addSelections(unitId, sheetId, selectionWithStyle);
+ this._refSelectionsService.setSelections(unitId, currSheetId, selectionWithStyle, SelectionMoveType.ONLY_SET);
}
}
@@ -1242,7 +1242,7 @@ export class PromptController extends Disposable {
* @param sequenceNodes
* @param textSelectionOffset
*/
- // eslint-disable-next-line max-lines-per-function
+
private _syncToEditor(
sequenceNodes: Array<string | ISequenceNode>,
textSelectionOffset: number,
@@ -1405,6 +1405,12 @@ export class PromptController extends Disposable {
return;
}
+ const { skeleton } = this._getCurrentUnitIdAndSheetId();
+ const unitId = skeleton?.worksheet.getUnitId();
+ const sheetId = skeleton?.worksheet.getSheetId();
+ currentSelection.range.sheetId = sheetId;
+ currentSelection.range.unitId = unitId;
+
const refString = this._generateRefString(currentSelection);
this._formulaPromptService.setSequenceNodes(insertNodes);
this._formulaPromptService.insertSequenceRef(this._previousInsertRefStringIndex, refString);
@@ -1542,7 +1548,6 @@ export class PromptController extends Disposable {
}
}
- // eslint-disable-next-line max-lines-per-function
private _onSelectionControlChange(toRange: IRangeWithCoord, selectionControl: SelectionControl) {
// FIXME: change here
const { skeleton } = this._getCurrentUnitIdAndSheetId();
@@ -1759,7 +1764,6 @@ export class PromptController extends Disposable {
}
}
- // eslint-disable-next-line max-lines-per-function
private _commandExecutedListener() {
// Listen to document edits to refresh the size of the editor.
const updateCommandList = [SelectEditorFormulaOperation.id];
@@ -1832,7 +1836,7 @@ export class PromptController extends Disposable {
const selectionData = this._sheetsSelectionsService.getCurrentLastSelection();
if (selectionData != null) {
const selectionDataNew = Tools.deepClone(selectionData);
- this._refSelectionsService.addSelections([selectionDataNew]);
+ this._refSelectionsService.setSelections([selectionDataNew]);
}
}
@@ -2010,7 +2014,9 @@ export class PromptController extends Disposable {
}
private _getEditorObject() {
- const editorUnitId = this._univerInstanceService.getCurrentUniverDocInstance()!.getUnitId();
+ const docInstance = this._univerInstanceService.getCurrentUniverDocInstance();
+ if (!docInstance) return;
+ const editorUnitId = docInstance.getUnitId();
const editor = this._editorService.getEditor(editorUnitId);
return editor?.render;
}
diff --git a/packages/sheets-formula-ui/src/services/render-services/ref-selections.render-service.ts b/packages/sheets-formula-ui/src/services/render-services/ref-selections.render-service.ts
index 64299eef73..b4fb61359c 100644
--- a/packages/sheets-formula-ui/src/services/render-services/ref-selections.render-service.ts
+++ b/packages/sheets-formula-ui/src/services/render-services/ref-selections.render-service.ts
@@ -178,6 +178,19 @@ export class RefSelectionsRenderService extends BaseSelectionRenderService imple
return control;
}
+ private _initSelectionChangeListener(): void {
+ // used for refresh selection when focus in formula editor.
+ // TODO @lumixraku The response of the formula selection to keyboard events is different from that of a regular selection; I believe they should be consistent.
+ // unlike normal selection, there is no need to listen selectionService.selectionMoveEnd$ for keyboard moving event. prompt@highlightFormula would refresh selection.
+ this.disposeWithMe(this._refSelectionsService.selectionSet$.subscribe((selectionsWithStyles) => {
+ this._reset();
+ const skeleton = this._skeleton;
+ if (!skeleton) return;
+ // The selections' style would be colorful here. PromptController would change the color of selections later.
+ this.resetSelectionsByModelData(selectionsWithStyles || []);
+ }));
+ }
+
/**
* Update selectionModel in this._workbookSelections by user action in spreadsheet area.
*/
@@ -205,22 +218,6 @@ export class RefSelectionsRenderService extends BaseSelectionRenderService imple
);
}
- private _initSelectionChangeListener(): void {
- // selectionMoveEnd$ beforeSelectionMoveEnd$ was triggered when pointerup after dragging to change selection area.
- // Changing the selection area through the 8 control points of the ref selection will not trigger this subscriber.
-
- // beforeSelectionMoveEnd$ & selectionMoveEnd$ would triggered when change skeleton(change sheet).
- this.disposeWithMe(this._workbookSelections.selectionSet$.subscribe((selectionsWithStyles) => {
- this._reset();
- const skeleton = this._skeleton;
- if (!skeleton) return;
- // The selections' style would be colorful here. PromptController would change the color of selections later.
- for (const selectionWithStyle of selectionsWithStyles) {
- this._addSelectionControlByModelData(selectionWithStyle);
- }
- }));
- }
-
private _initSkeletonChangeListener(): void {
// changing sheet is not the only way cause currentSkeleton$ emit, a lot of cmds will emit currentSkeleton$
// COMMAND_LISTENER_SKELETON_CHANGE ---> currentSkeleton$.next
@@ -266,7 +263,7 @@ export class RefSelectionsRenderService extends BaseSelectionRenderService imple
* @param viewport
* @param scrollTimerType
*/
- // eslint-disable-next-line max-lines-per-function, complexity
+ // eslint-disable-next-line complexity
protected _onPointerDown(
evt: IPointerEvent | IMouseEvent,
_zIndex = 0,
diff --git a/packages/sheets-ui/src/commands/commands/auto-fill.command.ts b/packages/sheets-ui/src/commands/commands/auto-fill.command.ts
index 405ffc8fe3..7d774c195b 100644
--- a/packages/sheets-ui/src/commands/commands/auto-fill.command.ts
+++ b/packages/sheets-ui/src/commands/commands/auto-fill.command.ts
@@ -15,7 +15,7 @@
*/
import type { IAccessor, ICommand, IRange } from '@univerjs/core';
-import type { ISetRangeValuesMutationParams } from '@univerjs/sheets';
+import type { ISetRangeValuesMutationParams, ISetSelectionsOperationParams } from '@univerjs/sheets';
import { CommandType, ICommandService, IUndoRedoService, IUniverInstanceService, sequenceExecute } from '@univerjs/core';
import { generateNullCellValue, getSheetCommandTarget, SetRangeValuesMutation, SetRangeValuesUndoMutationFactory, SetSelectionsOperation, SheetInterceptorService } from '@univerjs/sheets';
@@ -66,7 +66,7 @@ export const AutoClearContentCommand: ICommand = {
clearMutationParams
);
const { startColumn, startRow } = selectionRange;
- commandService.executeCommand(SetSelectionsOperation.id, {
+ const param: ISetSelectionsOperationParams = {
selections: [
{
primary: {
@@ -76,7 +76,7 @@ export const AutoClearContentCommand: ICommand = {
endRow: startRow,
actualRow: startRow,
actualColumn: startColumn,
- isMerge: false,
+ isMerged: false,
isMergedMainCell: false,
},
range: {
@@ -86,7 +86,8 @@ export const AutoClearContentCommand: ICommand = {
],
unitId,
subUnitId,
- });
+ };
+ commandService.executeCommand(SetSelectionsOperation.id, param);
const result = commandService.syncExecuteCommand(SetRangeValuesMutation.id, clearMutationParams);
if (result) {
diff --git a/packages/sheets-ui/src/commands/commands/set-selection.command.ts b/packages/sheets-ui/src/commands/commands/set-selection.command.ts
index dd45967dab..0b14d8457f 100644
--- a/packages/sheets-ui/src/commands/commands/set-selection.command.ts
+++ b/packages/sheets-ui/src/commands/commands/set-selection.command.ts
@@ -15,14 +15,17 @@
*/
import type { Direction, ICommand, IRange } from '@univerjs/core';
+import type {
+ ISetSelectionsOperationParams } from '@univerjs/sheets';
import { CommandType, ICommandService, IUniverInstanceService, RANGE_TYPE, Rectangle, Tools } from '@univerjs/core';
-import { IRenderManagerService } from '@univerjs/engine-render';
+import { IRenderManagerService } from '@univerjs/engine-render';
import {
expandToContinuousRange,
getCellAtRowCol,
getSelectionsService,
getSheetCommandTarget,
+ SelectionMoveType,
SetSelectionsOperation,
} from '@univerjs/sheets';
import { KeyCode } from '@univerjs/ui';
@@ -62,7 +65,7 @@ export interface IMoveSelectionEnterAndTabCommandParams {
}
/**
- * Move selection (Mainly by keyboard arrow keys, Tab and Enter key see MoveSelectionEnterAndTabCommand)
+ * Move selection (Mainly by keyboard arrow keys, For Tab and Enter key, check @MoveSelectionEnterAndTabCommand)
*/
export const MoveSelectionCommand: ICommand<IMoveSelectionCommandParams> = {
id: 'sheet.command.move-selection',
@@ -120,15 +123,12 @@ export const MoveSelectionCommand: ICommand<IMoveSelectionCommandParams> = {
},
},
];
-
const rs = accessor.get(ICommandService).executeCommand(SetSelectionsOperation.id, {
unitId: workbook.getUnitId(),
subUnitId: worksheet.getSheetId(),
selections,
- });
- const renderManagerService = accessor.get(IRenderManagerService);
- const selectionService = renderManagerService.getRenderById(unitId)?.with(ISheetSelectionRenderService);
- selectionService?.refreshSelectionMoveEnd();
+ type: SelectionMoveType.MOVE_END,
+ } as ISetSelectionsOperationParams);
return rs;
},
};
@@ -139,7 +139,7 @@ export const MoveSelectionCommand: ICommand<IMoveSelectionCommandParams> = {
export const MoveSelectionEnterAndTabCommand: ICommand<IMoveSelectionEnterAndTabCommandParams> = {
id: 'sheet.command.move-selection-enter-tab',
type: CommandType.COMMAND,
- // eslint-disable-next-line max-lines-per-function
+
handler: async (accessor, params) => {
if (!params) {
return false;
@@ -270,7 +270,7 @@ export const MoveSelectionEnterAndTabCommand: ICommand<IMoveSelectionEnterAndTab
const rs = accessor.get(ICommandService).executeCommand(SetSelectionsOperation.id, {
unitId,
subUnitId: sheetId,
-
+ type: SelectionMoveType.MOVE_END,
selections: [resultRange],
});
const renderManagerService = accessor.get(IRenderManagerService);
@@ -318,6 +318,7 @@ export const ExpandSelectionCommand: ICommand<IExpandSelectionCommandParams> = {
worksheet
)
: shrinkToNextCell(startRange, direction, worksheet);
+ destRange.rangeType = selection.range.rangeType;
if (Rectangle.equals(destRange, startRange)) {
return false;
@@ -326,7 +327,7 @@ export const ExpandSelectionCommand: ICommand<IExpandSelectionCommandParams> = {
return accessor.get(ICommandService).executeCommand(SetSelectionsOperation.id, {
unitId,
subUnitId,
-
+ type: SelectionMoveType.ONLY_SET,
selections: [
{
range: destRange,
diff --git a/packages/sheets-ui/src/controllers/clipboard/utils.ts b/packages/sheets-ui/src/controllers/clipboard/utils.ts
index 7143e7e47f..74d39ee35d 100644
--- a/packages/sheets-ui/src/controllers/clipboard/utils.ts
+++ b/packages/sheets-ui/src/controllers/clipboard/utils.ts
@@ -34,6 +34,7 @@ import {
MoveRangeMutation,
RemoveMergeUndoMutationFactory,
RemoveWorksheetMergeMutation,
+ SelectionMoveType,
SetRangeValuesMutation,
SetRangeValuesUndoMutationFactory,
SetSelectionsOperation,
@@ -256,8 +257,8 @@ export function getMoveRangeMutations(
params: {
unitId,
subUnitId: toSubUnitId,
-
selections: [{ range: toRange }],
+ type: SelectionMoveType.MOVE_END,
} as ISetSelectionsOperationParams,
},
];
@@ -270,7 +271,7 @@ export function getMoveRangeMutations(
params: {
unitId,
subUnitId: fromSubUnitId,
-
+ type: SelectionMoveType.MOVE_END,
selections: [{ range: fromRange }],
},
},
diff --git a/packages/sheets-ui/src/controllers/defined-name/defined-name.controller.ts b/packages/sheets-ui/src/controllers/defined-name/defined-name.controller.ts
index 7f7ca6b2b9..48d089178d 100644
--- a/packages/sheets-ui/src/controllers/defined-name/defined-name.controller.ts
+++ b/packages/sheets-ui/src/controllers/defined-name/defined-name.controller.ts
@@ -39,7 +39,8 @@ export class SheetsDefinedNameController extends Disposable {
this.disposeWithMe(merge(
this._selectionManagerService.selectionMoveStart$,
this._selectionManagerService.selectionMoving$,
- this._selectionManagerService.selectionMoveEnd$
+ this._selectionManagerService.selectionMoveEnd$,
+ this._selectionManagerService.selectionSet$
)
.pipe(filter((params) => !!params))
.subscribe((params) => {
diff --git a/packages/sheets-ui/src/controllers/menu/permission-menu-util.ts b/packages/sheets-ui/src/controllers/menu/permission-menu-util.ts
index 68b9cfcb89..b306fbf9de 100644
--- a/packages/sheets-ui/src/controllers/menu/permission-menu-util.ts
+++ b/packages/sheets-ui/src/controllers/menu/permission-menu-util.ts
@@ -502,4 +502,3 @@ export function getViewPermissionDisable$(accessor: IAccessor) {
})
);
}
-
diff --git a/packages/sheets-ui/src/controllers/move-range.controller.ts b/packages/sheets-ui/src/controllers/move-range.controller.ts
index 500c64f64e..97525e6ee8 100644
--- a/packages/sheets-ui/src/controllers/move-range.controller.ts
+++ b/packages/sheets-ui/src/controllers/move-range.controller.ts
@@ -15,6 +15,8 @@
*/
import type { IRange, Workbook } from '@univerjs/core';
+import type { IRenderContext, IRenderModule } from '@univerjs/engine-render';
+import type { IMoveRangeCommandParams } from '@univerjs/sheets';
import {
Disposable,
DisposableCollection,
@@ -22,10 +24,8 @@ import {
Inject,
toDisposable,
} from '@univerjs/core';
-import type { IMoveRangeCommandParams } from '@univerjs/sheets';
-import { MoveRangeCommand, SheetsSelectionsService } from '@univerjs/sheets';
-import type { IRenderContext, IRenderModule } from '@univerjs/engine-render';
+import { MoveRangeCommand, SheetsSelectionsService } from '@univerjs/sheets';
import { ISheetSelectionRenderService } from '../services/selection/base-selection-render.service';
export class MoveRangeRenderController extends Disposable implements IRenderModule {
@@ -51,7 +51,7 @@ export class MoveRangeRenderController extends Disposable implements IRenderModu
selectionControls.forEach((controlSelection) => {
disposableCollection.add(
toDisposable(
- controlSelection.selectionMoved$.subscribe((_toRange) => {
+ controlSelection.selectionMoveEnd$.subscribe((_toRange) => {
if (!_toRange) {
return;
}
diff --git a/packages/sheets-ui/src/controllers/utils/selections-tools.ts b/packages/sheets-ui/src/controllers/utils/selections-tools.ts
index cb4275ddd8..8379e9c3e6 100644
--- a/packages/sheets-ui/src/controllers/utils/selections-tools.ts
+++ b/packages/sheets-ui/src/controllers/utils/selections-tools.ts
@@ -15,8 +15,8 @@
*/
import type { IAccessor, Nullable, Workbook } from '@univerjs/core';
-import { IUniverInstanceService, RANGE_TYPE, Rectangle, UniverInstanceType } from '@univerjs/core';
import type { ISelectionWithStyle } from '@univerjs/sheets';
+import { IUniverInstanceService, RANGE_TYPE, Rectangle, UniverInstanceType } from '@univerjs/core';
import { MERGE_CELL_INTERCEPTOR_CHECK, MergeCellController, RangeProtectionRuleModel, SheetsSelectionsService } from '@univerjs/sheets';
import { combineLatest, map, of, switchMap } from 'rxjs';
@@ -45,7 +45,8 @@ export function getSheetSelectionsDisabled$(accessor: IAccessor) {
}
const subUnitRuleRange = rangeProtectionRuleModel.getSubunitRuleList(unitId, subUnitId)
- .map((rule) => rule.ranges).flat();
+ .map((rule) => rule.ranges)
+ .flat();
if (selection.length < 2) {
const range = selection[0].range;
diff --git a/packages/sheets-ui/src/services/selection/base-selection-render.service.ts b/packages/sheets-ui/src/services/selection/base-selection-render.service.ts
index 10ba168131..6055eca236 100644
--- a/packages/sheets-ui/src/services/selection/base-selection-render.service.ts
+++ b/packages/sheets-ui/src/services/selection/base-selection-render.service.ts
@@ -154,16 +154,21 @@ export class BaseSelectionRenderService extends Disposable implements ISheetSele
// #endregion
/**
- * Mainly emit by pointerup (pointerup is handled in _onPointerdown)
+ * Mainly emit by pointerup in spreadsheet. (pointerup is handled in _onPointerdown)
*/
protected readonly _selectionMoveEnd$ = new BehaviorSubject<ISelectionWithCoord[]>([]);
+ /**
+ * Pointerup in spreadsheet
+ */
readonly selectionMoveEnd$ = this._selectionMoveEnd$.asObservable();
+ /**
+ * Mainly emit by pointermove in spreadsheet
+ */
protected readonly _selectionMoving$ = new Subject<ISelectionWithCoord[]>();
- readonly selectionMoving$ = this._selectionMoving$.asObservable();
-
/**
- * Mainly emit by pointerdown
+ * Pointermove in spreadsheet
*/
+ readonly selectionMoving$ = this._selectionMoving$.asObservable();
protected readonly _selectionMoveStart$ = new Subject<ISelectionWithCoord[]>();
readonly selectionMoveStart$ = this._selectionMoveStart$.asObservable();
@@ -425,13 +430,6 @@ export class BaseSelectionRenderService extends Disposable implements ISheetSele
this._downObserver = null;
}
- // resetAndEndSelection(): void {
- // this.endSelection();
- // this._reset();
- // }
-
- // TODO: @wzhudev: refactor the method to make it more readable
-
/**
* Init pointer move listener in each pointer down, unbind in each pointer up.
* Both cell selections and row-column selections are supported by this method.
@@ -442,7 +440,7 @@ export class BaseSelectionRenderService extends Disposable implements ISheetSele
* @param moveStartPosX
* @param moveStartPosY
*/
- // eslint-disable-next-line max-lines-per-function
+
protected _setupPointerMoveListener(
viewportMain: Nullable<Viewport>,
activeSelectionControl: SelectionControl,
@@ -462,7 +460,7 @@ export class BaseSelectionRenderService extends Disposable implements ISheetSele
const startViewport = scene.getActiveViewportByCoord(Vector2.FromArray([moveStartPosX, moveStartPosY]));
// #region onPointerMove$
- // eslint-disable-next-line max-lines-per-function, complexity
+ // eslint-disable-next-line complexity
this._scenePointerMoveSub = scene.onPointerMove$.subscribeEvent((moveEvt: IPointerEvent | IMouseEvent) => {
const { offsetX: moveOffsetX, offsetY: moveOffsetY } = moveEvt;
diff --git a/packages/sheets-ui/src/services/selection/selection-control.ts b/packages/sheets-ui/src/services/selection/selection-control.ts
index be2e5a7626..ded5dc32d6 100644
--- a/packages/sheets-ui/src/services/selection/selection-control.ts
+++ b/packages/sheets-ui/src/services/selection/selection-control.ts
@@ -133,7 +133,6 @@ export class SelectionControl extends Disposable {
protected _columnHeaderHeight: number = 0;
protected _widgetRects: Rect[] = [];
-
protected _controlExtension: Nullable<SelectionShapeExtension>;
private _dispose$ = new BehaviorSubject<SelectionControl>(this);
@@ -144,7 +143,7 @@ export class SelectionControl extends Disposable {
* Observer: prompt.controller
*/
readonly selectionMoving$ = new Subject<IRangeWithCoord>();
- readonly selectionMoved$ = new Subject<IRangeWithCoord>();
+ readonly selectionMoveEnd$ = new Subject<IRangeWithCoord>();
readonly selectionScaling$ = new Subject<IRangeWithCoord>();
readonly selectionScaled$ = new Subject<Nullable<IRangeWithCoord>>();
readonly selectionFilling$ = new Subject<Nullable<IRangeWithCoord>>();
@@ -173,7 +172,6 @@ export class SelectionControl extends Disposable {
this._initialHeader();
}
- // eslint-disable-next-line max-lines-per-function
private _initializeSheetBody(): void {
this._defaultStyle = genNormalSelectionStyle(this._themeService);
this._currentStyle = genNormalSelectionStyle(this._themeService);
@@ -517,7 +515,7 @@ export class SelectionControl extends Disposable {
* Update Control Style And Position of SelectionControl
* @param selectionStyle
*/
- // eslint-disable-next-line max-lines-per-function
+
protected _updateLayoutOfSelectionControl(selectionStyle?: Nullable<Partial<ISelectionStyle>>): void {
if (selectionStyle) {
this.currentStyle = Object.assign({}, this._defaultStyle, selectionStyle);
@@ -690,6 +688,8 @@ export class SelectionControl extends Disposable {
/**
* Update selection model with new range & primary cell(aka: highlight/current), also update row/col selection size & style.
*
+ * @deprecated use `updateRangeBySelectionWithCoord` and `updateStyle` to do same thing.
+ *
* @param newSelectionRange
* @param rowHeaderWidth
* @param columnHeaderHeight
diff --git a/packages/sheets-ui/src/services/selection/selection-render.service.ts b/packages/sheets-ui/src/services/selection/selection-render.service.ts
index 2ecd5c8a1f..76d446b9da 100644
--- a/packages/sheets-ui/src/services/selection/selection-render.service.ts
+++ b/packages/sheets-ui/src/services/selection/selection-render.service.ts
@@ -23,7 +23,7 @@ import { ICommandService, IContextService, ILogService, Inject, Injector, RANGE_
import { ScrollTimerType, SHEET_VIEWPORT_KEY, Vector2 } from '@univerjs/engine-render';
import { convertSelectionDataToRange, DISABLE_NORMAL_SELECTIONS, SelectionMoveType, SetSelectionsOperation, SheetsSelectionsService } from '@univerjs/sheets';
import { IShortcutService } from '@univerjs/ui';
-import { distinctUntilChanged, startWith } from 'rxjs';
+import { distinctUntilChanged, merge, startWith } from 'rxjs';
import { getCoordByOffset, getSheetObject } from '../../controllers/utils/component-tools';
import { isThisColSelected, isThisRowSelected } from '../../controllers/utils/selections-tools';
import { SheetSkeletonManagerService } from '../sheet-skeleton-manager.service';
@@ -66,7 +66,7 @@ export class SheetSelectionRenderService extends BaseSelectionRenderService impl
const sheetObject = this._getSheetObject();
this._initEventListeners(sheetObject);
- this._initSelectionChangeListener();
+ this._initSelectionModelChangeListener();
this._initThemeChangeListener();
this._initSkeletonChangeListener();
this._initUserActionSyncListener();
@@ -144,13 +144,21 @@ export class SheetSelectionRenderService extends BaseSelectionRenderService impl
return this._contextService.getContextValue(DISABLE_NORMAL_SELECTIONS);
}
- private _initSelectionChangeListener(): void {
- // normal selection: after dragging selection(move end)
- this.disposeWithMe(this._workbookSelections.selectionMoveEnd$.subscribe((selectionWithStyleList) => {
+ /**
+ * Response for selection model changing.
+ */
+ private _initSelectionModelChangeListener(): void {
+ this.disposeWithMe(merge(
+ this._workbookSelections.selectionMoveEnd$, // triggered by keyboard(e.g. arrow key tab enter)
+ this._workbookSelections.selectionSet$ // shift + arrow key
+ ).subscribe((selectionWithStyleList) => {
this.resetSelectionsByModelData(selectionWithStyleList);
}));
}
+ /**
+ * Handle events in spreadsheet. (e.g. drag and move to make a selection)
+ */
private _initUserActionSyncListener(): void {
this.disposeWithMe(this.selectionMoveStart$.subscribe((params) => this._updateSelections(params, SelectionMoveType.MOVE_START)));
this.disposeWithMe(this.selectionMoving$.subscribe((params) => this._updateSelections(params, SelectionMoveType.MOVING)));
@@ -164,7 +172,9 @@ export class SheetSelectionRenderService extends BaseSelectionRenderService impl
this._reset();
} else {
this._renderDisposable = toDisposable(
- this.selectionMoveEnd$.subscribe((params) => this._updateSelections(params, SelectionMoveType.MOVE_END))
+ this.selectionMoveEnd$.subscribe((params) => {
+ this._updateSelections(params, SelectionMoveType.MOVE_END);
+ })
);
}
}));
@@ -184,13 +194,15 @@ export class SheetSelectionRenderService extends BaseSelectionRenderService impl
return;
}
+ const selectionWithStyles = selectionDataWithStyleList.map((selectionDataWithStyle) =>
+ convertSelectionDataToRange(selectionDataWithStyle)
+ );
+
this._commandService.executeCommand(SetSelectionsOperation.id, {
unitId,
subUnitId: sheetId,
type,
- selections: selectionDataWithStyleList.map((selectionDataWithStyle) =>
- convertSelectionDataToRange(selectionDataWithStyle)
- ),
+ selections: selectionWithStyles,
});
}
@@ -253,7 +265,7 @@ export class SheetSelectionRenderService extends BaseSelectionRenderService impl
* @param viewport
* @param scrollTimerType
*/
- // eslint-disable-next-line max-lines-per-function, complexity
+ // eslint-disable-next-line complexity
protected _onPointerDown(
evt: IPointerEvent | IMouseEvent,
_zIndex = 0,
diff --git a/packages/sheets-ui/src/services/selection/selection-shape-extension.ts b/packages/sheets-ui/src/services/selection/selection-shape-extension.ts
index f5b1511939..e5246d168c 100644
--- a/packages/sheets-ui/src/services/selection/selection-shape-extension.ts
+++ b/packages/sheets-ui/src/services/selection/selection-shape-extension.ts
@@ -14,16 +14,16 @@
* limitations under the License.
*/
-import type { ISelectionWithStyle } from '@univerjs/sheets';
-import { ColorKit, Quantity, UniverInstanceType } from '@univerjs/core';
-import { CURSOR_TYPE, IRenderManagerService, Rect, ScrollTimer, ScrollTimerType, SHEET_VIEWPORT_KEY, Vector2 } from '@univerjs/engine-render';
-import { SELECTION_CONTROL_BORDER_BUFFER_WIDTH } from '@univerjs/sheets';
-/* eslint-disable max-lines-per-function */
import type { IFreeze, Injector, IRange, IRangeWithCoord, Nullable, ThemeService } from '@univerjs/core';
import type { IMouseEvent, IPointerEvent, Scene, SpreadsheetSkeleton, Viewport } from '@univerjs/engine-render';
-
+import type { ISelectionWithStyle } from '@univerjs/sheets';
import type { Subscription } from 'rxjs';
+
import type { SelectionControl } from './selection-control';
+import { ColorKit, Quantity, UniverInstanceType } from '@univerjs/core';
+
+import { CURSOR_TYPE, IRenderManagerService, Rect, ScrollTimer, ScrollTimerType, SHEET_VIEWPORT_KEY, Vector2 } from '@univerjs/engine-render';
+import { SELECTION_CONTROL_BORDER_BUFFER_WIDTH } from '@univerjs/sheets';
import { SheetSkeletonManagerService } from '../sheet-skeleton-manager.service';
import { ISheetSelectionRenderService } from './base-selection-render.service';
import { genNormalSelectionStyle, RANGE_FILL_PERMISSION_CHECK, RANGE_MOVE_PERMISSION_CHECK } from './const';
@@ -192,7 +192,7 @@ export class SelectionShapeExtension {
control.resetCursor();
});
- control.onPointerDown$.subscribeEvent(this._controlEvent.bind(this));
+ control.onPointerDown$.subscribeEvent(this._controlPointerDownHandler.bind(this));
});
}
@@ -267,7 +267,7 @@ export class SelectionShapeExtension {
* Drag move whole selectionControl when cursor turns to crosshair. Not for dragging 8 control points.
* @param evt
*/
- private _controlEvent(evt: IMouseEvent | IPointerEvent) {
+ private _controlPointerDownHandler(evt: IMouseEvent | IPointerEvent) {
const { offsetX: evtOffsetX, offsetY: evtOffsetY } = evt;
const scene = this._scene;
@@ -370,10 +370,9 @@ export class SelectionShapeExtension {
this._clearObserverEvent();
scene.enableObjectsEvent();
this._scrollTimer?.dispose();
- this._control.selectionMoved$.next(this._targetSelection);
+ this._control.selectionMoveEnd$.next(this._targetSelection);
- // _selectionHooks.selectionMoveEnd should placed after this._control.selectionMoved$,
- // because selectionMoveEnd will dispose all selectionControls, then this._control will be null.
+ // _selectionHooks.selectionMoveEnd should placed after this._control.selectionMoveEnd$
this._selectionHooks.selectionMoveEnd?.();
});
}
@@ -504,8 +503,7 @@ export class SelectionShapeExtension {
this._scrollTimer?.dispose();
this._control.selectionScaled$.next(this._targetSelection);
- // _selectionHooks.selectionMoveEnd should placed after this._control.selectionMoved$,
- // because selectionMoveEnd will dispose all selectionControls, then this._control will be null.
+ // _selectionHooks.selectionMoveEnd should placed after this._control.selectionMoveEnd$,
this._selectionHooks.selectionMoveEnd?.();
});
}
diff --git a/packages/sheets-ui/src/views/formula-bar/FormulaBar.tsx b/packages/sheets-ui/src/views/formula-bar/FormulaBar.tsx
index 5180524ba7..804be38a9e 100644
--- a/packages/sheets-ui/src/views/formula-bar/FormulaBar.tsx
+++ b/packages/sheets-ui/src/views/formula-bar/FormulaBar.tsx
@@ -26,8 +26,8 @@ import React, { useEffect, useLayoutEffect, useState } from 'react';
import { EMPTY, merge, switchMap } from 'rxjs';
import { useActiveWorkbook } from '../../components/hook';
import { SheetsUIPart } from '../../consts/ui-name';
-import { IFormulaEditorManagerService } from '../../services/editor/formula-editor-manager.service';
import { IEditorBridgeService } from '../../services/editor-bridge.service';
+import { IFormulaEditorManagerService } from '../../services/editor/formula-editor-manager.service';
import { DefinedName } from '../defined-name/DefinedName';
import styles from './index.module.less';
@@ -72,7 +72,8 @@ export function FormulaBar() {
return merge(
worksheetProtectionRuleModel.ruleChange$,
rangeProtectionRuleModel.ruleChange$,
- selectionManager.selectionMoveEnd$
+ selectionManager.selectionMoveEnd$,
+ selectionManager.selectionSet$
).pipe(
switchMap(() => {
const unitId = workbook.getUnitId();
diff --git a/packages/sheets/src/basics/selection.ts b/packages/sheets/src/basics/selection.ts
index eb7e1dc648..1393851351 100644
--- a/packages/sheets/src/basics/selection.ts
+++ b/packages/sheets/src/basics/selection.ts
@@ -157,7 +157,7 @@ export interface ISelectionWithStyle extends ISelection {
* if primary is not defined, means not keep current primary cell.
*/
primary: Nullable<ISelectionCell>;
- style: Nullable<Partial<ISelectionStyle>>;
+ style?: Nullable<Partial<ISelectionStyle>>;
}
export interface ISheetRangeLocation {
diff --git a/packages/sheets/src/commands/commands/move-range.command.ts b/packages/sheets/src/commands/commands/move-range.command.ts
index cf3aef8e6d..7f2e62471f 100644
--- a/packages/sheets/src/commands/commands/move-range.command.ts
+++ b/packages/sheets/src/commands/commands/move-range.command.ts
@@ -32,6 +32,7 @@ import {
sequenceExecute,
Tools,
} from '@univerjs/core';
+import { SelectionMoveType } from '../../services/selections/type';
import { SheetInterceptorService } from '../../services/sheet-interceptor/sheet-interceptor.service';
import { MoveRangeMutation } from '../mutations/move-range.mutation';
import { SetSelectionsOperation } from '../operations/selection.operation';
@@ -90,8 +91,8 @@ export const MoveRangeCommand: ICommand = {
params: {
unitId,
subUnitId,
-
selections: [{ range: params.toRange, primary: getPrimaryForRange(params.toRange, worksheet) }],
+ type: SelectionMoveType.MOVE_END,
} as ISetSelectionsOperationParams,
},
];
@@ -104,8 +105,8 @@ export const MoveRangeCommand: ICommand = {
params: {
unitId,
subUnitId,
-
selections: [{ range: params.fromRange, primary: getPrimaryForRange(params.fromRange, worksheet) }],
+ type: SelectionMoveType.MOVE_END,
} as ISetSelectionsOperationParams,
},
];
diff --git a/packages/sheets/src/commands/commands/move-rows-cols.command.ts b/packages/sheets/src/commands/commands/move-rows-cols.command.ts
index 3bb2ead99f..dc9a98f733 100644
--- a/packages/sheets/src/commands/commands/move-rows-cols.command.ts
+++ b/packages/sheets/src/commands/commands/move-rows-cols.command.ts
@@ -31,6 +31,7 @@ import {
sequenceExecute,
} from '@univerjs/core';
import { SheetsSelectionsService } from '../../services/selections/selection.service';
+import { SelectionMoveType } from '../../services/selections/type';
import { SheetInterceptorService } from '../../services/sheet-interceptor/sheet-interceptor.service';
import {
MoveColsMutation,
@@ -65,7 +66,7 @@ export const MoveRowsCommandId = 'sheet.command.move-rows' as const;
export const MoveRowsCommand: ICommand<IMoveRowsCommandParams> = {
id: MoveRowsCommandId,
type: CommandType.COMMAND,
- // eslint-disable-next-line max-lines-per-function
+
handler: async (accessor: IAccessor, params: IMoveRowsCommandParams) => {
const selectionManagerService = accessor.get(SheetsSelectionsService);
const {
@@ -161,13 +162,17 @@ export const MoveRowsCommand: ICommand<IMoveRowsCommandParams> = {
const setSelectionsParam: ISetSelectionsOperationParams = {
unitId,
subUnitId,
-
- selections: [{ range: destSelection, primary: getPrimaryForRange(destSelection, worksheet), style: null }],
+ type: SelectionMoveType.MOVE_END,
+ selections: [{
+ range: destSelection,
+ primary: getPrimaryForRange(destSelection, worksheet),
+ style: null,
+ }],
};
const undoSetSelectionsParam: ISetSelectionsOperationParams = {
unitId,
subUnitId,
-
+ type: SelectionMoveType.MOVE_END,
selections: [{ range: rangeToMove, primary: beforePrimary, style: null }],
};
@@ -206,7 +211,7 @@ export const MoveColsCommandId = 'sheet.command.move-cols' as const;
export const MoveColsCommand: ICommand<IMoveColsCommandParams> = {
id: MoveColsCommandId,
type: CommandType.COMMAND,
- // eslint-disable-next-line max-lines-per-function
+
handler: async (accessor: IAccessor, params: IMoveColsCommandParams) => {
const selectionManagerService = accessor.get(SheetsSelectionsService);
const {
@@ -301,13 +306,13 @@ export const MoveColsCommand: ICommand<IMoveColsCommandParams> = {
const setSelectionsParam: ISetSelectionsOperationParams = {
unitId,
subUnitId,
-
+ type: SelectionMoveType.MOVE_END,
selections: [{ range: destSelection, primary: getPrimaryForRange(destSelection, worksheet), style: null }],
};
const undoSetSelectionsParam: ISetSelectionsOperationParams = {
unitId,
subUnitId,
-
+ type: SelectionMoveType.MOVE_END,
selections: [{ range: rangeToMove, primary: beforePrimary, style: null }],
};
diff --git a/packages/sheets/src/commands/utils/handle-merge-operation.ts b/packages/sheets/src/commands/utils/handle-merge-operation.ts
index ec34b3a4d2..3362458f73 100644
--- a/packages/sheets/src/commands/utils/handle-merge-operation.ts
+++ b/packages/sheets/src/commands/utils/handle-merge-operation.ts
@@ -19,6 +19,7 @@ import type { IAddMergeCommandParams } from '../commands/add-worksheet-merge.com
import type { ISetSelectionsOperationParams } from '../operations/selection.operation';
import { Dimension } from '@univerjs/core';
import { SheetsSelectionsService } from '../../services/selections/selection.service';
+import { SelectionMoveType } from '../../services/selections/type';
import { SetSelectionsOperation } from '../operations/selection.operation';
export const AddMergeRedoSelectionsOperationFactory = (accessor: IAccessor, params: IAddMergeCommandParams, ranges: IRange[]) => {
@@ -66,7 +67,7 @@ export const AddMergeRedoSelectionsOperationFactory = (accessor: IAccessor, para
const setSelectionsParamByRedo: ISetSelectionsOperationParams = {
unitId,
subUnitId,
-
+ type: SelectionMoveType.ONLY_SET,
selections: selectionsByRedo,
};
return {
@@ -90,7 +91,7 @@ export const AddMergeUndoSelectionsOperationFactory = (accessor: IAccessor, para
const setSelectionsParamByUndo: ISetSelectionsOperationParams = {
unitId,
subUnitId,
-
+ type: SelectionMoveType.ONLY_SET,
selections: [...selectionsBeforeMutation],
};
return {
diff --git a/packages/sheets/src/services/selections/ref-selections.service.ts b/packages/sheets/src/services/selections/ref-selections.service.ts
index 59f830ca3a..878c703b3f 100644
--- a/packages/sheets/src/services/selections/ref-selections.service.ts
+++ b/packages/sheets/src/services/selections/ref-selections.service.ts
@@ -45,6 +45,7 @@ export class RefSelectionsService extends SheetsSelectionsService {
this.selectionMoveStart$ = $.pipe(switchMap((ss) => merge(...ss.map((s) => s.selectionMoveStart$))));
this.selectionMoving$ = $.pipe(switchMap((ss) => merge(...ss.map((s) => s.selectionMoving$))));
this.selectionMoveEnd$ = $.pipe(switchMap((ss) => merge(...ss.map((s) => s.selectionMoveEnd$))));
+ this.selectionSet$ = $.pipe(switchMap((ss) => merge(...ss.map((s) => s.selectionSet$))));
}
private _getAliveWorkbooks$(): Observable<WorkbookSelectionModel[]> {
diff --git a/packages/sheets/src/services/selections/selection-data-model.ts b/packages/sheets/src/services/selections/selection-data-model.ts
index ddc81707b1..fc25862df1 100644
--- a/packages/sheets/src/services/selections/selection-data-model.ts
+++ b/packages/sheets/src/services/selections/selection-data-model.ts
@@ -62,16 +62,10 @@ export class WorkbookSelectionModel extends Disposable {
this._selectionSet$.complete();
}
- /** Clear all selections in this workbook. */
- clear(): void {
- this._worksheetSelections.clear();
- this._emitOnEnd([]);
- }
-
addSelections(sheetId: string, selectionDatas: ISelectionWithStyle[]): void {
const selections = this.getSelectionsOfWorksheet(sheetId);
selections.push(...selectionDatas);
- this._emitOnEnd(selections);
+ this._selectionSet$.next(selections);
}
/**
@@ -84,8 +78,8 @@ export class WorkbookSelectionModel extends Disposable {
// selectionDatas should not be same variable as this._worksheetSelections !!!
// but there are some place get selection from this._worksheetSelections and set selectionDatas(2nd parameter of this function ) cause selectionDatas is always []
// see univer/pull/2909
- this.deleteSheetSelection(sheetId);
- this.getSelectionsOfWorksheet(sheetId).push(...selectionDatas);
+ // this.deleteSheetSelection(sheetId);
+ this.setSelectionsOfWorksheet(sheetId, selectionDatas);
switch (type) {
case SelectionMoveType.MOVE_START:
@@ -97,14 +91,13 @@ export class WorkbookSelectionModel extends Disposable {
case SelectionMoveType.MOVE_END:
this._beforeSelectionMoveEnd$.next(selectionDatas);
this._selectionMoveEnd$.next(selectionDatas);
- // this._emitOnEnd(selectionDatas);
break;
case SelectionMoveType.ONLY_SET: {
this._selectionSet$.next(selectionDatas);
break;
}
default:
- this._emitOnEnd(selectionDatas);
+ this._selectionSet$.next(selectionDatas);
break;
}
}
@@ -130,33 +123,30 @@ export class WorkbookSelectionModel extends Disposable {
return this._worksheetSelections.get(sheetId)!;
}
- private _getCurrentSelections(): ISelectionWithStyle[] {
- return this.getSelectionsOfWorksheet(this._workbook.getActiveSheet()!.getSheetId());
+ setSelectionsOfWorksheet(sheetId: string, selections: ISelectionWithStyle[]): void {
+ this._worksheetSelections.set(sheetId, [...selections]);
}
- getCurrentLastSelection(): Readonly<Nullable<ISelectionWithStyle & { primary: ISelectionCell }>> {
- const selectionData = this._getCurrentSelections();
- return selectionData[selectionData.length - 1] as Readonly<Nullable<ISelectionWithStyle & { primary: ISelectionCell }>>;
+ deleteSheetSelection(sheetId: string) {
+ this._worksheetSelections.set(sheetId, []);
}
- /**
- * Same method as getSelectionsOfWorksheet.
- * @param sheetId
- * @returns this._worksheetSelections
- */
- private _ensureSheetSelection(sheetId: string): ISelectionWithStyle[] {
- if (!this._worksheetSelections.get(sheetId)) {
- this._worksheetSelections.set(sheetId, []);
- }
+ /** Clear all selections in this workbook. */
+ clear(): void {
+ this._worksheetSelections.clear();
+ this._eventAfterSetSelections([]);
+ }
- return this._worksheetSelections.get(sheetId)!;
+ private _getCurrentSelections(): ISelectionWithStyle[] {
+ return this.getSelectionsOfWorksheet(this._workbook.getActiveSheet()!.getSheetId());
}
- deleteSheetSelection(sheetId: string) {
- this._worksheetSelections.set(sheetId, []);
+ getCurrentLastSelection(): Readonly<Nullable<ISelectionWithStyle & { primary: ISelectionCell }>> {
+ const selectionData = this._getCurrentSelections();
+ return selectionData[selectionData.length - 1] as Readonly<Nullable<ISelectionWithStyle & { primary: ISelectionCell }>>;
}
- private _emitOnEnd(selections: ISelectionWithStyle[]): void {
+ private _eventAfterSetSelections(selections: ISelectionWithStyle[]): void {
this._selectionSet$.next(selections);
}
}
diff --git a/packages/sheets/src/services/selections/selection.service.ts b/packages/sheets/src/services/selections/selection.service.ts
index 4ff65a5fdb..4f4e52cfd8 100644
--- a/packages/sheets/src/services/selections/selection.service.ts
+++ b/packages/sheets/src/services/selections/selection.service.ts
@@ -37,10 +37,26 @@ export class SheetsSelectionsService extends RxDisposable {
return this._currentSelectionPos;
}
+ /**
+ * Selection Events, usually triggered when pointerdown in spreadsheet by selection render service after selectionModel has updated.
+ */
selectionMoveStart$: Observable<Nullable<ISelectionWithStyle[]>>;
+
+ /**
+ * Selection Events, usually triggered when pointermove in spreadsheet by selection render service after selectionModel has updated.
+ */
selectionMoving$: Observable<Nullable<ISelectionWithStyle[]>>;
+
+ /**
+ * Selection Events, usually triggered when pointerup in spreadsheet by selection render service after selectionModel has updated.
+ */
selectionMoveEnd$: Observable<ISelectionWithStyle[]>;
+ /**
+ * Selection Events, usually triggered when changing unit.(focus in formula editor)
+ */
+ selectionSet$: Observable<Nullable<ISelectionWithStyle[]>>;
+
constructor(
@IUniverInstanceService protected readonly _instanceSrv: IUniverInstanceService
) {
@@ -54,6 +70,7 @@ export class SheetsSelectionsService extends RxDisposable {
this.selectionMoveStart$ = c$.pipe(switchMap((workbook) => !workbook ? of() : this._ensureWorkbookSelection(workbook.getUnitId()).selectionMoveStart$));
this.selectionMoving$ = c$.pipe(switchMap((workbook) => !workbook ? of() : this._ensureWorkbookSelection(workbook.getUnitId()).selectionMoving$));
this.selectionMoveEnd$ = c$.pipe(switchMap((workbook) => !workbook ? of([]) : this._ensureWorkbookSelection(workbook.getUnitId()).selectionMoveEnd$));
+ this.selectionSet$ = c$.pipe(switchMap((workbook) => !workbook ? of([]) : this._ensureWorkbookSelection(workbook.getUnitId()).selectionSet$));
this._instanceSrv.getTypeOfUnitDisposed$(UniverInstanceType.UNIVER_SHEET).pipe(takeUntil(this.dispose$)).subscribe((workbook) => {
this._removeWorkbookSelection(workbook.getUnitId());
@@ -95,7 +112,7 @@ export class SheetsSelectionsService extends RxDisposable {
/**
* Set selection data to WorkbookSelectionModel.
- * If type is not specified, this method would clear all existing selections.
+ *
* @param unitIdOrSelections
* @param worksheetIdOrType
* @param selectionDatas
@@ -110,7 +127,12 @@ export class SheetsSelectionsService extends RxDisposable {
type?: SelectionMoveType
): void {
if (typeof unitIdOrSelections === 'string' && typeof worksheetIdOrType === 'string') {
- this._ensureWorkbookSelection(unitIdOrSelections).setSelections(worksheetIdOrType, selectionDatas!, type ?? SelectionMoveType.MOVE_END);
+ const unitId = unitIdOrSelections as string;
+ this._ensureWorkbookSelection(unitId).setSelections(
+ worksheetIdOrType,
+ selectionDatas || [],
+ type ?? SelectionMoveType.ONLY_SET
+ );
return;
}