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
feat(sheets): animate cell selection transitions (#7791)
白熱bb9079f131bf
diff --git a/packages/sheets-ui/src/services/selection/__tests__/selection-render.service.spec.ts b/packages/sheets-ui/src/services/selection/__tests__/selection-render.service.spec.tsindex 3aabb1da91..f687701cec 100644--- a/packages/sheets-ui/src/services/selection/__tests__/selection-render.service.spec.ts+++ b/packages/sheets-ui/src/services/selection/__tests__/selection-render.service.spec.ts@@ -33,6 +33,7 @@ import {RenderManagerService,SHEET_VIEWPORT_KEY,Spreadsheet,+ Vector2,Viewport,} from '@univerjs/engine-render';import {@@ -51,7 +52,7 @@ import {} from '@univerjs/ui';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';-import { SHEET_VIEW_KEY } from '../../../common/keys';+import { SHEET_COMPONENT_MAIN_LAYER_INDEX, SHEET_VIEW_KEY } from '../../../common/keys';import { createRenderTestBed } from '../../../controllers/render-controllers/__tests__/render-test-bed';import { SheetSkeletonManagerService } from '../../sheet-skeleton-manager.service';import { SheetSelectionRenderService } from '../selection-render.service';@@ -271,7 +272,7 @@ describe('SheetSelectionRenderService', () => {});});-describe('SheetSelectionRenderService additive pointer modifiers with real render providers', () => {+describe('SheetSelectionRenderService pointer gestures with real render providers', () => {let univer: Univer;beforeEach(() => {@@ -304,13 +305,13 @@ describe('SheetSelectionRenderService additive pointer modifiers with real rendevi.useRealTimers();});- function createSelectionTestBed(mergeData: IRange[] = []) {+ function createSelectionTestBed(mergeData: IRange[] = [], rowCount = 20) {const injector = univer.__getInjector();const workbook = univer.createUnit<IWorkbookData, Workbook>(UniverInstanceType.UNIVER_SHEET, {id: 'pointer-modifiers',name: 'Pointer modifiers',sheetOrder: ['sheet1'],- sheets: { sheet1: { id: 'sheet1', name: 'Sheet 1', rowCount: 20, columnCount: 10, cellData: {}, mergeData } },+ sheets: { sheet1: { id: 'sheet1', name: 'Sheet 1', rowCount, columnCount: 10, cellData: {}, mergeData } },});const renderManager = injector.get(IRenderManagerService);const render = renderManager.createRender(workbook.getUnitId());@@ -345,6 +346,130 @@ describe('SheetSelectionRenderService additive pointer modifiers with real rendereturn { injector, workbook, render, spreadsheet, service, skeleton, getSelections, eventAt, click };}+ it.each([20, 1_000_000])('animates clicks without delaying selection or invalidating sheet content with %i rows', (rowCount) => {+ const { click, service, skeleton, render, getSelections } = createSelectionTestBed([], rowCount);+ click(1, 1);+ vi.advanceTimersByTime(160);+ const control = service.getActiveSelectionControl()!;+ const from = control.getRange();++ click(5, 4);+ const target = control.getRange();+ expect(service.getActiveSelectionControl()).toBe(control);+ expect(getSelections()[0].range).toMatchObject({ startRow: 5, endRow: 5, startColumn: 4, endColumn: 4 });++ const mainLayer = render.scene.getLayer(SHEET_COMPONENT_MAIN_LAYER_INDEX);+ mainLayer.makeDirty(false);+ const calculate = vi.spyOn(skeleton, 'calculate');+ const getCell = vi.spyOn(skeleton, 'getCellWithMergeInfoByIndex');+ vi.advanceTimersByTime(48);+ expect(control.selectionShape.left).toBeGreaterThan(from.startX);+ expect(control.selectionShape.left).toBeLessThan(target.startX);+ expect(control.selectionShape.top).toBeGreaterThan(from.startY);+ expect(control.selectionShape.top).toBeLessThan(target.startY);+ const borderPosition = () => new Vector2(control.selectionShape.left + control.leftControl.left, control.selectionShape.top + 10);+ expect(render.scene.pick(borderPosition())).not.toBe(control.leftControl);+ expect(control.getRange()).toEqual(target);+ vi.advanceTimersByTime(160);+ expect(control.selectionShape.left).toBe(target.startX);+ expect(control.selectionShape.top).toBe(target.startY);+ expect(render.scene.pick(borderPosition())).toBe(control.leftControl);+ expect(mainLayer.isDirty()).toBe(false);+ expect(calculate).not.toHaveBeenCalled();+ expect(getCell).not.toHaveBeenCalled();++ const translate = vi.spyOn(control.selectionShape, 'translate');+ vi.advanceTimersByTime(300);+ expect(translate).not.toHaveBeenCalled();+ });++ it('retargets from the visible position and cancels motion when dragging or disposing', () => {+ const { click, service, eventAt, spreadsheet, render } = createSelectionTestBed();+ click(1, 1);+ vi.advanceTimersByTime(160);+ click(5, 4);+ vi.advanceTimersByTime(32);+ const control = service.getActiveSelectionControl()!;+ const visibleLeft = control.selectionShape.left;+ click(8, 6);+ expect(control.selectionShape.left).toBe(visibleLeft);+ vi.advanceTimersByTime(160);+ expect(control.selectionShape.left).toBe(control.getRange().startX);++ spreadsheet.onPointerDown$.emitEvent(eventAt(2, 2));+ render.scene.onPointerMove$.emitEvent(eventAt(4, 3));+ render.scene.onPointerUp$.emitEvent(eventAt(4, 3));+ const dragged = control.getRange();+ vi.advanceTimersByTime(160);+ expect(control.selectionShape.left).toBe(dragged.startX);+ expect(control.selectionShape.top).toBe(dragged.startY);+ expect(dragged).toMatchObject({ startRow: 2, endRow: 4, startColumn: 2, endColumn: 3 });++ click(1, 1);+ click(5, 4);+ const disposedControl = service.getActiveSelectionControl()!;+ const translate = vi.spyOn(disposedControl.selectionShape, 'translate');+ service.disableSelection();+ vi.advanceTimersByTime(160);+ expect(translate).not.toHaveBeenCalled();+ expect(service.getSelectionControls()).toHaveLength(0);+ });++ it('resizes merged cell outlines at constant stroke width and respects reduced motion', () => {+ const { click, service } = createSelectionTestBed([{ startRow: 3, endRow: 4, startColumn: 3, endColumn: 5 }]);+ click(1, 1);+ vi.advanceTimersByTime(160);+ const control = service.getActiveSelectionControl()!;+ const width = control.topControl.width;+ const stroke = control.leftControl.width;+ click(3, 3);+ vi.advanceTimersByTime(48);+ const target = control.getRange();+ expect(control.topControl.width).toBeGreaterThan(width);+ expect(control.topControl.width).toBeLessThan(target.endX - target.startX + stroke);+ expect(control.leftControl.width).toBe(stroke);+ vi.advanceTimersByTime(160);+ expect(control.topControl.width).toBe(target.endX - target.startX + stroke);++ vi.spyOn(window, 'matchMedia').mockReturnValue({ matches: true } as MediaQueryList);+ click(7, 2);+ expect(control.selectionShape.left).toBe(control.getRange().startX);+ expect(control.selectionShape.top).toBe(control.getRange().startY);+ const translate = vi.spyOn(control.selectionShape, 'translate');+ vi.advanceTimersByTime(160);+ expect(translate).not.toHaveBeenCalled();+ });++ it('settles immediately across frozen panes, on zoom, and when switching worksheets', () => {+ const { click, service, workbook, render } = createSelectionTestBed();+ workbook.getActiveSheet().getSnapshot().freeze = { startRow: 2, startColumn: 0, xSplit: 0, ySplit: 2 };+ click(1, 1);+ vi.advanceTimersByTime(160);+ click(4, 4);+ const control = service.getActiveSelectionControl()!;+ expect(control.selectionShape.left).toBe(control.getRange().startX);+ expect(control.selectionShape.top).toBe(control.getRange().startY);++ click(6, 5);+ render.scene.scale(1.5, 1.5);+ vi.advanceTimersByTime(160);+ expect(control.selectionShape.left).toBe(control.getRange().startX);+ expect(control.selectionShape.top).toBe(control.getRange().startY);++ render.scene.scale(1, 1);+ click(4, 2);+ const translate = vi.spyOn(control.selectionShape, 'translate');+ workbook.addWorksheet('sheet2', 1, { id: 'sheet2', name: 'Sheet 2', rowCount: 20, columnCount: 10 });+ workbook.setActiveSheet(workbook.getSheetBySheetId('sheet2')!);+ render.with(SheetSkeletonManagerService).setCurrent({ sheetId: 'sheet2' });+ vi.advanceTimersByTime(160);+ const nextControl = service.getActiveSelectionControl()!;+ expect(translate).not.toHaveBeenCalled();+ expect(nextControl).not.toBe(control);+ expect(nextControl.selectionShape.left).toBe(nextControl.getRange().startX);+ expect(nextControl.selectionShape.top).toBe(nextControl.getRange().startY);+ });+for (const single of [false, true]) {for (const modifier of ['none', 'ctrlKey', 'metaKey', 'shiftKey'] as const) {it(`preserves the intended pointer range with ${modifier} and single selection ${single}`, () => {diff --git a/packages/sheets-ui/src/services/selection/selection-control.ts b/packages/sheets-ui/src/services/selection/selection-control.tsindex 9e7d3d9f08..ff3e457c89 100644--- a/packages/sheets-ui/src/services/selection/selection-control.ts+++ b/packages/sheets-ui/src/services/selection/selection-control.ts@@ -18,14 +18,14 @@ import type { ICellWithCoord, IRangeWithCoord, Nullable, ThemeService } from '@uimport type { IObjectFullState, IRectProps, Scene, SpreadsheetSkeleton } from '@univerjs/engine-render';import type { ISelectionStyle, ISelectionWidgetConfig, ISelectionWithCoord } from '@univerjs/sheets';import type { ISelectionShapeExtensionOption } from './selection-shape-extension';-import { ColorKit, Disposable, RANGE_TYPE, toDisposable } from '@univerjs/core';+import { ColorKit, Disposable, RANGE_TYPE, Rectangle, toDisposable, Tools } from '@univerjs/core';import { cancelRequestFrame, DashedRect, FIX_ONE_PIXEL_BLUR_OFFSET, Group, Rect, requestNewFrame, TRANSFORM_CHANGE_OBSERVABLE_TYPE } from '@univerjs/engine-render';import {SELECTION_CONTROL_BORDER_BUFFER_COLOR,SELECTION_CONTROL_BORDER_BUFFER_WIDTH,} from '@univerjs/sheets';-import { BehaviorSubject, Subject } from 'rxjs';+import { SHEET_COMPONENT_HEADER_SELECTION_LAYER_INDEX, SHEET_COMPONENT_SELECTION_LAYER_INDEX } from '../../common/keys';import { genNormalSelectionStyle } from './const';import { SelectionRenderModel } from './selection-render-model';@@ -70,11 +70,16 @@ export enum SELECTION_MANAGER_KEY {}const SELECTION_TITLE_HIGHLIGHT_ALPHA = 0.3;+const SELECTION_MOVE_DURATION = 120;/*** The main selection canvas component, includes leftControl,rightControl,topControl,bottomControl,backgroundControlTop,backgroundControlMiddleLeft,backgroundControlMiddleRight,backgroundControlBottom,fillControl*/export class SelectionControl extends Disposable {+ private _moveAnimationFrame = -1;+ private _animatedRange: IRangeWithCoord | null = null;+ private _restoreMoveEvents: (() => void) | null = null;+private _isHelperSelection: boolean = true;/**@@ -260,6 +265,7 @@ export class SelectionControl extends Disposable {return;}+ this._stopMoveAnimation();this._updateLayoutOfSelectionControl(this._currentStyle);this._updateControlCoord();})@@ -515,6 +521,11 @@ export class SelectionControl extends Disposable {}setEvent(state: boolean): void {+ if (this._animatedRange) {+ this._stopMoveAnimation();+ this._updateLayoutOfSelectionControl();+ this._updateControlCoord();+ }this.leftControl.evented = state;this.rightControl.evented = state;this.topControl.evented = state;@@ -555,7 +566,7 @@ export class SelectionControl extends Disposable {const fixOnePixelBlurOffset = FIX_ONE_PIXEL_BLUR_OFFSET / scale;// startX startY shares same coordinate with viewport.(include row & col header)- const { startX, startY, endX, endY } = this._selectionRenderModel;+ const { startX, startY, endX, endY } = this._animatedRange ?? this._selectionRenderModel;this.leftControl.transformByState({height: endY - startY,left: -leftAdjustWidth + fixOnePixelBlurOffset,@@ -655,7 +666,9 @@ export class SelectionControl extends Disposable {}this._updateBackgroundControl(currentStyle);- this._updateHeaderBackground(currentStyle);+ if (!this._animatedRange) {+ this._updateHeaderBackground(currentStyle);+ }this._updateWidgets(currentStyle);}@@ -663,13 +676,14 @@ export class SelectionControl extends Disposable {* update selection control coordination by curr selection model*/protected _updateControlCoord(): void {- const { startX, startY } = this._selectionRenderModel;+ const { startX, startY } = this._animatedRange ?? this._selectionRenderModel;this.selectionShapeGroup.show();this.selectionShapeGroup.translate(startX, startY);this.selectionShapeGroup.makeDirtyNoDebounce(true);}updateStyle(style: Partial<ISelectionStyle>): void {+ this._stopMoveAnimation();this._updateLayoutOfSelectionControl(style);this._updateControlCoord();}@@ -684,6 +698,7 @@ export class SelectionControl extends Disposable {* @param primaryWithCoord*/updateRange(rangeWithCoord: IRangeWithCoord, primaryWithCoord: Nullable<ICellWithCoord>): void {+ this._stopMoveAnimation();this._selectionRenderModel.setValue(rangeWithCoord, primaryWithCoord);this._showAutoFill = primaryWithCoord !== null;this._updateLayoutOfSelectionControl();@@ -694,7 +709,15 @@ export class SelectionControl extends Disposable {* Update range and primary range and style.* @param selectionWthCoord*/- updateRangeBySelectionWithCoord(selectionWthCoord: ISelectionWithCoord, sk?: SpreadsheetSkeleton) {+ updateRangeBySelectionWithCoord(selectionWthCoord: ISelectionWithCoord, sk?: SpreadsheetSkeleton, animate = false) {+ const previousRange = this._animatedRange ?? this.getRange();+ const targetRange = selectionWthCoord.rangeWithCoord;+ const rangeChanged = !Rectangle.equals(this.model, targetRange) ||+ this.model.startX !== targetRange.startX || this.model.startY !== targetRange.startY ||+ this.model.endX !== targetRange.endX || this.model.endY !== targetRange.endY;+ if (animate || rangeChanged || selectionWthCoord.primaryWithCoord === null) {+ this._stopMoveAnimation();+ }if (sk) {// do not get header size from workbook, that is default value.// if row is over one million, row header width would be bigger than default value.@@ -708,6 +731,58 @@ export class SelectionControl extends Disposable {this._showAutoFill = selectionWthCoord.primaryWithCoord !== null;this._updateLayoutOfSelectionControl(selectionWthCoord.style);this._updateControlCoord();++ if (animate && rangeChanged && !window.matchMedia('(prefers-reduced-motion: reduce)').matches) {+ this._animateMove(previousRange);+ }+ }++ private _animateMove(from: IRangeWithCoord): void {+ const target = this.getRange();+ const startedAt = Tools.now();+ // A moving border must not intercept the next click as a range move or autofill gesture.+ const eventedShapes = this.selectionShapeGroup.getObjects().filter((shape) => shape.evented);+ eventedShapes.forEach((shape) => {+ shape.evented = false;+ });+ this._restoreMoveEvents = () => eventedShapes.forEach((shape) => {+ shape.evented = true;+ });+ this._animatedRange = from;+ this._updateLayoutOfSelectionControl();+ this._updateControlCoord();++ const frame = () => {+ const progress = Math.min(1, (Tools.now() - startedAt) / SELECTION_MOVE_DURATION);+ const eased = 1 - (1 - progress) ** 3;+ if (progress === 1) {+ this._stopMoveAnimation();+ }+ // Only interpolate the selection geometry; the model and worksheet caches stay at the destination.+ this._animatedRange = progress < 1+ ? {+ ...target,+ startX: from.startX + (target.startX - from.startX) * eased,+ startY: from.startY + (target.startY - from.startY) * eased,+ endX: from.endX + (target.endX - from.endX) * eased,+ endY: from.endY + (target.endY - from.endY) * eased,+ }+ : null;+ this._updateLayoutOfSelectionControl();+ this._updateControlCoord();+ this._moveAnimationFrame = progress < 1 ? requestNewFrame(frame) : -1;+ };+ this._moveAnimationFrame = requestNewFrame(frame);+ }++ private _stopMoveAnimation(): void {+ if (this._moveAnimationFrame !== -1) {+ cancelRequestFrame(this._moveAnimationFrame);+ this._moveAnimationFrame = -1;+ }+ this._animatedRange = null;+ this._restoreMoveEvents?.();+ this._restoreMoveEvents = null;}/**@@ -727,46 +802,24 @@ export class SelectionControl extends Disposable {}clearHighlight(): void {+ this._stopMoveAnimation();// in multiple selection shape, only shape with highlight has auto fill.this._showAutoFill = false;this._selectionRenderModel.clearCurrentCell();this._updateLayoutOfSelectionControl(this._currentStyle);+ this._updateControlCoord();}getScene(): Scene {return this._scene;}- // eslint-disable-next-line complexityoverride dispose(): void {- this._leftBorder?.dispose();- this._rightBorder?.dispose();- this._topBorder?.dispose();- this._bottomBorder?.dispose();- this._backgroundControlTop?.dispose();- this._backgroundControlMiddleLeft?.dispose();- this._backgroundControlMiddleRight?.dispose();- this._backgroundControlBottom?.dispose();- this._autoFillControl.dispose();- this._selectionShapeGroup?.dispose();-- this._rowHeaderBackground?.dispose();- this._rowHeaderBorder?.dispose();- this._rowHeaderGroup?.dispose();- this._rowHeaderBackground?.dispose();- this._columnHeaderBackground?.dispose();- this._columnHeaderBorder?.dispose();- this._columnHeaderGroup?.dispose();-- this._topLeftWidget?.dispose();- this._topCenterWidget?.dispose();- this._topRightWidget?.dispose();- this._middleLeftWidget?.dispose();- this._middleRightWidget?.dispose();- this._bottomLeftWidget?.dispose();- this._bottomCenterWidget?.dispose();- this._bottomRightWidget?.dispose();-+ this._stopMoveAnimation();+ this._stopAntLineAnimation();+ this._selectionShapeGroup.dispose();+ this._rowHeaderGroup.dispose();+ this._columnHeaderGroup.dispose();this._controlExtension?.dispose();super.dispose();@@ -916,13 +969,13 @@ export class SelectionControl extends Disposable {}private _updateBackgroundControl(style: ISelectionStyle): void {- const { startX, startY, endX, endY } = this._selectionRenderModel;+ const { startX, startY, endX, endY } = this._animatedRange ?? this._selectionRenderModel;const scale = this._getScale();const { fill = style.fill! } = style;let { strokeWidth } = style;strokeWidth /= scale;- const highlightSelection = this._selectionRenderModel.highlightToSelection();+ const highlightSelection = this._animatedRange ?? this._selectionRenderModel.highlightToSelection();if (!highlightSelection) {this._backgroundControlTop.resize(endX - startX, endY - startY);@@ -991,7 +1044,7 @@ export class SelectionControl extends Disposable {}private _updateWidgets(style: Required<ISelectionStyle>): void {- const { startX, startY, endX, endY } = this._selectionRenderModel;+ const { startX, startY, endX, endY } = this._animatedRange ?? this._selectionRenderModel;const { stroke = style.stroke!, widgets = style.widgets!, widgetStroke = style.widgetStroke! } = style;const scale = this._getScale();diff --git a/packages/sheets-ui/src/services/selection/selection-render.service.ts b/packages/sheets-ui/src/services/selection/selection-render.service.tsindex 2f624ee50d..3ce1c69255 100644--- a/packages/sheets-ui/src/services/selection/selection-render.service.ts+++ b/packages/sheets-ui/src/services/selection/selection-render.service.ts@@ -48,6 +48,7 @@ import {} from '@univerjs/sheets';import { IShortcutService } from '@univerjs/ui';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';@@ -296,7 +297,7 @@ export class SheetSelectionRenderService extends BaseSelectionRenderService implconvertSelectionDataToRange(selectionDataWithStyle));- this._commandService.executeCommand(SetSelectionsOperation.id, {+ this._commandService.syncExecuteCommand(SetSelectionsOperation.id, {unitId,subUnitId: sheetId,type,@@ -322,6 +323,7 @@ export class SheetSelectionRenderService extends BaseSelectionRenderService implthis._changeRuntime(skeleton, scene, viewportMain);if (prevSheetId !== skeleton.worksheet.getSheetId()) {+ this._reset();// If there is no initial selection, add one by default in the top left corner.const selections = this._workbookSelections.getCurrentSelections();// WARNING: SetSelectionsOperation with type=null would clear all exists selections@@ -450,6 +452,10 @@ export class SheetSelectionRenderService extends BaseSelectionRenderService impl}let activeControl = this.getActiveSelectionControl();+ if (activeControl && this._canAnimateSelection(evt, activeControl, cursorRange)) {+ activeControl.updateRangeBySelectionWithCoord(selectionWithCoord, this._skeleton, true);+ return activeControl;+ }this._checkClearPreviousControls(evt);const currentCell = activeControl?.model.currentCell;if (evt.shiftKey && currentCell && activeControl) {@@ -463,6 +469,21 @@ export class SheetSelectionRenderService extends BaseSelectionRenderService implreturn activeControl;}+ private _canAnimateSelection(evt: IPointerEvent | IMouseEvent, control: SelectionControl, target: ISelectionWithCoord['rangeWithCoord']): boolean {+ if (this.getSelectionControls().length !== 1 || this._rangeType !== RANGE_TYPE.NORMAL || this._remainLastEnabled ||+ evt.button !== 0 || evt.ctrlKey || evt.metaKey || evt.shiftKey || evt.altKey) {+ return false;+ }+ const current = control.getCurrentCellInfo();+ if (!current || !Rectangle.equals(control.model, current)) {+ return false;+ }+ const freeze = this._skeleton.worksheet.getFreeze();+ // Frozen panes have different scroll offsets, so only interpolate inside the same pane.+ return (current.startRow < freeze.startRow) === (target.startRow < freeze.startRow) &&+ (current.startColumn < freeze.startColumn) === (target.startColumn < freeze.startColumn);+ }+override endSelection(): void {const previousSelections = this._selectionBeforeModifierClick;this._selectionBeforeModifierClick = null;