Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat(sheets): scroll the grid while a drag nears or passes its edge (#8128)
teoeaa7670e7417
diff --git a/apps/web/src/features/block-spreadsheet/README.md b/apps/web/src/features/block-spreadsheet/README.mdindex 7ea013d894..593e8cdb13 100644--- a/apps/web/src/features/block-spreadsheet/README.md+++ b/apps/web/src/features/block-spreadsheet/README.md@@ -261,6 +261,19 @@ formula awaits a reference keeps its draft, even when the formula's row is pastthe other sheet's last row, and every tab change scrolls to that sheet's ownselection.+Dragging a range, row or column headers, the fill handle, a formula reference, or+a touch selection handle scrolls the grid while the pointer is within 24 pixels+of an edge of the cells or past it, and extends the drag to the cell under the+pointer or the nearest one in view. Speed grows with the pointer's depth into+that edge (20 pixels per second per pixel), and a header drag scrolls only along+its own axis. `components/drag-auto-scroll.ts` scrolls; the grid maps the+pointer to a cell and extends whichever drag is in progress. The sticky headers lie outside the cells, so scrolling up or left+starts at their inner edges and never selects a cell hidden beneath them. The+grid does not draw imported frozen panes, so the headers are its only fixed area.+A press scrolls only after it moves 8 pixels, so a click beside an edge does not.+When the window misses a drag's release (the pointer next moves without its+button), the drag is cancelled rather than finished, so no fill is applied.+Selection does not recalculate the workbook. A bounded row window mounts visiblerows and a small buffer, keeping the active editor mounted while scrolling. Sharedrow offsets account for wrapped text, font size, and zoom. Two overlays@@ -359,8 +372,8 @@ compare formula, error, and formatting behavior before replacing it.- **Format and data → Goal Seek…** finds the number that makes a formula cellreach a typed value, then writes it when confirmed. The search runs on a copyof the calculated workbook, so cancel leaves every cell as it was.-- Filters, editing named ranges, automatic spill expansion, and drag- auto-scroll remain future work.+- Filters, editing named ranges, and automatic spill expansion remain future+ work.- CSV import writes a validated rectangle at the active cell, appending rows whenneeded. It preserves existing cell styles and supports quoted multiline fields.CSV exports values and drops formatting. XLSX import/export converts supporteddiff --git a/apps/web/src/features/block-spreadsheet/browser-test/README.md b/apps/web/src/features/block-spreadsheet/browser-test/README.mdindex 9a69578d6b..64631b8925 100644--- a/apps/web/src/features/block-spreadsheet/browser-test/README.md+++ b/apps/web/src/features/block-spreadsheet/browser-test/README.md@@ -71,8 +71,8 @@ bunx playwright test --config src/features/block-spreadsheet/browser-test/playwr```The `android-chrome` (Pixel 7) and `iphone-webkit` (iPhone 13) projects exercise-touch taps, edit/apply/cancel, formula suggestions, selection/reference handles,-formatting menus, sheet creation/rename, find, viewer permissions, the narrow+touch taps, edit/apply/cancel, formula suggestions, selection/reference handles+(including a selection handle held past the bottom edge to scroll), formatting menus, sheet creation/rename, find, viewer permissions, the narrowfooter, and tapping between dropdown cells while a list is open. Landscape and reduced viewport checks cover layout with less verticalspace. Chromium swipes and handle drags use CDP's trusted touch input, includingnative scrolling and pointer cancellation; ribbon swipes must not format cells.@@ -112,4 +112,4 @@ explicit test document/socket query parameters are supplied.## Editor interaction regressions-`editor-interactions.browser.e2e.ts` mounts the real global hotkey listener to verify that selected-cell typing and arrows beat app navigation shortcuts. It also exercises multi-header drag/Shift selection, persistent row resizing and auto-fit, cross-sheet formula reference picking (including after comparison operators, from a row past the other sheet's end), and numeric/month-end date fill with undo. `formatting.browser.e2e.ts` checks mixed whole-column formatting, style persistence, viewport stability, a styled cell's pixels staying the same when selected, in a range and edited, and percentage entry through both editors against the real calculation worker.+`editor-interactions.browser.e2e.ts` mounts the real global hotkey listener to verify that selected-cell typing and arrows beat app navigation shortcuts. It also exercises multi-header drag/Shift selection, drags that scroll the grid past its bottom and right edges and back over the sticky headers to reach off-screen cells (including a fill-handle drag down to the last row), persistent row resizing and auto-fit, cross-sheet formula reference picking (including after comparison operators, from a row past the other sheet's end), and numeric/month-end date fill with undo. `formatting.browser.e2e.ts` checks mixed whole-column formatting, style persistence, viewport stability, a styled cell's pixels staying the same when selected, in a range and edited, and percentage entry through both editors against the real calculation worker.diff --git a/apps/web/src/features/block-spreadsheet/browser-test/editor-interactions.browser.e2e.ts b/apps/web/src/features/block-spreadsheet/browser-test/editor-interactions.browser.e2e.tsindex 015fc99f99..f0de5aa19d 100644--- a/apps/web/src/features/block-spreadsheet/browser-test/editor-interactions.browser.e2e.ts+++ b/apps/web/src/features/block-spreadsheet/browser-test/editor-interactions.browser.e2e.ts@@ -91,6 +91,115 @@ test('selects multiple rows and columns by dragging and shift-clicking headers',await expect(address).toHaveValue('A4');});+test('drag-selecting past the bottom edge scrolls to the last row in one gesture', async ({+ page,+}) => {+ const grid = page.getByRole('grid', { name: 'Spreadsheet' });+ const gridBox = await grid.boundingBox();+ const start = await page.locator('[data-address="B2"]').boundingBox();+ if (!gridBox || !start) throw new Error('Grid is not visible');+ await page.mouse.move(start.x + start.width / 2, start.y + start.height / 2);+ await page.mouse.down();+ // Below the grid, over the footer. Scrolling continues while it rests there.+ await page.mouse.move(+ start.x + start.width / 2,+ gridBox.y + gridBox.height + 12,+ { steps: 8 }+ );+ const address = page.getByRole('textbox', { name: 'Go to cell' });+ await expect(address).toHaveValue('B2:B200');+ await page.mouse.up();+ await expect(page.locator('[data-address="B200"]')).toBeInViewport();+ await expect(page.locator('[data-address="B200"]')).toHaveAttribute(+ 'aria-selected',+ 'true'+ );+ await expect(address).toHaveValue('B2:B200');+});++test('drag-selecting into the right edge scrolls to the last column', async ({+ page,+}) => {+ const grid = page.getByRole('grid', { name: 'Spreadsheet' });+ const gridBox = await grid.boundingBox();+ const start = await page.locator('[data-address="B2"]').boundingBox();+ if (!gridBox || !start) throw new Error('Grid is not visible');+ await page.mouse.move(start.x + start.width / 2, start.y + start.height / 2);+ await page.mouse.down();+ // Inside the grid, within the edge zone before its right edge.+ await page.mouse.move(+ gridBox.x + gridBox.width - 6,+ start.y + start.height / 2,+ { steps: 8 }+ );+ const address = page.getByRole('textbox', { name: 'Go to cell' });+ await expect(address).toHaveValue('B2:Z2');+ await page.mouse.up();+ await expect(page.locator('[data-address="Z2"]')).toBeInViewport();+ await expect(address).toHaveValue('B2:Z2');+});++test('dragging over the sticky headers scrolls back to the first row and column', async ({+ page,+}) => {+ const grid = page.getByRole('grid', { name: 'Spreadsheet' });+ await grid.evaluate((element) => {+ element.scrollTop = 630;+ element.scrollLeft = 500;+ });+ const cell = page.locator('[data-address="H40"]');+ await expect(cell).toBeInViewport();+ const gridBox = await grid.boundingBox();+ const start = await cell.boundingBox();+ if (!gridBox || !start) throw new Error('Grid is not visible');+ await page.mouse.move(start.x + start.width / 2, start.y + start.height / 2);+ await page.mouse.down();+ // The corner where the column letters meet the row numbers.+ await page.mouse.move(gridBox.x + 8, gridBox.y + 8, { steps: 8 });+ const address = page.getByRole('textbox', { name: 'Go to cell' });+ await expect(address).toHaveValue('A1:H40');+ await page.mouse.up();+ expect(+ await grid.evaluate((element) => [element.scrollTop, element.scrollLeft])+ ).toEqual([0, 0]);+ await expect(address).toHaveValue('A1:H40');+});++test('dragging the fill handle past the bottom edge fills down to the last row', async ({+ page,+}) => {+ await edit(page, 'D1', 'Paid');+ await page.locator('[data-address="D1"]').click();+ const grid = page.getByRole('grid', { name: 'Spreadsheet' });+ const gridBox = await grid.boundingBox();+ const handle = await page+ .getByRole('button', { name: 'Drag to fill selection' })+ .boundingBox();+ if (!gridBox || !handle) throw new Error('Fill handle is not visible');+ await page.mouse.move(+ handle.x + handle.width / 2,+ handle.y + handle.height / 2+ );+ await page.mouse.down();+ await page.mouse.move(+ handle.x + handle.width / 2,+ gridBox.y + gridBox.height + 12,+ { steps: 8 }+ );+ await expect(page.locator('[data-address="D200"]')).toHaveAttribute(+ 'aria-selected',+ 'true'+ );+ await page.mouse.up();+ await expect(page.locator('[data-address="D200"]')).toHaveText('Paid');+ const cells = await page.evaluate(+ () => window.spreadsheetFixture.snapshot()[0].cells+ );+ expect(cells.D2.value).toBe('Paid');+ expect(cells.D200.value).toBe('Paid');+ expect(cells.E200).toBeUndefined();+});+test('resizes row height with a pointer, saves it, and restores automatic height', async ({page,}) => {diff --git a/apps/web/src/features/block-spreadsheet/browser-test/spreadsheet.mobile.e2e.ts b/apps/web/src/features/block-spreadsheet/browser-test/spreadsheet.mobile.e2e.tsindex 0e56b175d5..faef980735 100644--- a/apps/web/src/features/block-spreadsheet/browser-test/spreadsheet.mobile.e2e.ts+++ b/apps/web/src/features/block-spreadsheet/browser-test/spreadsheet.mobile.e2e.ts@@ -17,8 +17,16 @@ async function center(locator: Locator): Promise<Point> {return { x: box.x + box.width / 2, y: box.y + box.height / 2 };}-/** Chromium delivers trusted touch input, including native scroll/pointercancel. */-async function androidDrag(page: Page, from: Point, to: Point) {+/**+ * Chromium delivers trusted touch input, including native scroll/pointercancel.+ * `hold` runs with the finger still down at `to`.+ */+async function androidDrag(+ page: Page,+ from: Point,+ to: Point,+ hold?: () => Promise<void>+) {const session = await page.context().newCDPSession(page);const touch = (point: Point) => ({ ...point, id: 1, radiusX: 4, radiusY: 4 });try {@@ -40,6 +48,7 @@ async function androidDrag(page: Page, from: Point, to: Point) {// does not exercise the browser's scroll recognition.await page.waitForTimeout(16);}+ await hold?.();await session.send('Input.dispatchTouchEvent', {type: 'touchEnd',touchPoints: [],@@ -50,13 +59,19 @@ async function androidDrag(page: Page, from: Point, to: Point) {}/** WebKit exposes touch taps, but no trusted touch drag API. */-async function webkitPointerHandleDrag(page: Page, handle: Locator, to: Point) {+async function webkitPointerHandleDrag(+ page: Page,+ handle: Locator,+ to: Point,+ hold?: () => Promise<void>+) {const from = await center(handle);// A browser mouse pointer exercises handle hit-testing and pointer capture;// it does not prove iOS native touch scrolling or gesture arbitration.await page.mouse.move(from.x, from.y);await page.mouse.down();await page.mouse.move(to.x, to.y, { steps: 12 });+ await hold?.();await page.mouse.up();}@@ -197,6 +212,38 @@ test('selection handles extend a range (WebKit drag uses a mouse pointer)', asynawait expect(cell(page, 'B5')).toHaveAttribute('aria-selected', 'false');});+test('a selection handle held past the bottom edge scrolls and extends the range (WebKit drag uses a mouse pointer)', async ({+ page,+ browserName,+}) => {+ await cell(page, 'A2').tap();+ const handle = button(page, 'Move selection end');+ await expect(handle).toBeVisible();+ const grid = page.getByRole('grid', { name: 'Spreadsheet' });+ const box = await grid.boundingBox();+ if (!box) throw new Error('Grid is missing.');+ const from = await center(handle);+ // Over the footer, below the grid, in column A.+ const to = {+ x: (await center(cell(page, 'A2'))).x,+ y: box.y + box.height + 20,+ };+ const lastRow = async () =>+ Number((await addressBar(page).inputValue()).match(/^A2:A(\d+)$/)?.[1]);+ const scrollsDown = async () => {+ await expect.poll(lastRow).toBeGreaterThanOrEqual(80);+ };+ if (browserName === 'chromium')+ await androidDrag(page, from, to, scrollsDown);+ else await webkitPointerHandleDrag(page, handle, to, scrollsDown);+ const row = await lastRow();+ await expect(cell(page, `A${row}`)).toBeInViewport();+ await expect(cell(page, `A${row}`)).toHaveAttribute('aria-selected', 'true');+ expect(await grid.evaluate((element) => element.scrollTop)).toBeGreaterThan(+ 1000+ );+});+test('touch formula suggestions and reference handles retain the editor (WebKit drag uses a mouse pointer)', async ({page,browserName,diff --git a/apps/web/src/features/block-spreadsheet/components/SpreadsheetGrid.test.tsx b/apps/web/src/features/block-spreadsheet/components/SpreadsheetGrid.test.tsxindex 0798007288..ebcba03a10 100644--- a/apps/web/src/features/block-spreadsheet/components/SpreadsheetGrid.test.tsx+++ b/apps/web/src/features/block-spreadsheet/components/SpreadsheetGrid.test.tsx@@ -152,6 +152,11 @@ function renderGrid();});const element = view.getByRole('grid');+ // Coordinates map to cells within the grid's client box, the mocked viewport.+ Object.defineProperties(element, {+ clientWidth: { configurable: true, value: 1000 },+ clientHeight: { configurable: true, value: 960 },+ });// jsdom has no layout or scrolling; only the selected cells need this DOM API.for (const address of ['A1', 'A2']) {const cell = view.container.querySelector<HTMLElement>(@@ -565,6 +570,130 @@ describe('spreadsheet pointer gestures across sheet changes', () => {});});+describe('spreadsheet drag auto-scroll', () => {+ function mouse(+ target: Element | Window,+ type: string,+ x: number,+ y: number,+ buttons = type === 'pointerup' ? 0 : 1+ ) {+ fireEvent(+ target,+ new MouseEvent(type, {+ button: 0,+ buttons,+ clientX: x,+ clientY: y,+ bubbles: true,+ cancelable: true,+ })+ );+ }++ it('scrolls once a drag moves, faster the farther past the edge, until release', () => {+ vi.useFakeTimers();+ onTestFinished(() => {+ vi.useRealTimers();+ });+ const view = renderGrid({}, { rowCount: 200 });+ // B45 spans y 948-969; the grid's client box ends at 960.+ mouse(view.getByRole('gridcell', { name: 'B45' }), 'pointerdown', 196, 950);+ mouse(window, 'pointermove', 196, 953);+ vi.advanceTimersToNextFrame();+ expect(view.element.scrollTop).toBe(0);++ // 34px into the bottom edge zone for a 16ms frame is 10.88px, then 134px+ // is 42.88px plus the carried 0.88px.+ mouse(window, 'pointermove', 196, 970);+ vi.advanceTimersToNextFrame();+ expect(view.element.scrollTop).toBe(10);+ mouse(window, 'pointermove', 196, 1070);+ vi.advanceTimersToNextFrame();+ expect(view.element.scrollTop).toBe(53);+ expect(view.controller.selection()).toEqual({+ anchor: { row: 44, column: 1 },+ focus: { row: 47, column: 1 },+ });++ mouse(window, 'pointerup', 196, 1070);+ vi.advanceTimersToNextFrame();+ expect(view.element.scrollTop).toBe(53);+ });++ it('keeps the scroll rate at slow speeds by carrying partial pixels between frames', () => {+ vi.useFakeTimers();+ onTestFinished(() => {+ vi.useRealTimers();+ });+ const view = renderGrid({}, { rowCount: 200 });+ mouse(view.getByRole('gridcell', { name: 'B45' }), 'pointerdown', 196, 950);+ // 1px into the bottom edge zone: 20px a second, 0.32px a 16ms frame.+ mouse(window, 'pointermove', 196, 937);+ for (let frame = 0; frame < 60; frame++) vi.advanceTimersToNextFrame();+ expect(view.element.scrollTop).toBe(19);+ });++ it('scrolls a column header drag only across, and stops when the release was missed', () => {+ vi.useFakeTimers();+ onTestFinished(() => {+ vi.useRealTimers();+ });+ const view = renderGrid();+ mouse(+ view.getByRole('button', { name: 'Select column B' }),+ 'pointerdown',+ 196,+ 12+ );+ mouse(window, 'pointermove', 1010, 1000);+ vi.advanceTimersToNextFrame();+ expect(view.element.scrollTop).toBe(0);+ expect(view.element.scrollLeft).toBe(10);+ expect(view.controller.selection()).toEqual({+ anchor: { row: 0, column: 1 },+ focus: { row: 29, column: 9 },+ });++ mouse(window, 'pointermove', 1010, 1000, 0);+ vi.advanceTimersToNextFrame();+ mouse(window, 'pointermove', 400, 500);+ vi.advanceTimersToNextFrame();+ expect(view.element.scrollLeft).toBe(10);+ expect(view.controller.selection().focus).toEqual({ row: 29, column: 9 });+ });++ it('cancels a fill whose release the window missed instead of applying it to the next drag', () => {+ const onFill = vi.fn();+ const view = renderGrid({}, { onFill });+ mouse(+ view.getByRole('button', { name: 'Drag to fill selection' }),+ 'pointerdown',+ 146,+ 45+ );+ mouse(window, 'pointermove', 146, 80);+ fireEvent(+ view.getByRole('gridcell', { name: 'A3' }),+ new MouseEvent('pointerenter', { buttons: 1 })+ );+ // Released outside the window: the next move arrives without the button.+ mouse(window, 'pointermove', 146, 80, 0);++ mouse(view.getByRole('gridcell', { name: 'B2' }), 'pointerdown', 196, 55);+ fireEvent(+ view.getByRole('gridcell', { name: 'B3' }),+ new MouseEvent('pointerenter', { buttons: 1 })+ );+ mouse(window, 'pointerup', 196, 76);+ expect(onFill).not.toHaveBeenCalled();+ expect(view.controller.selection()).toEqual({+ anchor: { row: 1, column: 1 },+ focus: { row: 2, column: 1 },+ });+ });+});+describe('spreadsheet grid clipboard and editing', () => {it('copies instead of marking formulas as moved when a viewer uses cut', () => {const view = renderGrid({ A1: { value: '=B1' } }, { readonly: true });diff --git a/apps/web/src/features/block-spreadsheet/components/SpreadsheetGrid.tsx b/apps/web/src/features/block-spreadsheet/components/SpreadsheetGrid.tsxindex 213fde9bd5..fdd55e525c 100644--- a/apps/web/src/features/block-spreadsheet/components/SpreadsheetGrid.tsx+++ b/apps/web/src/features/block-spreadsheet/components/SpreadsheetGrid.tsx@@ -62,6 +62,7 @@ import {cellForeground,dataBarBackground,} from './cell-colors';+import { createDragAutoScroll, DRAG_SLOP } from './drag-auto-scroll';import { FormulaInput } from './FormulaInput';import { type DrawingRect, SheetDrawingLayer } from './SheetDrawingLayer';import { type CellAction, SpreadsheetCellMenu } from './SpreadsheetCellMenu';@@ -86,7 +87,6 @@ const CELL_PADDING_X = 3;const CELL_PADDING_Y = 2;const CELL_LINE_HEIGHT = 1.2;const MAX_ROW_HEIGHT = 160;-const TOUCH_SLOP = 8;export function renderedSelectionCell(root: ParentNode | undefined,@@ -317,8 +317,6 @@ export function SpreadsheetGrid(props: {| {kind: 'selection' | 'reference';pointerId: number;- x: number;- y: number;fixed: CellPosition;startX: number;startY: number;@@ -327,7 +325,8 @@ export function SpreadsheetGrid(props: {}| undefined;let lastTap: { address: string; time: number } | undefined;- let autoScrollFrame: number | undefined;+ // The cell the drag in progress last extended to.+ let dragCell: string | undefined;const columnWidth = (column: number) =>resizing()?.column === column? resizing()!.width@@ -652,9 +651,8 @@ export function SpreadsheetGrid(props: {return `polygon(evenodd, 0 0, 100% 0, 100% 100%, 0 100%, 0 0, ${left}px ${top}px, ${right}px ${top}px, ${right}px ${bottom}px, ${left}px ${bottom}px, ${left}px ${top}px)`;};- function stopTouchGesture() {- if (autoScrollFrame !== undefined) cancelAnimationFrame(autoScrollFrame);- autoScrollFrame = undefined;+ function stopDrag() {+ autoScroll.stop();touchGesture = undefined;}@@ -684,12 +682,12 @@ export function SpreadsheetGrid(props: {function endPointer(event: PointerEvent) {if (touchGesture && event.pointerId !== touchGesture.pointerId) return;const gesture = touchGesture;- stopTouchGesture();+ stopDrag();if (gesture?.kind === 'tap' &&!gesture.moved &&Math.hypot(event.clientX - gesture.x, event.clientY - gesture.y) <=- TOUCH_SLOP+ DRAG_SLOP) {tapCell(gesture.position, event.timeStamp);} else if (@@ -700,7 +698,7 @@ export function SpreadsheetGrid(props: {Math.hypot(event.clientX - gesture.startX,event.clientY - gesture.startY- ) <= TOUCH_SLOP+ ) <= DRAG_SLOP) {// The accessible grip extends over nearby cells. A tap in its invisible// padding should still select that cell; only a drag claims the grip.@@ -732,7 +730,7 @@ export function SpreadsheetGrid(props: {}function cancelPointer() {- stopTouchGesture();+ stopDrag();lastTap = undefined;dragging = false;headerDrag = undefined;@@ -846,15 +844,25 @@ export function SpreadsheetGrid(props: {const anchor = event.shiftKey ? props.selection.anchor[axis] : index;headerDrag = { axis, anchor };selectHeaderRange(axis, index, anchor);+ followPointer(event);};+ /**+ * The cell at a point. Cells hidden under the sticky headers or outside the+ * visible area give way to the nearest cell in view.+ */function positionAtPoint(x: number, y: number): CellPosition {const rect = grid.getBoundingClientRect();- const column = offsetIndex(- columnOffsets(),- x - rect.left + grid.scrollLeft+ const left = Math.max(+ headerWidth(),+ Math.min(x - rect.left, grid.clientWidth - 1));- const row = offsetIndex(rowOffsets(), y - rect.top + grid.scrollTop);+ const top = Math.max(+ headerHeight(),+ Math.min(y - rect.top, grid.clientHeight - 1)+ );+ const column = offsetIndex(columnOffsets(), left + grid.scrollLeft);+ const row = offsetIndex(rowOffsets(), top + grid.scrollTop);// Offsets start at the first cell after the headers.return {row: Math.min(rowCount() - 1, row),@@ -862,43 +870,49 @@ export function SpreadsheetGrid(props: {};}- function moveTouchHandle() {+ /** Extend the drag in progress (range, header, fill, or reference) to a cell. */+ function dragTo(position: CellPosition) {+ const address = cellAddress(position);+ if (address === dragCell) return;+ dragCell = address;const gesture = touchGesture;- if (!gesture || gesture.kind === 'tap' || !gesture.moved) return;- const position = positionAtPoint(gesture.x, gesture.y);- if (gesture.kind === 'reference') props.onReferenceMove?.(position);- else props.onSelectRange(gesture.fixed, position);+ if (headerDrag)+ selectHeaderRange(+ headerDrag.axis,+ position[headerDrag.axis],+ headerDrag.anchor+ );+ else if (gesture?.kind === 'reference') props.onReferenceMove?.(position);+ else if (gesture?.kind === 'selection')+ props.onSelectRange(gesture.fixed, position);+ else if (props.pickingReference) props.onReferenceMove?.(position);+ else if (fillSource) previewFill(position);+ else if (dragging) props.onSelect(position, true);}- function scrollTouchHandle() {- const gesture = touchGesture;- if (!gesture || gesture.kind === 'tap' || !gesture.moved) return;- const rect = grid.getBoundingClientRect();- const step = (point: number, start: number, end: number) =>- point < start + 24 ? -10 : point > end - 24 ? 10 : 0;- const x = step(gesture.x, rect.left + headerWidth(), rect.right);- const y = step(gesture.y, rect.top + headerHeight(), rect.bottom);- if (x || y) {- const previousLeft = grid.scrollLeft;- const previousTop = grid.scrollTop;- grid.scrollLeft += x;- grid.scrollTop += y;- if (previousLeft !== grid.scrollLeft || previousTop !== grid.scrollTop) {- setScrollTop(grid.scrollTop);- moveTouchHandle();- }- }- autoScrollFrame = requestAnimationFrame(scrollTouchHandle);+ const autoScroll = createDragAutoScroll({+ element: () => grid,+ inset: () => ({ left: headerWidth(), top: headerHeight() }),+ axis: () => headerDrag && (headerDrag.axis === 'column' ? 'x' : 'y'),+ onEdge: (x, y) => {+ // Render the rows and columns coming into view before the scroll event.+ setScrollLeft(grid.scrollLeft);+ setScrollTop(grid.scrollTop);+ dragTo(positionAtPoint(x, y));+ },+ // Ending would apply a fill or reference whose release point is unknown.+ onLostRelease: cancelPointer,+ });++ function followPointer(event: PointerEvent, moved?: boolean) {+ dragCell = undefined;+ autoScroll.follow(event, moved);}function movePointer(event: PointerEvent) {+ autoScroll.move(event);if (headerDrag && event.buttons === 1) {- const position = positionAtPoint(event.clientX, event.clientY);- selectHeaderRange(- headerDrag.axis,- position[headerDrag.axis],- headerDrag.anchor- );+ dragTo(positionAtPoint(event.clientX, event.clientY));return;}const gesture = touchGesture;@@ -906,7 +920,7 @@ export function SpreadsheetGrid(props: {if (gesture.kind === 'tap') {if (Math.hypot(event.clientX - gesture.x, event.clientY - gesture.y) >- TOUCH_SLOP+ DRAG_SLOP) {gesture.moved = true;lastTap = undefined;@@ -919,16 +933,14 @@ export function SpreadsheetGrid(props: {Math.hypot(event.clientX - gesture.startX,event.clientY - gesture.startY- ) <= TOUCH_SLOP+ ) <= DRAG_SLOP)return;gesture.moved = true;lastTap = undefined;- autoScrollFrame = requestAnimationFrame(scrollTouchHandle);+ followPointer(event, true);}- gesture.x = event.clientX;- gesture.y = event.clientY;- moveTouchHandle();+ dragTo(positionAtPoint(event.clientX, event.clientY));}const touchRange = () => props.referenceSelection ?? props.selection;@@ -954,7 +966,7 @@ export function SpreadsheetGrid(props: {rect.top -grid.scrollTop;const tapPosition =- Math.hypot(event.clientX - handleX, event.clientY - handleY) > TOUCH_SLOP+ Math.hypot(event.clientX - handleX, event.clientY - handleY) > DRAG_SLOP? positionAtPoint(event.clientX, event.clientY): undefined;keepReferenceFocus =@@ -964,8 +976,6 @@ export function SpreadsheetGrid(props: {touchGesture = {kind: reference ? 'reference' : 'selection',pointerId: event.pointerId,- x: event.clientX,- y: event.clientY,startX: event.clientX,startY: event.clientY,moved: false,@@ -1113,7 +1123,7 @@ export function SpreadsheetGrid(props: {type,onDocumentClipboard as EventListener);- stopTouchGesture();+ stopDrag();});});@@ -1801,6 +1811,7 @@ export function SpreadsheetGrid(props: {keepReferenceFocus =props.onReferenceStart?.({ row, column }) ??false;+ followPointer(event);if (keepReferenceFocus) return;dragging = true;closeOrMoveList({ row, column }, event.shiftKey);@@ -1809,16 +1820,7 @@ export function SpreadsheetGrid(props: {}}onPointerEnter={(event) => {if (event.pointerType === 'touch') return;- if (props.pickingReference && event.buttons === 1) {- props.onReferenceMove?.({ row, column });- return;- }- if (fillSource && event.buttons === 1) {- previewFill({ row, column });- return;- }- if (dragging && event.buttons === 1)- props.onSelect({ row, column }, true);+ if (event.buttons === 1) dragTo({ row, column });else dragging = false;}}onDblClick={() => {@@ -2259,6 +2261,7 @@ export function SpreadsheetGrid(props: {fillGeneration++;fillSource = props.selection;setFillTarget(props.selection);+ followPointer(event);focusGrid();}}/>diff --git a/apps/web/src/features/block-spreadsheet/components/drag-auto-scroll.ts b/apps/web/src/features/block-spreadsheet/components/drag-auto-scroll.tsnew file mode 100644index 0000000000..e4709ad747--- /dev/null+++ b/apps/web/src/features/block-spreadsheet/components/drag-auto-scroll.ts@@ -0,0 +1,114 @@+import { onCleanup } from 'solid-js';++/** How far a press moves before it is a drag rather than a tap or click. */+export const DRAG_SLOP = 8;+/** Pixels inside each edge of the visible area where a drag starts scrolling. */+const EDGE = 24;+/** Scroll speed, in pixels per second, per pixel of the pointer's edge depth. */+const RATE = 20;++/**+ * How far a point is into the edge zones of a visible span: negative toward+ * its start, positive toward its end, and 0 between them.+ */+function edgeDepth(point: number, start: number, end: number) {+ const edge = Math.min(EDGE, (end - start) / 4);+ if (point < start + edge) return point - start - edge;+ if (point > end - edge) return point - end + edge;+ return 0;+}++/**+ * Scroll a container while a dragged pointer is near or past the edges of its+ * visible area, faster the farther out it is. Sticky headers (`inset`) stay in+ * place, so the start edges are their inner sides.+ */+export function createDragAutoScroll(options: {+ element: () => HTMLElement;+ inset: () => { left: number; top: number };+ /** The only axis to scroll, for a drag that moves along one. */+ axis: () => 'x' | 'y' | undefined;+ /** Each frame the pointer is in an edge zone, after scrolling. */+ onEdge: (x: number, y: number) => void;+ /** The followed pointer moved without its button; the window missed its release. */+ onLostRelease: () => void;+}) {+ let pointer:+ | {+ id: number;+ x: number;+ y: number;+ time?: number;+ carryX: number;+ carryY: number;+ }+ | undefined;+ let frame: number | undefined;++ function scroll(time: number) {+ if (!pointer) return;+ frame = requestAnimationFrame(scroll);+ const elapsed = Math.min(100, time - (pointer.time ?? time - 16));+ pointer.time = time;+ const element = options.element();+ const rect = element.getBoundingClientRect();+ const inset = options.inset();+ const axis = options.axis();+ const x =+ axis === 'y'+ ? 0+ : edgeDepth(pointer.x - rect.left, inset.left, element.clientWidth);+ const y =+ axis === 'x'+ ? 0+ : edgeDepth(pointer.y - rect.top, inset.top, element.clientHeight);+ // Scroll whole pixels and carry the rest, so slow speeds keep their rate+ // at any frame rate.+ const distanceX = x && pointer.carryX + (x * RATE * elapsed) / 1000;+ const distanceY = y && pointer.carryY + (y * RATE * elapsed) / 1000;+ pointer.carryX = distanceX % 1;+ pointer.carryY = distanceY % 1;+ if (!x && !y) return;+ element.scrollLeft += Math.trunc(distanceX);+ element.scrollTop += Math.trunc(distanceY);+ options.onEdge(pointer.x, pointer.y);+ }++ function stop() {+ if (frame !== undefined) cancelAnimationFrame(frame);+ frame = undefined;+ pointer = undefined;+ }+ onCleanup(stop);++ return {+ /** Follow a drag's pointer: from its first move, or now when `moved`. */+ follow(event: PointerEvent, moved = false) {+ stop();+ pointer = {+ id: event.pointerId,+ x: event.clientX,+ y: event.clientY,+ carryX: 0,+ carryY: 0,+ };+ if (moved) frame = requestAnimationFrame(scroll);+ },+ move(event: PointerEvent) {+ if (!pointer || pointer.id !== event.pointerId) return;+ if (!(event.buttons & 1)) {+ stop();+ options.onLostRelease();+ } else if (+ frame !== undefined ||+ Math.hypot(event.clientX - pointer.x, event.clientY - pointer.y) >+ DRAG_SLOP+ ) {+ pointer.x = event.clientX;+ pointer.y = event.clientY;+ frame ??= requestAnimationFrame(scroll);+ }+ },+ stop,+ };+}diff --git a/docs/agent-guide/documents.md b/docs/agent-guide/documents.mdindex 6a0ec9dbc6..ec325987a0 100644--- a/docs/agent-guide/documents.md+++ b/docs/agent-guide/documents.md@@ -229,6 +229,12 @@ that read a kept pivot table calculate from its cells, so editing a value in theDeleting a sheet whose data a chart on another sheet reads keeps the chart: itshows the values it had, which no longer change.+Drag across cells to select a range. Holding the pointer near or past an edge of+the grid (including over the row numbers or column letters) scrolls it, faster+the farther out it is, so one drag reaches off-screen cells; the fill handle,+header drags, formula reference picking, and phone selection handles scroll the+same way.+Select a cell to inspect its address and input in the formula bar. Double-clicka cell, start typing, or use the formula bar to edit its value. Formulas beginwith `=` and may refer to cells or ranges, for example `=SUM(B2:B5)`. Check both