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(mobile): scroll zoom and selection (#6483)

Univer6cf25a25def7
diff --git a/packages/sheets-ui/src/consts/mobile-context.ts b/packages/sheets-ui/src/consts/mobile-context.ts
new file mode 100644
index 0000000000..19a9b70561
--- /dev/null
+++ b/packages/sheets-ui/src/consts/mobile-context.ts
@@ -0,0 +1,27 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * Context key indicating that pinch-to-zoom gesture is in progress on mobile.
+ * Used to prevent selection operations during pinch zoom.
+ */
+export const MOBILE_PINCH_ZOOMING = 'MOBILE_PINCH_ZOOMING';
+
+/**
+ * Context key indicating that selection is being expanded on mobile (dragging fill controls).
+ * Used to prevent scroll/inertia/zoom operations during selection expansion.
+ */
+export const MOBILE_EXPANDING_SELECTION = 'MOBILE_EXPANDING_SELECTION';
diff --git a/packages/sheets-ui/src/controllers/render-controllers/mobile/mobile-scroll.render-controller.ts b/packages/sheets-ui/src/controllers/render-controllers/mobile/mobile-scroll.render-controller.ts
index 5d172cd696..255376b530 100644
--- a/packages/sheets-ui/src/controllers/render-controllers/mobile/mobile-scroll.render-controller.ts
+++ b/packages/sheets-ui/src/controllers/render-controllers/mobile/mobile-scroll.render-controller.ts
@@ -25,6 +25,7 @@ import {
Direction,
Disposable,
ICommandService,
+ IContextService,
Inject,
IUniverInstanceService,
RANGE_TYPE,
@@ -34,6 +35,8 @@ import { IRenderManagerService, SHEET_VIEWPORT_KEY } from '@univerjs/engine-rend
import { ScrollToCellOperation, SheetsSelectionsService } from '@univerjs/sheets';
import { ScrollCommand, SetScrollRelativeCommand } from '../../../commands/commands/set-scroll.command';
import { ExpandSelectionCommand, MoveSelectionCommand, MoveSelectionEnterAndTabCommand } from '../../../commands/commands/set-selection.command';
+import { SetZoomRatioCommand } from '../../../commands/commands/set-zoom-ratio.command';
+import { MOBILE_EXPANDING_SELECTION, MOBILE_PINCH_ZOOMING } from '../../../consts/mobile-context';
import { SheetScrollManagerService } from '../../../services/scroll-manager.service';
import { SheetSkeletonManagerService } from '../../../services/sheet-skeleton-manager.service';
import { getSheetObject } from '../../utils/component-tools';
@@ -51,7 +54,8 @@ export class MobileSheetsScrollRenderController extends Disposable implements IR
@IRenderManagerService private readonly _renderManagerService: IRenderManagerService,
@Inject(SheetsSelectionsService) private readonly _selectionManagerService: SheetsSelectionsService,
@Inject(SheetScrollManagerService) private readonly _scrollManagerService: SheetScrollManagerService,
- @IUniverInstanceService protected readonly _univerInstanceService: IUniverInstanceService
+ @IUniverInstanceService protected readonly _univerInstanceService: IUniverInstanceService,
+ @IContextService private readonly _contextService: IContextService
) {
super();
@@ -308,104 +312,743 @@ export class MobileSheetsScrollRenderController extends Disposable implements IR
}
/**
- * for mobile
+ * for mobile - iOS-like smooth inertia scrolling
+ * Uses native touch events for better mobile experience while keeping onPointerDown$ as trigger
+ * to avoid interfering with header events
*/
// eslint-disable-next-line max-lines-per-function
private _initPointerScrollEvent() {
const sheetObject = this._getSheetObject();
if (!sheetObject) return;
- // const workbook = this._univerInstanceService.getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET)!;
- const scrollManagerService = this._scrollManagerService;
const scene = sheetObject.scene;
const spreadsheet = sheetObject.spreadsheet;
const viewportMain = scene.getViewport(SHEET_VIEWPORT_KEY.VIEW_MAIN);
- const lastPointerPos: IPoint = { x: 0, y: 0 };
- let _pointerScrolling: boolean = false;
+ const lastTouchPos: IPoint = { x: 0, y: 0 };
+ let _touchScrolling: boolean = false;
+ // Velocity tracking for smooth inertia (iOS-like)
const velocity = { x: 0, y: 0 };
- const deceleration = 0.95;
let scrollInertiaAnimationID: null | number = null;
- const pointerScrollInertia = () => {
+
+ // Track velocity history for smoother calculation (like iOS)
+ const VELOCITY_HISTORY_SIZE = 5;
+ const velocityHistory: Array<{ x: number; y: number; time: number }> = [];
+ let lastMoveTime = 0;
+
+ // Track swipe characteristics for dynamic inertia calculation
+ let swipeStartTime = 0;
+ let swipeTotalDisplacement = { x: 0, y: 0 };
+
+ // Direction locking - prevent simultaneous X/Y scrolling
+ let lockedDirection: 'x' | 'y' | null = null;
+ const DIRECTION_LOCK_THRESHOLD = 8; // px - minimum movement to lock direction
+
+ // iOS-like physics constants (tuned for smoother feel)
+ const BASE_DECELERATION_RATE = 0.992; // Per millisecond deceleration (lower = stops faster)
+ const BASE_MIN_VELOCITY_THRESHOLD = 0.22; // Minimum velocity to continue animation
+ const BASE_MAX_VELOCITY = 12; // Cap maximum velocity for stability
+
+ // Flick detection thresholds
+ const FLICK_TIME_THRESHOLD = 240; // ms - swipes faster than this are considered "flicks"
+ const FLICK_DISTANCE_THRESHOLD = 30; // px - minimum distance to be considered a flick
+ const MIN_VELOCITY_MULTIPLIER = 0.05; // For slow drags
+ const MAX_VELOCITY_MULTIPLIER = 0.26; // For quick flicks
+
+ /**
+ * Get current zoom ratio for adjusting physics parameters
+ */
+ const getCurrentZoomRatio = (): number => {
+ const worksheet = this._context.unit.getActiveSheet();
+ return worksheet?.getZoomRatio() || 1;
+ };
+
+ /**
+ * Get physics parameters for inertia scrolling
+ * These are now zoom-independent since zoom adjustment is applied at the delta level
+ * This ensures consistent scroll behavior at any zoom level
+ */
+ const getZoomAdjustedParams = () => {
+ // Use base values directly - zoom adjustment is handled in touchmove delta calculation
+ return {
+ decelerationRate: BASE_DECELERATION_RATE,
+ minVelocityThreshold: BASE_MIN_VELOCITY_THRESHOLD,
+ maxVelocity: BASE_MAX_VELOCITY,
+ };
+ };
+
+ /**
+ * Calculate dynamic velocity multiplier based on swipe characteristics
+ * Quick short flicks get higher multiplier, slow drags get lower multiplier
+ */
+ const calculateDynamicVelocityMultiplier = (
+ swipeDuration: number,
+ swipeDistance: number,
+ instantVelocity: number
+ ): number => {
+ // Calculate swipe speed (distance / time)
+ const swipeSpeed = swipeDuration > 0 ? swipeDistance / swipeDuration : 0;
+
+ // Detect if this is a "flick" gesture (quick, intentional swipe)
+ const isFlick = swipeDuration < FLICK_TIME_THRESHOLD && swipeDistance > FLICK_DISTANCE_THRESHOLD;
+
+ // Base multiplier calculation
+ let multiplier: number;
+
+ if (isFlick) {
+ // Quick flick: use higher multiplier based on speed
+ // Faster flicks get closer to MAX_VELOCITY_MULTIPLIER
+ const speedFactor = Math.min(swipeSpeed / 2, 1); // Normalize speed (2 px/ms = fast)
+ multiplier = MIN_VELOCITY_MULTIPLIER + (MAX_VELOCITY_MULTIPLIER - MIN_VELOCITY_MULTIPLIER) * speedFactor;
+
+ // Boost multiplier for very quick flicks with high instantaneous velocity
+ if (swipeDuration < 150 && Math.abs(instantVelocity) > 3) {
+ multiplier *= 1.3;
+ }
+ } else {
+ // Slow drag: use lower multiplier, but still proportional to final velocity
+ const velocityFactor = Math.min(Math.abs(instantVelocity) / 5, 1);
+ multiplier = MIN_VELOCITY_MULTIPLIER * (0.5 + velocityFactor * 0.5);
+ }
+
+ // Clamp the multiplier
+ return Math.max(MIN_VELOCITY_MULTIPLIER * 0.5, Math.min(MAX_VELOCITY_MULTIPLIER * 1.5, multiplier));
+ };
+
+ /**
+ * Calculate weighted average velocity from history (iOS-like behavior)
+ * More recent samples have higher weight
+ */
+ const calculateAverageVelocity = (): { x: number; y: number } => {
+ if (velocityHistory.length === 0) {
+ return { x: 0, y: 0 };
+ }
+
+ let totalWeight = 0;
+ let weightedVelX = 0;
+ let weightedVelY = 0;
+
+ // Give more weight to recent velocity samples
+ for (let i = 0; i < velocityHistory.length; i++) {
+ const weight = (i + 1) * (i + 1); // Quadratic weighting
+ weightedVelX += velocityHistory[i].x * weight;
+ weightedVelY += velocityHistory[i].y * weight;
+ totalWeight += weight;
+ }
+
+ return {
+ x: weightedVelX / totalWeight,
+ y: weightedVelY / totalWeight,
+ };
+ };
+
+ /**
+ * iOS-like inertia animation with time-based deceleration
+ */
+ let lastFrameTime = 0;
+ let _pinchZooming = false;
+ let initialPinchDistance = 0;
+ let initialZoomRatio = 1;
+ let pinchCenter: IPoint = { x: 0, y: 0 };
+ const cancelInertiaAnimation = () => {
+ if (scrollInertiaAnimationID !== null) {
+ cancelAnimationFrame(scrollInertiaAnimationID);
+ scrollInertiaAnimationID = null;
+ }
+ lastFrameTime = 0;
+ velocity.x = 0;
+ velocity.y = 0;
+ };
+
+ const scrollInertia = (currentTime: number) => {
if (!viewportMain) return;
- velocity.x *= deceleration;
- velocity.y *= deceleration;
- lastPointerPos.x += velocity.x;
- lastPointerPos.y += velocity.y;
- const offsetX = velocity.x;
- const offsetY = velocity.y;
-
- if (offsetY !== 0 || offsetX !== 0) {
+
+ // Stop inertia if pinch zooming has started
+ if (_pinchZooming) {
+ cancelInertiaAnimation();
+ return;
+ }
+
+ if (lastFrameTime === 0) {
+ lastFrameTime = currentTime;
+ scrollInertiaAnimationID = requestAnimationFrame(scrollInertia);
+ return;
+ }
+
+ const deltaTime = currentTime - lastFrameTime;
+ lastFrameTime = currentTime;
+
+ const { decelerationRate, minVelocityThreshold } = getZoomAdjustedParams();
+
+ // Apply time-based exponential deceleration (iOS-like)
+ const decelerationFactor = decelerationRate ** deltaTime;
+ velocity.x *= decelerationFactor;
+ velocity.y *= decelerationFactor;
+
+ // Calculate displacement for this frame
+ // Using integral of velocity over time for smoother motion
+ const dampingFactor = -Math.log(decelerationRate);
+ const offsetX = velocity.x * (1 - decelerationFactor) / dampingFactor;
+ const offsetY = velocity.y * (1 - decelerationFactor) / dampingFactor;
+
+ if (Math.abs(offsetX) > 0.01 || Math.abs(offsetY) > 0.01) {
this._commandService.executeCommand(SetScrollRelativeCommand.id, { offsetY, offsetX });
}
- if (Math.abs(velocity.x) > 1 || Math.abs(velocity.y) > 1) {
- scrollInertiaAnimationID = requestAnimationFrame(pointerScrollInertia);
+ // Continue animation if velocity is above threshold
+ const speed = Math.sqrt(velocity.x * velocity.x + velocity.y * velocity.y);
+ if (speed > minVelocityThreshold) {
+ scrollInertiaAnimationID = requestAnimationFrame(scrollInertia);
} else {
scrollInertiaAnimationID = null;
+ lastFrameTime = 0;
}
};
+ // Get the canvas element for native touch events
+ const engine = scene.getEngine();
+ const canvasElement = engine?.getCanvasElement();
+ if (!canvasElement) return;
+
+ // ============== Pinch-to-Zoom State ==============
+
+ // Store the cell position at pinch center for maintaining focus point
+ let pinchCenterCellInfo: {
+ row: number;
+ column: number;
+ rowOffset: number; // offset within the cell
+ columnOffset: number;
+ cellStartX: number; // cell's start X in viewport coords
+ cellStartY: number;
+ } | null = null;
+
+ // Store the initial scroll position when pinch starts
+ // This is more reliable than cell-based calculation for maintaining position
+ let pinchStartScrollPos: { x: number; y: number } | null = null;
+ // Store the sheet position at pinch center (in unscaled sheet coordinates)
+ let pinchSheetPos: { x: number; y: number } | null = null;
+
+ // Create zoom indicator overlay
+ const zoomIndicator = this._createZoomIndicator(canvasElement);
+
+ /**
+ * Convert touch event to offset coordinates relative to canvas
+ */
+ const getTouchOffset = (touch: Touch): { offsetX: number; offsetY: number } => {
+ const rect = canvasElement.getBoundingClientRect();
+ return {
+ offsetX: touch.clientX - rect.left,
+ offsetY: touch.clientY - rect.top,
+ };
+ };
- const cancelInertiaAnimation = () => {
- cancelAnimationFrame(scrollInertiaAnimationID!);
- scrollInertiaAnimationID = null;
+ /**
+ * Calculate distance between two touch points
+ */
+ const getTouchDistance = (touch1: Touch, touch2: Touch): number => {
+ const dx = touch1.clientX - touch2.clientX;
+ const dy = touch1.clientY - touch2.clientY;
+ return Math.sqrt(dx * dx + dy * dy);
};
- spreadsheet.onPointerDown$.subscribeEvent((evt: IPointerEvent | IMouseEvent, state) => {
- cancelInertiaAnimation();
+ /**
+ * Get center point between two touches (in canvas coordinates)
+ */
+ const getPinchCenter = (touch1: Touch, touch2: Touch): IPoint => {
+ const offset1 = getTouchOffset(touch1);
+ const offset2 = getTouchOffset(touch2);
+ return {
+ x: (offset1.offsetX + offset2.offsetX) / 2,
+ y: (offset1.offsetY + offset2.offsetY) / 2,
+ };
+ };
+
+ /**
+ * Check if touch is within spreadsheet area (not on headers)
+ */
+ const isTouchOnSpreadsheet = (offsetX: number, offsetY: number): boolean => {
+ const skeleton = this._sheetSkeletonManagerService.getCurrentParam()?.skeleton;
+ if (!skeleton) return false;
+ const { rowHeaderWidthAndMarginLeft, columnHeaderHeightAndMarginTop } = skeleton;
+ return offsetX > rowHeaderWidthAndMarginLeft && offsetY > columnHeaderHeightAndMarginTop;
+ };
+ /**
+ * Convert canvas coordinates to cell information
+ */
+ const getCellInfoAtPoint = (canvasX: number, canvasY: number, zoomRatio: number): typeof pinchCenterCellInfo => {
+ const skeleton = this._sheetSkeletonManagerService.getCurrentParam()?.skeleton;
+ if (!skeleton || !viewportMain) return null;
+
+ const { rowHeaderWidthAndMarginLeft, columnHeaderHeightAndMarginTop } = skeleton;
+
+ // Convert canvas coordinates to viewport scroll coordinates
+ const viewportScrollX = viewportMain.viewportScrollX || 0;
+ const viewportScrollY = viewportMain.viewportScrollY || 0;
+
+ // Calculate the actual position in the sheet (accounting for zoom and scroll)
+ const sheetX = (canvasX - rowHeaderWidthAndMarginLeft) / zoomRatio + viewportScrollX;
+ const sheetY = (canvasY - columnHeaderHeightAndMarginTop) / zoomRatio + viewportScrollY;
+
+ // Find which cell this corresponds to
+ const { row, column, rowOffset, columnOffset } = skeleton.getOffsetRelativeToRowCol(
+ Math.max(0, sheetX),
+ Math.max(0, sheetY)
+ );
+
+ // Get the cell's start position
+ const cellInfo = skeleton.getCellWithCoordByIndex(row, column, false);
+
+ return {
+ row,
+ column,
+ rowOffset,
+ columnOffset,
+ cellStartX: cellInfo.startX,
+ cellStartY: cellInfo.startY,
+ };
+ };
+
+ /**
+ * Apply zoom and adjust scroll to keep pinch center in place
+ */
+ const applyZoomWithFocus = (newZoomRatio: number, oldZoomRatio: number) => {
if (!viewportMain) return;
- lastPointerPos.x = evt.offsetX;
- lastPointerPos.y = evt.offsetY;
- _pointerScrolling = true;
+ const skeleton = this._sheetSkeletonManagerService.getCurrentParam()?.skeleton;
+ if (!skeleton) return;
+
+ const { rowHeaderWidthAndMarginLeft, columnHeaderHeightAndMarginTop } = skeleton;
+
+ // Get current scroll position
+ const currentViewportScrollX = viewportMain.viewportScrollX || 0;
+ const currentViewportScrollY = viewportMain.viewportScrollY || 0;
+
+ // The position of pinch center in canvas coordinates (relative to content area)
+ const pinchCanvasX = pinchCenter.x - rowHeaderWidthAndMarginLeft;
+ const pinchCanvasY = pinchCenter.y - columnHeaderHeightAndMarginTop;
+
+ let newViewportScrollX: number;
+ let newViewportScrollY: number;
+
+ // Use pinchSheetPos (stored at pinch start) for more stable calculation
+ if (pinchSheetPos) {
+ // Calculate new scroll position to keep the pinch point stationary
+ // The pinchSheetPos is the fixed point in sheet coordinates that should stay under the finger
+ // At any zoom: canvasPos = (sheetPos - scrollPos) * zoom
+ // Solving for scrollPos: scrollPos = sheetPos - canvasPos / zoom
+ newViewportScrollX = pinchSheetPos.x - pinchCanvasX / newZoomRatio;
+ newViewportScrollY = pinchSheetPos.y - pinchCanvasY / newZoomRatio;
+ } else if (pinchCenterCellInfo) {
+ // Fallback to cell-based calculation
+ const pinchSheetX = pinchCenterCellInfo.cellStartX + pinchCenterCellInfo.columnOffset;
+ const pinchSheetY = pinchCenterCellInfo.cellStartY + pinchCenterCellInfo.rowOffset;
+ newViewportScrollX = pinchSheetX - pinchCanvasX / newZoomRatio;
+ newViewportScrollY = pinchSheetY - pinchCanvasY / newZoomRatio;
+ } else {
+ // No reference point available, maintain current position ratio
+ const zoomChange = newZoomRatio / oldZoomRatio;
+ newViewportScrollX = currentViewportScrollX / zoomChange;
+ newViewportScrollY = currentViewportScrollY / zoomChange;
+ }
+
+ // Only clamp negative values - don't force to 0 unnecessarily
+ // This prevents the "snapping to origin" issue
+ if (newViewportScrollX < 0) {
+ newViewportScrollX = 0;
+ }
+ if (newViewportScrollY < 0) {
+ newViewportScrollY = 0;
+ }
+
+ // Apply zoom first
+ const workbook = this._context.unit;
+ const worksheet = workbook.getActiveSheet();
+ if (!worksheet) return;
+
+ this._commandService.executeCommand(SetZoomRatioCommand.id, {
+ zoomRatio: newZoomRatio,
+ unitId: workbook.getUnitId(),
+ subUnitId: worksheet.getSheetId(),
+ });
+
+ // Then apply scroll adjustment
+ const { row, column, rowOffset, columnOffset } = skeleton.getOffsetRelativeToRowCol(
+ newViewportScrollX,
+ newViewportScrollY
+ );
+
+ this._commandService.executeCommand(ScrollCommand.id, {
+ sheetViewStartRow: row,
+ sheetViewStartColumn: column,
+ offsetX: columnOffset,
+ offsetY: rowOffset,
+ });
+ };
+
+ // Use onPointerDown$ as trigger to maintain header event compatibility
+ // This ensures the event system knows scrolling has started
+ spreadsheet.onPointerDown$.subscribeEvent((evt: IPointerEvent | IMouseEvent, state) => {
+ cancelInertiaAnimation();
state.stopPropagation();
});
- spreadsheet.onPointerMove$.subscribeEvent((evt: IPointerEvent | IMouseEvent, state) => {
- // cancelInertiaAnimation();
- if (!_pointerScrolling) return;
+ // Helper function to initialize pinch zoom state
+ const initializePinchZoom = (touch1: Touch, touch2: Touch) => {
+ _pinchZooming = true;
+ this._contextService.setContextValue(MOBILE_PINCH_ZOOMING, true);
+ initialPinchDistance = getTouchDistance(touch1, touch2);
+ initialZoomRatio = getCurrentZoomRatio();
+ pinchCenter = getPinchCenter(touch1, touch2);
+
+ // Store the cell info at pinch center
+ pinchCenterCellInfo = getCellInfoAtPoint(pinchCenter.x, pinchCenter.y, initialZoomRatio);
+
+ // Store initial scroll position and calculate sheet position at pinch center
+ if (viewportMain) {
+ const skeleton = this._sheetSkeletonManagerService.getCurrentParam()?.skeleton;
+ if (skeleton) {
+ const { rowHeaderWidthAndMarginLeft, columnHeaderHeightAndMarginTop } = skeleton;
+ pinchStartScrollPos = {
+ x: viewportMain.viewportScrollX || 0,
+ y: viewportMain.viewportScrollY || 0,
+ };
+ const pinchCanvasX = pinchCenter.x - rowHeaderWidthAndMarginLeft;
+ const pinchCanvasY = pinchCenter.y - columnHeaderHeightAndMarginTop;
+ pinchSheetPos = {
+ x: pinchStartScrollPos.x + pinchCanvasX / initialZoomRatio,
+ y: pinchStartScrollPos.y + pinchCanvasY / initialZoomRatio,
+ };
+ }
+ }
+ };
+
+ // Native touch event handlers for better mobile scrolling experience
+ const handleTouchStart = (e: TouchEvent) => {
+ // Handle pinch-to-zoom (two fingers)
+ cancelInertiaAnimation();
+ if (e.touches.length === 2) {
+ const touch1 = e.touches[0];
+ const touch2 = e.touches[1];
+
+ // Check if both touches are on spreadsheet area
+ const offset1 = getTouchOffset(touch1);
+ const offset2 = getTouchOffset(touch2);
+ if (!isTouchOnSpreadsheet(offset1.offsetX, offset1.offsetY) ||
+ !isTouchOnSpreadsheet(offset2.offsetX, offset2.offsetY)) {
+ return;
+ }
+
+ // Cancel any single-touch scrolling
+ _touchScrolling = false;
+
+ // Initialize pinch state
+ initializePinchZoom(touch1, touch2);
+
+ // Show zoom indicator
+ this._showZoomIndicator(zoomIndicator, Math.round(initialZoomRatio * 100));
+
+ e.preventDefault();
+ return;
+ }
+
+ // Single touch - handle scrolling
+ if (e.touches.length !== 1) return;
+
+ // If we were pinch zooming and now only one finger, don't start scrolling immediately
+ if (_pinchZooming) return;
+
+ // Don't start scrolling if selection is being expanded (dragging fill controls)
+ if (this._contextService.getContextValue(MOBILE_EXPANDING_SELECTION)) return;
+
+ const touch = e.touches[0];
+ const { offsetX, offsetY } = getTouchOffset(touch);
+
+ // Only start scrolling if touch is on spreadsheet area
+ if (!isTouchOnSpreadsheet(offsetX, offsetY)) return;
+
+ lastTouchPos.x = offsetX;
+ lastTouchPos.y = offsetY;
+ lastMoveTime = performance.now();
+ swipeStartTime = lastMoveTime;
+ swipeTotalDisplacement = { x: 0, y: 0 };
+ lockedDirection = null; // Reset direction lock on new touch
+ velocityHistory.length = 0;
+ _touchScrolling = true;
+
+ // Prevent default to avoid browser scroll behavior
+ e.preventDefault();
+ };
+
+ // eslint-disable-next-line max-lines-per-function
+ const handleTouchMove = (e: TouchEvent) => {
+ // Handle pinch-to-zoom
+ if (_pinchZooming && e.touches.length === 2) {
+ // Extra protection: ensure inertia is cancelled during zoom
+ if (scrollInertiaAnimationID !== null) {
+ cancelInertiaAnimation();
+ }
+
+ const touch1 = e.touches[0];
+ const touch2 = e.touches[1];
+
+ const currentDistance = getTouchDistance(touch1, touch2);
+ const scale = currentDistance / initialPinchDistance;
+
+ // Calculate new zoom ratio with constraints (mobile: 25% - 200%)
+ let newZoomRatio = initialZoomRatio * scale;
+ const MOBILE_ZOOM_MIN = 0.2;
+ const MOBILE_ZOOM_MAX = 2;
+ newZoomRatio = Math.max(MOBILE_ZOOM_MIN, Math.min(MOBILE_ZOOM_MAX, newZoomRatio));
+ // Round to one decimal place for smoother updates
+ newZoomRatio = Math.round(newZoomRatio * 10) / 10;
+
+ const currentZoom = getCurrentZoomRatio();
+ if (Math.abs(newZoomRatio - currentZoom) >= 0.05) {
+ // Update pinch center for smooth experience
+ pinchCenter = getPinchCenter(touch1, touch2);
+
+ // Apply zoom with focus point
+ applyZoomWithFocus(newZoomRatio, currentZoom);
+
+ // Update zoom indicator
+ this._showZoomIndicator(zoomIndicator, Math.round(newZoomRatio * 100));
+ }
+
+ e.preventDefault();
+ return;
+ }
+
+ // Handle scrolling
+ if (!_touchScrolling) return;
+ if (e.touches.length !== 1) return;
if (!viewportMain) return;
- const e = evt as IPointerEvent | IMouseEvent;
- const deltaX = -(e.offsetX - lastPointerPos.x);
- const deltaY = -(e.offsetY - lastPointerPos.y);
- velocity.x = -(e.offsetX - lastPointerPos.x);
- velocity.y = -(e.offsetY - lastPointerPos.y);
- const offsetX = deltaX;
- const offsetY = deltaY;
+
+ // Don't process scroll if selection is being expanded
+ if (this._contextService.getContextValue(MOBILE_EXPANDING_SELECTION)) return;
+
+ const touch = e.touches[0];
+ const { offsetX, offsetY } = getTouchOffset(touch);
+ const currentTime = performance.now();
+ const deltaTime = currentTime - lastMoveTime;
+
+ if (deltaTime <= 0) return;
+
+ const rawDeltaX = -(offsetX - lastTouchPos.x);
+ const rawDeltaY = -(offsetY - lastTouchPos.y);
+
+ // Adjust delta by zoom ratio to maintain consistent scroll feel at any zoom level
+ // When zoomed in, divide by larger ratio = less scroll (less sensitive)
+ // When zoomed out, divide by smaller ratio = more scroll (more responsive)
+ const zoomRatio = getCurrentZoomRatio();
+ const deltaX = rawDeltaX / zoomRatio;
+ const deltaY = rawDeltaY / zoomRatio;
+
+ // Track total displacement for flick detection and direction locking (used for inertia only)
+ // Use raw values for gesture detection to maintain consistent flick recognition
+ swipeTotalDisplacement.x += Math.abs(rawDeltaX);
+ swipeTotalDisplacement.y += Math.abs(rawDeltaY);
+
+ // Direction locking logic - lock to primary axis once threshold is reached
+ // Note: This only affects inertia scrolling, not the actual touchmove scroll
+ if (lockedDirection === null) {
+ const totalX = swipeTotalDisplacement.x;
+ const totalY = swipeTotalDisplacement.y;
+ if (totalX > DIRECTION_LOCK_THRESHOLD || totalY > DIRECTION_LOCK_THRESHOLD) {
+ // Lock to the axis with more displacement (for inertia only)
+ lockedDirection = totalX > totalY ? 'x' : 'y';
+ }
+ }
+
+ // Calculate instantaneous velocity (pixels per millisecond)
+ // Track both directions for velocity history
+ const instantVelX = deltaX / deltaTime * 16;
+ const instantVelY = deltaY / deltaTime * 16;
+
+ // Add to velocity history
+ velocityHistory.push({
+ x: instantVelX,
+ y: instantVelY,
+ time: currentTime,
+ });
+
+ // Keep only recent samples
+ while (velocityHistory.length > VELOCITY_HISTORY_SIZE) {
+ velocityHistory.shift();
+ }
+
+ // Apply scroll immediately for responsive feel
if (deltaX !== 0 || deltaY !== 0) {
- if (offsetY !== 0 || offsetX !== 0) {
- this._commandService.executeCommand(SetScrollRelativeCommand.id, { offsetY, offsetX });
+ this._commandService.executeCommand(SetScrollRelativeCommand.id, { offsetY: deltaY, offsetX: deltaX });
+ }
+
+ lastTouchPos.x = offsetX;
+ lastTouchPos.y = offsetY;
+ lastMoveTime = currentTime;
+
+ // Prevent default to avoid browser scroll behavior
+ e.preventDefault();
+ };
+
+ const handleTouchEnd = (e: TouchEvent) => {
+ // Handle pinch zoom end
+ if (_pinchZooming) {
+ if (e.touches.length < 2) {
+ _pinchZooming = false;
+ this._contextService.setContextValue(MOBILE_PINCH_ZOOMING, false);
+ pinchCenterCellInfo = null;
+ pinchStartScrollPos = null;
+ pinchSheetPos = null;
+ // Ensure inertia is fully cancelled after zoom
+ cancelInertiaAnimation();
+ velocityHistory.length = 0;
+ // Hide zoom indicator with delay
+ this._hideZoomIndicator(zoomIndicator);
}
+ return;
}
- // get scrollInfo from packages/sheets-ui/src/commands/commands/set-scroll.command.ts
- const _currentScroll = scrollManagerService.getCurrentScrollState();
+ // Handle scroll end
+ if (!_touchScrolling) return;
+ _touchScrolling = false;
- lastPointerPos.x = e.offsetX;
- lastPointerPos.y = e.offsetY;
+ // Calculate final velocity from history
+ const avgVelocity = calculateAverageVelocity();
- state.stopPropagation();
- });
+ // Calculate swipe characteristics for dynamic inertia
+ const swipeDuration = performance.now() - swipeStartTime;
+ const totalDistance = Math.sqrt(
+ swipeTotalDisplacement.x * swipeTotalDisplacement.x +
+ swipeTotalDisplacement.y * swipeTotalDisplacement.y
+ );
+ const instantVelocity = Math.sqrt(avgVelocity.x * avgVelocity.x + avgVelocity.y * avgVelocity.y);
- spreadsheet.onPointerUp$.subscribeEvent((_evt: IPointerEvent | IMouseEvent) => {
- _pointerScrolling = false;
- scrollInertiaAnimationID = requestAnimationFrame(pointerScrollInertia);
- });
+ // Get dynamic velocity multiplier based on swipe characteristics
+ const dynamicMultiplier = calculateDynamicVelocityMultiplier(swipeDuration, totalDistance, instantVelocity);
- // trigger by scene.input-manager@_onPointerMove because currObject has changed
- spreadsheet.onPointerLeave$.subscribeEvent(() => {
- _pointerScrolling = false;
- });
- spreadsheet.onPointerOut$.subscribeEvent(() => {
- _pointerScrolling = false;
- });
- scene.onPointerOut$.subscribeEvent(() => {
- _pointerScrolling = false;
- });
- scene.onPointerCancel$.subscribeEvent(() => {
- _pointerScrolling = false;
- });
+ const { maxVelocity, minVelocityThreshold } = getZoomAdjustedParams();
+
+ // Velocity is already zoom-adjusted since it's calculated from zoom-adjusted deltas
+ // No additional zoom adjustment needed here
+
+ // Apply dynamic velocity multiplier and cap
+ const cappedVelX = Math.max(-maxVelocity, Math.min(maxVelocity, avgVelocity.x * dynamicMultiplier));
+ const cappedVelY = Math.max(-maxVelocity, Math.min(maxVelocity, avgVelocity.y * dynamicMultiplier));
+
+ // Apply direction lock for inertia - only scroll in the primary direction
+ // This makes inertia feel more controlled while touchmove allows free movement
+ velocity.x = lockedDirection === 'y' ? 0 : cappedVelX;
+ velocity.y = lockedDirection === 'x' ? 0 : cappedVelY;
+
+ // Only start inertia if velocity is significant
+ const speed = Math.sqrt(velocity.x * velocity.x + velocity.y * velocity.y);
+ if (speed > minVelocityThreshold * 2) {
+ lastFrameTime = 0;
+ scrollInertiaAnimationID = requestAnimationFrame(scrollInertia);
+ }
+
+ velocityHistory.length = 0;
+ };
+
+ const handleTouchCancel = () => {
+ if (_pinchZooming) {
+ _pinchZooming = false;
+ this._contextService.setContextValue(MOBILE_PINCH_ZOOMING, false);
+ pinchCenterCellInfo = null;
+ pinchStartScrollPos = null;
+ pinchSheetPos = null;
+ this._hideZoomIndicator(zoomIndicator);
+ }
+ if (_touchScrolling) {
+ _touchScrolling = false;
+ velocityHistory.length = 0;
+ }
+ // Always cancel inertia on touch cancel
+ cancelInertiaAnimation();
+ };
+
+ // Add native touch event listeners with passive: false to allow preventDefault
+ canvasElement.addEventListener('touchstart', handleTouchStart, { passive: false });
+ canvasElement.addEventListener('touchmove', handleTouchMove, { passive: false });
+ canvasElement.addEventListener('touchend', handleTouchEnd, { passive: false });
+ canvasElement.addEventListener('touchcancel', handleTouchCancel, { passive: false });
+
+ // Clean up touch event listeners on dispose
+ this.disposeWithMe(toDisposable(() => {
+ canvasElement.removeEventListener('touchstart', handleTouchStart);
+ canvasElement.removeEventListener('touchmove', handleTouchMove);
+ canvasElement.removeEventListener('touchend', handleTouchEnd);
+ canvasElement.removeEventListener('touchcancel', handleTouchCancel);
+ // Remove zoom indicator
+ if (zoomIndicator && zoomIndicator.parentElement) {
+ zoomIndicator.parentElement.removeChild(zoomIndicator);
+ }
+ }));
+
+ // Note: We intentionally do NOT add handleScrollEnd listeners for onPointerLeave$/onPointerOut$
+ // When using native touch events, the touch can move outside the spreadsheet area (into headers)
+ // but the scroll should continue. The scroll will only end on touchend/touchcancel events.
+ // This fixes the issue where scrolling would stop when finger moves over row/column headers.
+ }
+
+ /**
+ * Create zoom indicator overlay element
+ */
+ private _createZoomIndicator(canvasElement: HTMLCanvasElement): HTMLDivElement {
+ const container = canvasElement.parentElement;
+ if (!container) {
+ // Fallback: create a detached element
+ const div = document.createElement('div');
+ div.style.display = 'none';
+ return div;
+ }
+
+ const indicator = document.createElement('div');
+ indicator.style.cssText = `
+ position: absolute;
+ top: 50%;
+ left: 50%;
+ transform: translate(-50%, -50%);
+ background-color: rgba(0, 0, 0, 0.7);
+ color: white;
+ padding: 12px 24px;
+ border-radius: 8px;
+ font-size: 24px;
+ font-weight: bold;
+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
+ pointer-events: none;
+ opacity: 0;
+ transition: opacity 0.15s ease-in-out;
+ z-index: 10000;
+ user-select: none;
+ -webkit-user-select: none;
+ `;
+
+ // Ensure container has relative positioning for absolute child
+ const containerPosition = window.getComputedStyle(container).position;
+ if (containerPosition === 'static') {
+ container.style.position = 'relative';
+ }
+
+ container.appendChild(indicator);
+ return indicator;
+ }
+
+ /**
+ * Show zoom indicator with percentage
+ */
+ private _showZoomIndicator(indicator: HTMLDivElement, percentage: number): void {
+ indicator.textContent = `${percentage}%`;
+ indicator.style.opacity = '1';
+ }
+
+ /**
+ * Hide zoom indicator with fade out
+ */
+ private _hideZoomIndicator(indicator: HTMLDivElement): void {
+ // Delay hiding to show final zoom value briefly
+ setTimeout(() => {
+ indicator.style.opacity = '0';
+ }, 300);
}
private _updateSceneSize(param: ISheetSkeletonManagerParam) {
@@ -423,12 +1066,10 @@ export class MobileSheetsScrollRenderController extends Disposable implements IR
const { rowTotalHeight, columnTotalWidth, rowHeaderWidthAndMarginLeft, columnHeaderHeightAndMarginTop } =
skeleton;
- const workbook = this._context.unit;
- const worksheet = workbook.getActiveSheet();
- if (!worksheet) return;
- const zoomRatio = worksheet.getZoomRatio() || 1;
- scene?.setScaleValueOnly(zoomRatio, zoomRatio);
+ // Note: Do NOT call scene.setScaleValueOnly here.
+ // Zoom is handled by SheetsZoomRenderController._updateViewZoom which calls scene.scale().
+ // Calling setScaleValueOnly here can cause scroll position issues when zooming back to 100%.
scene?.transformByState({
width: rowHeaderWidthAndMarginLeft + columnTotalWidth,
height: columnHeaderHeightAndMarginTop + rowTotalHeight,
@@ -439,42 +1080,6 @@ export class MobileSheetsScrollRenderController extends Disposable implements IR
return getSheetObject(this._context.unit, this._context);
}
- private _scrollToSelectionByDirection(range: IRange) {
- const bounds = this._getViewportBounding();
- if (bounds == null) {
- return false;
- }
- const {
- startRow: viewportStartRow,
- startColumn: viewportStartColumn,
- endRow: viewportEndRow,
- endColumn: viewportEndColumn,
- } = bounds;
-
- let row = 0;
- let column = 0;
-
- const { startRow, startColumn, endRow, endColumn } = range;
-
- if (startRow >= viewportStartRow) {
- row = endRow;
- }
-
- if (endRow <= viewportEndRow) {
- row = startRow;
- }
-
- if (startColumn >= viewportStartColumn) {
- column = endColumn;
- }
-
- if (endColumn <= viewportEndColumn) {
- column = startColumn;
- }
-
- this._scrollToCell(row, column);
- }
-
private _scrollToSelection(targetIsActualRowAndColumn = true) {
const selection = this._selectionManagerService.getCurrentLastSelection();
if (selection == null) {
diff --git a/packages/sheets-ui/src/services/selection/mobile-selection-render.service.ts b/packages/sheets-ui/src/services/selection/mobile-selection-render.service.ts
index 5d9f0279d4..e0d2fab851 100644
--- a/packages/sheets-ui/src/services/selection/mobile-selection-render.service.ts
+++ b/packages/sheets-ui/src/services/selection/mobile-selection-render.service.ts
@@ -41,7 +41,8 @@ import {
import { ScrollTimer, ScrollTimerType, SHEET_VIEWPORT_KEY, Vector2 } from '@univerjs/engine-render';
import { convertSelectionDataToRange, REF_SELECTIONS_ENABLED, SelectionMoveType, SetSelectionsOperation, SheetsSelectionsService } from '@univerjs/sheets';
import { IShortcutService } from '@univerjs/ui';
-import { distinctUntilChanged, startWith } from 'rxjs';
+import { distinctUntilChanged, merge, startWith } from 'rxjs';
+import { MOBILE_EXPANDING_SELECTION, MOBILE_PINCH_ZOOMING } from '../../consts/mobile-context';
import { getCoordByOffset, getSheetObject } from '../../controllers/utils/component-tools';
import { isThisColSelected, isThisRowSelected } from '../../controllers/utils/selections-tools';
import { SheetScrollManagerService } from '../scroll-manager.service';
@@ -68,6 +69,8 @@ export class MobileSheetsSelectionRenderService extends BaseSelectionRenderServi
expandingControlMode: ExpandingControl = ExpandingControl.BOTTOM_RIGHT;
+ private _anchorCellForExpanding: Nullable<ICellWithCoord> = null;
+
constructor(
private readonly _context: IRenderContext<Workbook>,
@Inject(Injector) injector: Injector,
@@ -104,6 +107,8 @@ export class MobileSheetsSelectionRenderService extends BaseSelectionRenderServi
}
private _initSkeletonChangeListener() {
+ // changing sheet is not the only way cause currentSkeleton$ emit, a lot of cmds will emit currentSkeleton$
+ // COMMAND_LISTENER_SKELETON_CHANGE ---> currentSkeleton$.next
this.disposeWithMe(this._sheetSkeletonManagerService.currentSkeleton$.subscribe((param) => {
if (param == null) {
this._logService.error('[SelectionRenderService]: should not receive null!');
@@ -114,29 +119,40 @@ export class MobileSheetsSelectionRenderService extends BaseSelectionRenderServi
const { sheetId, skeleton } = param;
const { scene } = this._context;
const viewportMain = scene.getViewport(SHEET_VIEWPORT_KEY.VIEW_MAIN);
+ const prevSheetId = this._skeleton?.worksheet?.getSheetId();
this._changeRuntime(skeleton, scene, viewportMain);
- // If there is no initial selection, add one by default in the top left corner.
- const firstSelection = this._workbookSelections.getCurrentLastSelection();
- if (!firstSelection) {
+ // Only handle selection when sheet is actually changed
+ if (prevSheetId !== skeleton.worksheet.getSheetId()) {
+ // Get current selections for this sheet from model
+ const selections = this._workbookSelections.getCurrentSelections();
+ // If there are existing selections for this sheet, use them; otherwise use default A1
this._commandService.syncExecuteCommand(SetSelectionsOperation.id, {
unitId,
subUnitId: sheetId,
- selections: [getTopLeftSelectionOfCurrSheet(skeleton)],
+ selections: selections.length !== 0 ? selections : [getTopLeftSelectionOfCurrSheet(skeleton)],
} as ISetSelectionsOperationParams);
}
+
+ // For col width & row height resize, update selection rendering
+ const currentSelections = this._workbookSelections.getCurrentSelections();
+ if (currentSelections != null) {
+ this.resetSelectionsByModelData(currentSelections);
+ }
}));
}
private _initSelectionChangeListener() {
- // When selection completes, we need to update the selections' rendering and clear event handlers.
- // only ref selection need this. now mobile only has normal selection.
- // this.disposeWithMe(this._workbookSelections.selectionMoveEnd$.subscribe((ISelectionWithStyleList) => {
- // this._reset();
- // for (const selectionWithStyle of ISelectionWithStyleList) {
- // this._addSelectionControlByModelData(selectionWithStyle);
- // }
- // }));
+ // When selection model changes (e.g. switching sheets, keyboard navigation),
+ // we need to update the selections' rendering.
+ this.disposeWithMe(merge(
+ this._workbookSelections.selectionMoveEnd$,
+ this._workbookSelections.selectionSet$
+ ).subscribe((selectionWithStyleList) => {
+ if (selectionWithStyleList) {
+ this.resetSelectionsByModelData(selectionWithStyleList);
+ }
+ }));
}
private _initEventListeners(sheetObject: ISheetObjectParam): void {
@@ -145,7 +161,7 @@ export class MobileSheetsSelectionRenderService extends BaseSelectionRenderServi
this._initSpreadsheetEvent(sheetObject);
this.disposeWithMe(
- spreadsheetRowHeader?.onPointerUp$.subscribeEvent((evt: IPointerEvent | IMouseEvent, _state: EventState) => {
+ spreadsheetRowHeader?.onPointerDown$.subscribeEvent((evt: IPointerEvent | IMouseEvent, _state: EventState) => {
if (this._normalSelectionDisabled()) return;
const skeleton = this._sheetSkeletonManagerService.getCurrentParam()!.skeleton;
@@ -159,7 +175,7 @@ export class MobileSheetsSelectionRenderService extends BaseSelectionRenderServi
);
this.disposeWithMe(
- spreadsheetColumnHeader?.onPointerUp$.subscribeEvent((evt: IPointerEvent | IMouseEvent, _state: EventState) => {
+ spreadsheetColumnHeader?.onPointerDown$.subscribeEvent((evt: IPointerEvent | IMouseEvent, _state: EventState) => {
if (this._normalSelectionDisabled()) return;
const skeleton = this._sheetSkeletonManagerService.getCurrentParam()!.skeleton;
@@ -174,7 +190,7 @@ export class MobileSheetsSelectionRenderService extends BaseSelectionRenderServi
// in mobile version, create a selection when pointerup.
// do not use onPointerDown$, pointerDown would close popup
// see packages/ui/src/views/components/context-menu/ContextMenu.tsx
- this.disposeWithMe(spreadsheetLeftTopPlaceholder?.onPointerUp$.subscribeEvent((_evt: IPointerEvent | IMouseEvent, state: EventState) => {
+ this.disposeWithMe(spreadsheetLeftTopPlaceholder?.onPointerDown$.subscribeEvent((_evt: IPointerEvent | IMouseEvent, state: EventState) => {
if (this._normalSelectionDisabled()) return;
this._reset(); // remove all other selections
@@ -202,6 +218,9 @@ export class MobileSheetsSelectionRenderService extends BaseSelectionRenderServi
};
const createNewSelection = (evt: IPointerEvent | IMouseEvent, showContextMenu: boolean) => {
+ // Don't create selection during pinch zoom
+ if (this._contextService.getContextValue(MOBILE_PINCH_ZOOMING)) return;
+
// TODO @lumixraku
this.createNewSelection(
evt,
@@ -224,6 +243,9 @@ export class MobileSheetsSelectionRenderService extends BaseSelectionRenderServi
}
});
const spreadsheetPointerDownSub = spreadsheet?.onPointerDown$.subscribeEvent((evt: IPointerEvent | IMouseEvent, state) => {
+ // Don't start long press timer during pinch zoom
+ if (this._contextService.getContextValue(MOBILE_PINCH_ZOOMING)) return;
+
pointerDownPos.x = evt.offsetX;
pointerDownPos.y = evt.offsetY;
longPressTimer = setTimeout(() => {
@@ -234,6 +256,8 @@ export class MobileSheetsSelectionRenderService extends BaseSelectionRenderServi
});
const spreadsheetPointerUpSub = spreadsheet?.onPointerUp$.subscribeEvent((evt: IPointerEvent | IMouseEvent, state) => {
if (this._normalSelectionDisabled()) return;
+ // Don't create selection during pinch zoom
+ if (this._contextService.getContextValue(MOBILE_PINCH_ZOOMING)) return;
clearTimeout(longPressTimer);
const edge = 10;
@@ -426,6 +450,7 @@ export class MobileSheetsSelectionRenderService extends BaseSelectionRenderServi
control.fillControlTopLeft!.onPointerDown$.subscribeEvent((evt: IPointerEvent | IMouseEvent) => {
this._expandingSelection = true;
+ this._contextService.setContextValue(MOBILE_EXPANDING_SELECTION, true);
this.expandingControlMode = expandingModeForTopLeft;
this._selectionMoveStart$.next(this.getSelectionDataWithStyle());
this._fillControlPointerDownHandler(
@@ -436,6 +461,7 @@ export class MobileSheetsSelectionRenderService extends BaseSelectionRenderServi
});
control.fillControlBottomRight!.onPointerDown$.subscribeEvent((evt: IPointerEvent | IMouseEvent) => {
this._expandingSelection = true;
+ this._contextService.setContextValue(MOBILE_EXPANDING_SELECTION, true);
this.expandingControlMode = expandingModeForBottomRight;
this._selectionMoveStart$.next(this.getSelectionDataWithStyle());
this._fillControlPointerDownHandler(
@@ -494,16 +520,14 @@ export class MobileSheetsSelectionRenderService extends BaseSelectionRenderServi
if (!activeSelectionControl) return;
- this._changeCurrCellWhenControlPointerDown();
+ const anchorCell = this._changeCurrCellWhenControlPointerDown();
+ this._anchorCellForExpanding = anchorCell;
this._selectionMoveStart$.next(this.getSelectionDataWithStyle());
this._clearUpdatingListeners();
this._addEndingListeners();
- this._scrollTimer = ScrollTimer.create(this._scene, scrollTimerType);
- this._scrollTimer.startScroll(viewportMain?.left ?? 0, viewportMain?.top ?? 0, viewportMain);
-
scene.getTransformer()?.clearSelectedObjects();
// #region pointermove
@@ -517,6 +541,7 @@ export class MobileSheetsSelectionRenderService extends BaseSelectionRenderServi
this._scenePointerUpSub = scene.onPointerUp$.subscribeEvent((_evt: IPointerEvent | IMouseEvent) => {
this.endSelection();
this._expandingSelection = false;
+ this._contextService.setContextValue(MOBILE_EXPANDING_SELECTION, false);
this.expandingControlMode = ExpandingControl.BOTTOM_RIGHT;
this._selectionMoveEnd$.next(this.getSelectionDataWithStyle());
@@ -573,6 +598,47 @@ export class MobileSheetsSelectionRenderService extends BaseSelectionRenderServi
return currCellRange;
}
+ /**
+ * Override base class method to add pinch zoom check.
+ * When pinch zooming, we should not process pointer move events for selection.
+ */
+ protected override _setupPointerMoveListener(
+ viewportMain: Nullable<Viewport>,
+ activeSelectionControl: MobileSelectionControl,
+ rangeType: RANGE_TYPE,
+ scrollTimerType: ScrollTimerType = ScrollTimerType.ALL,
+ moveStartPosX: number,
+ moveStartPosY: number
+ ): void {
+ this._scrollTimer = ScrollTimer.create(this._scene, scrollTimerType);
+ this._scrollTimer.startScroll(viewportMain?.left ?? 0, viewportMain?.top ?? 0, viewportMain);
+
+ const scene = this._scene;
+
+ // #region onPointerMove$
+ this._scenePointerMoveSub = scene.onPointerMove$.subscribeEvent((moveEvt: IPointerEvent | IMouseEvent) => {
+ // Skip processing if pinch zooming is in progress
+ if (this._contextService.getContextValue(MOBILE_PINCH_ZOOMING)) {
+ return;
+ }
+
+ const { offsetX: moveOffsetX, offsetY: moveOffsetY } = moveEvt;
+
+ const { x: newMoveOffsetX, y: newMoveOffsetY } = scene.getCoordRelativeToViewport(Vector2.FromArray([moveOffsetX, moveOffsetY]));
+
+ this._movingHandler(newMoveOffsetX, newMoveOffsetY, activeSelectionControl, rangeType);
+
+ const scrollOffsetX = newMoveOffsetX;
+ const scrollOffsetY = newMoveOffsetY;
+
+ // Auto scrolling - simplified for mobile (no freeze handling like PC version)
+ this._scrollTimer.scrolling(scrollOffsetX, scrollOffsetY, () => {
+ this._movingHandler(newMoveOffsetX, newMoveOffsetY, activeSelectionControl, rangeType);
+ });
+ });
+ // #endregion
+ }
+
/**
* Not same as _moving in PC (base selection render service)
* The diff is
@@ -626,14 +692,27 @@ export class MobileSheetsSelectionRenderService extends BaseSelectionRenderServi
const { rangeWithCoord: cursorCellRange } = cursorCellRangeInfo;
const currCellRange = activeSelectionControl.model.currentCell;
- const startRowOfActiveCell = currCellRange?.mergeInfo.startRow ?? -1;
- const endRowOfActiveCell = currCellRange?.mergeInfo.endRow ?? -1;
- const startColumnOfActiveCell = currCellRange?.mergeInfo.startColumn ?? -1;
- const endColOfActiveCell = currCellRange?.mergeInfo.endColumn ?? -1;
+
+ const anchorCell = this._anchorCellForExpanding ?? activeSelectionControl.model.currentCell;
+
+ const startRowOfActiveCell = anchorCell?.mergeInfo?.startRow ?? anchorCell?.actualRow ?? -1;
+ const endRowOfActiveCell = anchorCell?.mergeInfo?.endRow ?? anchorCell?.actualRow ?? -1;
+ const startColumnOfActiveCell = anchorCell?.mergeInfo?.startColumn ?? anchorCell?.actualColumn ?? -1;
+ const endColOfActiveCell = anchorCell?.mergeInfo?.endColumn ?? anchorCell?.actualColumn ?? -1;
+
+ let startRow = Math.min(cursorCellRange.startRow, startRowOfActiveCell);
+ if (startRowOfActiveCell === -1) {
+ startRow = cursorCellRange.startRow;
+ }
+
+ let startColumn = Math.min(cursorCellRange.startColumn, startColumnOfActiveCell);
+ if (startColumnOfActiveCell === -1) {
+ startColumn = cursorCellRange.startColumn;
+ }
let newSelectionRange: IRange = {
- startRow: Math.min(cursorCellRange.startRow, startRowOfActiveCell),
- startColumn: Math.min(cursorCellRange.startColumn, startColumnOfActiveCell),
+ startRow,
+ startColumn,
endRow: Math.max(cursorCellRange.endRow, endRowOfActiveCell),
endColumn: Math.max(cursorCellRange.endColumn, endColOfActiveCell),
};