Add workspace sidebar drag autoscroll (#3027)

Co-authored-by: Orca <help@stably.ai>
This commit is contained in:
Jinwoo Hong
2026-05-28 21:52:08 -07:00
committed by GitHub
co-authored by Orca
parent 0caef5c340
commit 476f9084ec
4 changed files with 891 additions and 73 deletions
+139
View File
@@ -0,0 +1,139 @@
# Worktree Sidebar Drag Autoscroll
## Problem
The left sidebar supports reordering worktree rows, but holding a drag near the top or bottom of the scrollable sidebar does not continue scrolling.
- `src/renderer/src/components/sidebar/WorktreeList.tsx:399` keeps active worktree drag state and cached group rects.
- `src/renderer/src/components/sidebar/WorktreeList.tsx:757` computes the drop from `clientY`, the current sidebar `getBoundingClientRect()`, and `scrollTop`.
- `src/renderer/src/components/sidebar/WorktreeList.tsx:1400` updates the custom pointer drag only after pointer events.
- `src/renderer/src/components/sidebar/WorktreeList.tsx:1660` uses the native drag path for card drag start/over/drop.
- `src/renderer/src/components/sidebar/WorktreeList.tsx:1920` renders the scroll container as `[data-worktree-sidebar]`.
## Current Behavior
The custom pointer path promotes to an active drag after `SIDEBAR_POINTER_DRAG_THRESHOLD_PX`, creates a fixed preview, stores a `WorktreeDragSession`, and schedules `flushWorktreePointerDrag()` on pointer movement. Drop still uses `computeWorktreeDrop()` and `onReorderWorktrees()`. If `computeWorktreeDrop()` returns null, pointer drops may instead pin or move the worktree to a workspace status target.
The native HTML5 handlers still exist: they store the same `WorktreeDragSession` on `onCardDragStart`, compute the reorder preview in `onDragOver`, commit through `onDrop` or the capture-phase document drop handler, and clear on `onCardDragEnd` through `WorktreeCard`. In the current list rendering, `WorktreeCard` is passed `nativeDragEnabled={false}`, so the active user-facing worktree reorder path is the custom pointer path. If the native handlers remain in place, keep them consistent; workspace status/pin drops are already handled by `useWorkspaceStatusDocumentDrop()`.
Scroll bookkeeping already exists. `handleScroll()` calls `markScrollMovement()`, which suppresses virtualizer measurement correction. Direct wheel/touch/scrollbar input additionally calls `markDirectScrollInput()`, which blocks anchor restoration retries. Autoscroll must mark programmatic movement, not direct user input.
## Root Cause
Both drag paths are event-driven. When the pointer is held at a sidebar edge, no frame loop changes `scrollTop`; without a scroll change, the virtualized list does not reveal farther rows and `computeWorktreeDrop()` keeps evaluating against the same viewport.
There is also a virtualization constraint: `computeWorktreeDrop()` only considers `worktreeDragSessionRef.current.rects`, which are a snapshot of the source group's mounted rows at drag start. Autoscroll would reveal new rows but still reject drops outside the original snapshot unless the active session refreshes its source-group rects from the current DOM. Refreshing rects must stay limited to the same `sourceGroupKey`; ordering still commits through the existing `worktreeDragUnitGroups`, `getFullDropIndexForWorktreeDragUnit()`, and `onReorderWorktrees()` path.
## Non-Goals
- Do not change manual ordering, rank persistence, group membership, lineage expansion, selection, pinning, or workspace status semantics.
- Do not change the workspace board drawer drag behavior.
- Do not add settings, controls, new visual affordances, IPC, persistence, SSH, filesystem, or git-provider behavior.
## Design
1. Add a concrete helper for sidebar drag autoscroll, for example `worktree-sidebar-drag-autoscroll.ts`. It should compute a bounded next `scrollTop` from:
- latest pointer `clientX`/`clientY`;
- container bounds;
- `scrollTop`, `scrollHeight`, and `clientHeight`;
- elapsed frame time, clamped so a throttled/background frame cannot jump the list.
2. The helper must return no-op when the pointer is outside the container horizontally, the pointer is outside the vertical edge zones, or the container is already at the relevant scroll bound.
3. Add a small session refresh helper that replaces `worktreeDragSessionRef.current` with the latest `getWorktreeDragRectsForGroup(scrollRef.current, session.sourceGroupKey)` result and revalidates the latest groups: `worktreeDragGroups` must still contain the source group and `session.draggingWorktreeId`, and `worktreeDragUnitGroups` must still contain `session.reorderUnitDraggedIds` for the same `sourceGroupKey`. Do not require every `session.reorderDraggedIds` entry to be in the source group, because the existing multi-select/lineage reorder path filters those ids during commit. If the source group or reordered unit ids disappear, clear the drag instead of committing stale ids.
4. Track autoscroll animation frame ids separately from `WorktreePointerDrag.frameId`. The existing `frameId` is for preview/drop flushing; sharing it would make it easy to cancel the wrong work or skip a needed preview update.
5. Pointer drag path:
- start autoscroll only after `beginWorktreePointerDrag()` promotes the drag to active;
- each autoscroll frame reads the latest `drag.currentX/currentY`;
- apply `container.scrollTop = nextScrollTop` only when it changes;
- call `markScrollMovement()` before or immediately after the scroll write instead of `markDirectScrollInput()`;
- refresh source-group rects from the mounted DOM before recomputing a drop; if the virtualizer has not rendered the newly exposed rows yet, keep the current null-drop behavior for that frame;
- schedule `scheduleWorktreePointerDragFrame(drag)` after a scroll write so the preview line is recomputed against the new `scrollTop` and refreshed rects.
6. Native drag path, if it is kept or re-enabled:
- store the latest native drag-over `clientX/clientY` in a small ref while a `WorktreeDragSession` exists;
- run a separate autoscroll frame loop from `onDragOver`;
- after a scroll write, refresh source-group rects, recompute the native drop preview from the stored `clientY`, and update `worktreeDragState`;
- set `event.dataTransfer.dropEffect = 'move'` only inside real `dragover`/`drop` event handlers when the current drop is valid. A RAF callback cannot update the native drag cursor/effect; it can only update sidebar preview state until the next native drag event.
7. Cleanup must cancel both pointer and native autoscroll loops on drop, document drop, dragend, pointerup, pointercancel, document visibility loss, component unmount, and `clearWorktreeDrag()`.
Keep the implementation local to the renderer sidebar. The scroll container remains `scrollRef.current`; do not query arbitrary sidebars globally.
## Data Flow
Pointer:
- Pointer down snapshots source-group rects and arms a non-active pointer drag.
- Pointer move beyond the threshold promotes to active, creates the preview, stores the drag session, and starts autoscroll.
- Autoscroll frames update `scrollTop` when the latest pointer point is in an edge zone.
- After each scroll write, the active session refreshes source-group rects from the current DOM and the normal pointer drag frame recomputes the drop preview using the existing `computeWorktreeDrop()`.
- Pointer up commits through the existing `onReorderWorktrees()` path, or through the existing pin/status fallback when no reorder drop is valid.
Native:
- If enabled, native drag start stores the drag session and cached source-group rects.
- Native drag over stores the latest point, computes the current drop, and starts autoscroll.
- Autoscroll frames reuse the latest stored point to update scroll, refresh source-group rects, and recompute preview. They do not try to set `DataTransfer.dropEffect`.
- Native drop/document drop commits through the existing reorder path; dragend clears state.
## Edge Cases
- Top and bottom bounds: do not keep writing the same `scrollTop`.
- Horizontal outside: no sidebar autoscroll if `clientX` is left or right of the scroll container.
- Vertical outside: allow scrolling when `clientY` is at or slightly beyond the top/bottom edge, but cap speed.
- Threshold: custom pointer autoscroll must not start before the existing drag threshold.
- Native event sparsity: continue from the last known drag-over point while events pause, but stop on dragend/drop/visibility loss.
- Drop validity while scrolling: if refreshed source-group rects still do not cover the pointer after scroll, preserve the current null-drop behavior rather than guessing a new index.
- Virtualized rows: rows can mount/unmount while scrolling. Refresh rects from `[data-worktree-drag-id]` for the source group only, and tolerate a frame where the virtualizer has not mounted newly visible rows yet.
- Source mutations: if the dragged worktree, source group, or reorder unit disappears during drag, clear the drag instead of committing against stale ids.
- Concurrent ordering changes: final drop should use the latest `worktreeDragGroups`/`worktreeDragUnitGroups` already captured by React callbacks, but the source group and reordered unit ids must be revalidated before commit. Do not rederive a different dragged set mid-drag.
- Multi-window/external mutations: this is renderer-local UI state. Do not persist autoscroll state or broadcast it; external list mutations should only invalidate or clear the active drag.
- Workspace status and pin targets: preserve pointer fallback behavior and do not make native reorder autoscroll steal document-level status/pin drops. The capture-phase document reorder handler should only prevent default/stop propagation when `computeWorktreeDrop()` returns a valid reorder drop.
- Unmount/remount: cancel animation frames and remove previews/styles in the existing cleanup path.
## Test Plan
- Unit: add tests for the autoscroll calculation helper covering top edge, bottom edge, middle no-op, horizontal outside, scroll bounds, capped speed, and elapsed-time scaling.
- Unit: add tests for the rect/session refresh helper with same-group refresh, missing source group, missing dragged ids, and empty mounted rects.
- Unit: add tests for any extracted native/pointer loop coordinator only if it can run without a full virtualized React render.
- Unit: keep `worktree-manual-order.test.ts` and `worktree-drag-units.test.ts` passing to prove rank and drag-unit semantics did not change.
- Typecheck/lint: run `pnpm run typecheck` and `pnpm run lint`.
- Focused tests: run `pnpm test -- src/renderer/src/components/sidebar/worktree-manual-order.test.ts src/renderer/src/components/sidebar/worktree-drag-units.test.ts` plus the new autoscroll helper tests.
- Electron/manual: validate a long worktree list by dragging near the bottom until the list scrolls, dropping, then dragging near the top until it scrolls back. Also smoke native drag if it is reachable in the current app configuration.
## UI Quality Bar
Follow `docs/STYLEGUIDE.md` and the existing sidebar tokens. This change should not introduce new colors, shadows, controls, or copy. The only visible behavior change is smooth scrolling while dragging near the sidebar edge. The existing floating preview, insertion line, row opacity, status/pin highlights, focus ring, and sidebar scrollbar styling should remain unchanged.
No clipping, flicker, stuck insertion line, unexpected row jump, or preview lag should appear during autoscroll.
## Review Screenshots
Required evidence:
1. Sidebar precondition with enough worktrees to scroll.
2. Pointer drag held near the bottom edge after autoscroll advances the list, with preview and insertion line visible.
3. Pointer drag held near the top edge after autoscroll moves back upward, with preview and insertion line visible.
4. Final dropped order visible in the sidebar.
Optional evidence if native drag is enabled in the tested build:
5. Native drag autoscroll in progress or a note explaining why native drag could not be exercised.
Do not commit evidence images.
## Rollout
1. Add `worktree-sidebar-drag-autoscroll.ts` and focused unit tests.
2. Add session rect refresh/revalidation and use it before drag preview/drop recomputation during active autoscroll.
3. Wire custom pointer-drag autoscroll with separate frame cleanup.
4. If the native handlers remain supported or are re-enabled, wire native drag-over autoscroll with latest-point storage and document dragend/drop cleanup, keeping `dropEffect` writes inside drag events.
5. Run typecheck, lint, focused sidebar tests, and Electron validation with screenshots.
## Lightweight Eng Review
- Scope: correctly limited to the worktree sidebar drag paths. The plan must not touch persistence, ordering algorithms, workspace board drawer drag, SSH, filesystem, or git-provider code.
- Architecture/data flow: renderer-only helper is appropriate. Pointer and native drag should share the scroll calculation and rect refresh/revalidation, not necessarily the same animation-frame state, because their preview/drop update paths differ.
- Failure modes: frame leaks, stale last drag-over points, redundant bound writes, stale session ids after external mutations, virtualization gaps, document-level status/pin drops, invalid `dropEffect` assumptions, and unmount cleanup are in scope.
- Tests: pure scroll helper and rect-refresh tests are required. Full virtualized pointer behavior is not a good jsdom target; use focused unit tests plus Electron/manual validation. Existing manual-order tests are regression tests only, not evidence that autoscroll works.
- Performance/blast radius: one RAF loop per active drag path is acceptable only while a drag session exists. Avoid layout thrash by reading container rect once per frame before writing `scrollTop`, and avoid React state writes when the recomputed preview is unchanged.
- UI quality: no new design surface. Verify smoothness, insertion-line accuracy, existing preview styling, and absence of row jumps against the style guide.
- Screenshot requirement: screenshots are required for review evidence but must not be committed.
- Residual risks: native drag event behavior differs across Electron/platforms, and virtualized rows may lag one frame behind programmatic scroll writes. Validate the main pointer path first and explicitly document any native limitation found during implementation.
@@ -126,6 +126,15 @@ import {
setSidebarPointerDragDocumentStyles,
updateSidebarDragPreviewPosition
} from './worktree-sidebar-pointer-drag-dom'
import {
getWorktreeSidebarDragAutoscroll,
getWorktreeSidebarBoundaryDrop,
getWorktreeSidebarDragRectsForGroup,
refreshWorktreeSidebarDragSession,
type WorktreeSidebarDragRect,
type WorktreeSidebarDragSession,
type WorktreeSidebarDragPoint
} from './worktree-sidebar-drag-autoscroll'
import { resolveProjectGroupHeaderColor } from './project-header-color'
import {
areWorktreeSelectionsEqual,
@@ -389,22 +398,6 @@ const WORKTREE_ROW_DRAG_INITIAL_STATE: WorktreeRowDragState = {
pointerY: null
}
type WorktreeDragRect = {
worktreeId: string
groupIndex: number
top: number
bottom: number
}
type WorktreeDragSession = {
draggingWorktreeId: string
sourceGroupKey: string
draggedIds: readonly string[]
reorderDraggedIds: readonly string[]
reorderUnitDraggedIds: readonly string[]
rects: readonly WorktreeDragRect[]
}
type VirtualItemBounds = {
index: number
start: number
@@ -423,7 +416,7 @@ type WorktreePointerDrag = {
reorderDraggedIds: readonly string[]
reorderUnitDraggedIds: readonly string[]
sourceGroupKey: string
rects: readonly WorktreeDragRect[]
rects: readonly WorktreeSidebarDragRect[]
active: boolean
preview: HTMLElement | null
previewOffsetX: number
@@ -460,34 +453,6 @@ function getWorktreeVirtualRowTransform(start: number, previewOffset: number): s
return previewOffset === 0 ? base : `${base} translateY(${previewOffset}px)`
}
function getWorktreeDragRectsForGroup(
container: HTMLElement,
groupKey: string
): WorktreeDragRect[] {
const containerRect = container.getBoundingClientRect()
const rects: WorktreeDragRect[] = []
container.querySelectorAll<HTMLElement>('[data-worktree-drag-id]').forEach((element) => {
if (element.getAttribute('data-worktree-drag-group-key') !== groupKey) {
return
}
const worktreeId = element.getAttribute('data-worktree-drag-id')
const rawGroupIndex = element.getAttribute('data-worktree-drag-group-index')
const groupIndex = rawGroupIndex === null ? Number.NaN : Number(rawGroupIndex)
if (!worktreeId || !Number.isFinite(groupIndex)) {
return
}
const rect = element.getBoundingClientRect()
rects.push({
worktreeId,
groupIndex,
top: rect.top - containerRect.top + container.scrollTop,
bottom: rect.bottom - containerRect.top + container.scrollTop
})
})
rects.sort((a, b) => a.top - b.top)
return rects
}
function getPointerDropStatusTarget(args: { container: HTMLElement; x: number; y: number }): {
status: WorkspaceStatus | null
isPinDrop: boolean
@@ -670,8 +635,13 @@ const VirtualizedWorktreeViewport = React.memo(function VirtualizedWorktreeViewp
const [highlightedRevealWorktreeId, setHighlightedRevealWorktreeId] = useState<string | null>(
null
)
const worktreeDragSessionRef = useRef<WorktreeDragSession | null>(null)
const worktreeDragSessionRef = useRef<WorktreeSidebarDragSession | null>(null)
const worktreePointerDragRef = useRef<WorktreePointerDrag | null>(null)
const worktreePointerAutoscrollFrameIdRef = useRef<number | null>(null)
const worktreePointerAutoscrollLastFrameTimeRef = useRef<number | null>(null)
const worktreeNativeAutoscrollFrameIdRef = useRef<number | null>(null)
const worktreeNativeAutoscrollLastFrameTimeRef = useRef<number | null>(null)
const worktreeNativeLatestPointRef = useRef<WorktreeSidebarDragPoint | null>(null)
const pendingRevealRetryRef = useRef<{ worktreeId: string; count: number } | null>(null)
const revealHighlightTimeoutRef = useRef<number | null>(null)
const flashRevealedWorktree = useCallback((worktreeId: string) => {
@@ -754,6 +724,22 @@ const VirtualizedWorktreeViewport = React.memo(function VirtualizedWorktreeViewp
() => getWorktreeDragIndexes(worktreeDragUnitGroups),
[worktreeDragUnitGroups]
)
const refreshWorktreeDragSession = useCallback((): boolean => {
const session = worktreeDragSessionRef.current
const container = scrollRef.current
if (!session || !container) {
return false
}
const refreshedSession = refreshWorktreeSidebarDragSession({
session,
groups: worktreeDragGroups,
unitGroups: worktreeDragUnitGroups,
rects: getWorktreeSidebarDragRectsForGroup(container, session.sourceGroupKey)
})
worktreeDragSessionRef.current = refreshedSession
return refreshedSession !== null
}, [worktreeDragGroups, worktreeDragUnitGroups])
const computeWorktreeDrop = useCallback(
(pointerY: number): WorktreeDropPreview | null => {
const session = worktreeDragSessionRef.current
@@ -768,35 +754,46 @@ const VirtualizedWorktreeViewport = React.memo(function VirtualizedWorktreeViewp
if (rects.length === 0) {
return null
}
const sourceGroup = worktreeDragUnitGroups.find(
(group) => group.key === session.sourceGroupKey
)
if (!sourceGroup) {
return null
}
const first = rects[0]!
const last = rects.at(-1)!
const BOUNDS_PADDING_PX = 8
if (localY < first.top - BOUNDS_PADDING_PX || localY > last.bottom + BOUNDS_PADDING_PX) {
const boundaryDrop = getWorktreeSidebarBoundaryDrop({
localY,
firstRect: first,
lastRect: last,
sourceGroupSize: sourceGroup.worktreeIds.length
})
if (boundaryDrop.kind === 'outside') {
return null
}
let dropIndex = last.groupIndex + 1
let indicatorY = last.bottom + 3
for (const rect of rects) {
const mid = (rect.top + rect.bottom) / 2
if (localY < mid) {
dropIndex = rect.groupIndex
indicatorY = Math.max(0, rect.top - 3)
break
if (boundaryDrop.kind === 'drop') {
dropIndex = boundaryDrop.dropIndex
indicatorY = boundaryDrop.indicatorY
} else {
for (const rect of rects) {
const mid = (rect.top + rect.bottom) / 2
if (localY < mid) {
dropIndex = rect.groupIndex
indicatorY = Math.max(0, rect.top - 3)
break
}
}
}
const sourceGroup = worktreeDragUnitGroups.find(
(group) => group.key === session.sourceGroupKey
)
const previewOffsetsByWorktreeId = sourceGroup
? buildWorktreeDragPreviewOffsets({
groupIds: sourceGroup.worktreeIds,
draggedIds: session.reorderUnitDraggedIds,
dropIndex,
rects
})
: EMPTY_WORKTREE_DRAG_PREVIEW_OFFSETS
const previewOffsetsByWorktreeId = buildWorktreeDragPreviewOffsets({
groupIds: sourceGroup.worktreeIds,
draggedIds: session.reorderUnitDraggedIds,
dropIndex,
rects
})
return { dropIndex, dropIndicatorY: indicatorY, previewOffsetsByWorktreeId }
},
[worktreeDragUnitGroups]
@@ -1370,8 +1367,26 @@ const VirtualizedWorktreeViewport = React.memo(function VirtualizedWorktreeViewp
}
}, [])
const cancelWorktreePointerAutoscroll = useCallback(() => {
if (worktreePointerAutoscrollFrameIdRef.current !== null) {
window.cancelAnimationFrame(worktreePointerAutoscrollFrameIdRef.current)
worktreePointerAutoscrollFrameIdRef.current = null
}
worktreePointerAutoscrollLastFrameTimeRef.current = null
}, [])
const cancelWorktreeNativeAutoscroll = useCallback(() => {
if (worktreeNativeAutoscrollFrameIdRef.current !== null) {
window.cancelAnimationFrame(worktreeNativeAutoscrollFrameIdRef.current)
worktreeNativeAutoscrollFrameIdRef.current = null
}
worktreeNativeAutoscrollLastFrameTimeRef.current = null
worktreeNativeLatestPointRef.current = null
}, [])
const cleanupWorktreePointerDrag = useCallback(() => {
const drag = worktreePointerDragRef.current
cancelWorktreePointerAutoscroll()
if (!drag) {
return
}
@@ -1383,13 +1398,14 @@ const VirtualizedWorktreeViewport = React.memo(function VirtualizedWorktreeViewp
setSidebarPointerDragDocumentStyles(false)
setDragOverStatus(null)
setPinDragOver(false)
}, [])
}, [cancelWorktreePointerAutoscroll])
const clearWorktreeDrag = useCallback(() => {
cleanupWorktreePointerDrag()
cancelWorktreeNativeAutoscroll()
worktreeDragSessionRef.current = null
setWorktreeDragState(WORKTREE_ROW_DRAG_INITIAL_STATE)
}, [cleanupWorktreePointerDrag])
}, [cancelWorktreeNativeAutoscroll, cleanupWorktreePointerDrag])
const flushWorktreePointerDrag = useCallback(() => {
const drag = worktreePointerDragRef.current
@@ -1407,6 +1423,10 @@ const VirtualizedWorktreeViewport = React.memo(function VirtualizedWorktreeViewp
offsetX: drag.previewOffsetX,
offsetY: drag.previewOffsetY
})
if (!refreshWorktreeDragSession()) {
clearWorktreeDrag()
return
}
const drop = computeWorktreeDrop(drag.currentY)
const sidebarContainer = scrollRef.current
if (!drop) {
@@ -1448,7 +1468,7 @@ const VirtualizedWorktreeViewport = React.memo(function VirtualizedWorktreeViewp
? prev
: { ...prev, ...drop, pointerY: drag.currentY }
)
}, [computeWorktreeDrop])
}, [clearWorktreeDrag, computeWorktreeDrop, refreshWorktreeDragSession])
const scheduleWorktreePointerDragFrame = useCallback(
(drag: WorktreePointerDrag) => {
@@ -1460,6 +1480,60 @@ const VirtualizedWorktreeViewport = React.memo(function VirtualizedWorktreeViewp
[flushWorktreePointerDrag]
)
const runWorktreePointerAutoscrollFrame = useCallback(
(frameTime: number) => {
worktreePointerAutoscrollFrameIdRef.current = null
const drag = worktreePointerDragRef.current
const container = scrollRef.current
const session = worktreeDragSessionRef.current
if (!drag?.active || !container || !session) {
cancelWorktreePointerAutoscroll()
return
}
const previousFrameTime = worktreePointerAutoscrollLastFrameTimeRef.current ?? frameTime
worktreePointerAutoscrollLastFrameTimeRef.current = frameTime
const autoscroll = getWorktreeSidebarDragAutoscroll({
point: { clientX: drag.currentX, clientY: drag.currentY },
containerRect: container.getBoundingClientRect(),
scrollTop: container.scrollTop,
scrollHeight: container.scrollHeight,
clientHeight: container.clientHeight,
elapsedMs: frameTime - previousFrameTime
})
if (autoscroll) {
markScrollMovement()
container.scrollTop = autoscroll.scrollTop
if (!refreshWorktreeDragSession()) {
clearWorktreeDrag()
return
}
scheduleWorktreePointerDragFrame(drag)
}
worktreePointerAutoscrollFrameIdRef.current = window.requestAnimationFrame(
runWorktreePointerAutoscrollFrame
)
},
[
cancelWorktreePointerAutoscroll,
clearWorktreeDrag,
markScrollMovement,
refreshWorktreeDragSession,
scheduleWorktreePointerDragFrame
]
)
const startWorktreePointerAutoscroll = useCallback(() => {
if (worktreePointerAutoscrollFrameIdRef.current !== null) {
return
}
worktreePointerAutoscrollLastFrameTimeRef.current = null
worktreePointerAutoscrollFrameIdRef.current = window.requestAnimationFrame(
runWorktreePointerAutoscrollFrame
)
}, [runWorktreePointerAutoscrollFrame])
const beginWorktreePointerDrag = useCallback(
(drag: WorktreePointerDrag) => {
const { preview, offsetX, offsetY } = createSidebarDragPreview({
@@ -1490,9 +1564,10 @@ const VirtualizedWorktreeViewport = React.memo(function VirtualizedWorktreeViewp
previewOffsetsByWorktreeId: EMPTY_WORKTREE_DRAG_PREVIEW_OFFSETS,
pointerY: drag.currentY
})
startWorktreePointerAutoscroll()
scheduleWorktreePointerDragFrame(drag)
},
[scheduleWorktreePointerDragFrame]
[scheduleWorktreePointerDragFrame, startWorktreePointerAutoscroll]
)
const handleWorktreeRowPointerDown = useCallback(
@@ -1509,7 +1584,7 @@ const VirtualizedWorktreeViewport = React.memo(function VirtualizedWorktreeViewp
if (!sourceGroupKey || !container) {
return
}
const rects = getWorktreeDragRectsForGroup(container, sourceGroupKey)
const rects = getWorktreeSidebarDragRectsForGroup(container, sourceGroupKey)
if (rects.length <= 1) {
return
}
@@ -1589,6 +1664,10 @@ const VirtualizedWorktreeViewport = React.memo(function VirtualizedWorktreeViewp
}
event.preventDefault()
event.stopPropagation()
if (!refreshWorktreeDragSession()) {
clearWorktreeDrag()
return
}
const drop = computeWorktreeDrop(event.clientY)
const container = scrollRef.current
if (drop) {
@@ -1640,11 +1719,92 @@ const VirtualizedWorktreeViewport = React.memo(function VirtualizedWorktreeViewp
onMoveWorktreesToStatus,
onPinWorktrees,
onReorderWorktrees,
refreshWorktreeDragSession,
scheduleWorktreePointerDragFrame,
worktreeDragGroups,
worktreeDragUnitGroups
])
const runWorktreeNativeAutoscrollFrame = useCallback(
(frameTime: number) => {
worktreeNativeAutoscrollFrameIdRef.current = null
const point = worktreeNativeLatestPointRef.current
const container = scrollRef.current
const session = worktreeDragSessionRef.current
if (!point || !container || !session) {
cancelWorktreeNativeAutoscroll()
return
}
const previousFrameTime = worktreeNativeAutoscrollLastFrameTimeRef.current ?? frameTime
worktreeNativeAutoscrollLastFrameTimeRef.current = frameTime
const autoscroll = getWorktreeSidebarDragAutoscroll({
point,
containerRect: container.getBoundingClientRect(),
scrollTop: container.scrollTop,
scrollHeight: container.scrollHeight,
clientHeight: container.clientHeight,
elapsedMs: frameTime - previousFrameTime
})
if (autoscroll) {
markScrollMovement()
container.scrollTop = autoscroll.scrollTop
if (!refreshWorktreeDragSession()) {
clearWorktreeDrag()
return
}
const drop = computeWorktreeDrop(point.clientY)
if (!drop) {
setWorktreeDragState((prev) =>
prev.dropIndex === null &&
prev.dropIndicatorY === null &&
prev.previewOffsetsByWorktreeId.size === 0
? prev
: {
...prev,
dropIndex: null,
dropIndicatorY: null,
previewOffsetsByWorktreeId: EMPTY_WORKTREE_DRAG_PREVIEW_OFFSETS,
pointerY: null
}
)
} else {
setWorktreeDragState((prev) =>
prev.dropIndex === drop.dropIndex &&
prev.dropIndicatorY === drop.dropIndicatorY &&
areWorktreeDragPreviewOffsetsEqual(
prev.previewOffsetsByWorktreeId,
drop.previewOffsetsByWorktreeId
)
? prev
: { ...prev, ...drop, pointerY: point.clientY }
)
}
}
worktreeNativeAutoscrollFrameIdRef.current = window.requestAnimationFrame(
runWorktreeNativeAutoscrollFrame
)
},
[
cancelWorktreeNativeAutoscroll,
clearWorktreeDrag,
computeWorktreeDrop,
markScrollMovement,
refreshWorktreeDragSession
]
)
const startWorktreeNativeAutoscroll = useCallback(() => {
if (worktreeNativeAutoscrollFrameIdRef.current !== null) {
return
}
worktreeNativeAutoscrollLastFrameTimeRef.current = null
worktreeNativeAutoscrollFrameIdRef.current = window.requestAnimationFrame(
runWorktreeNativeAutoscrollFrame
)
}, [runWorktreeNativeAutoscrollFrame])
const handleWorktreeCardDragStart = useCallback(
(
_event: React.DragEvent<HTMLDivElement>,
@@ -1664,7 +1824,7 @@ const VirtualizedWorktreeViewport = React.memo(function VirtualizedWorktreeViewp
reorderDraggedIds,
reorderUnitDraggedIds,
rects: scrollRef.current
? getWorktreeDragRectsForGroup(scrollRef.current, sourceGroupKey)
? getWorktreeSidebarDragRectsForGroup(scrollRef.current, sourceGroupKey)
: []
}
setWorktreeDragState({
@@ -1685,6 +1845,12 @@ const VirtualizedWorktreeViewport = React.memo(function VirtualizedWorktreeViewp
if (!session) {
return
}
worktreeNativeLatestPointRef.current = { clientX: event.clientX, clientY: event.clientY }
startWorktreeNativeAutoscroll()
if (!refreshWorktreeDragSession()) {
clearWorktreeDrag()
return
}
const drop = computeWorktreeDrop(event.clientY)
if (!drop) {
setWorktreeDragState((prev) =>
@@ -1715,7 +1881,12 @@ const VirtualizedWorktreeViewport = React.memo(function VirtualizedWorktreeViewp
: { ...prev, ...drop, pointerY: event.clientY }
)
},
[computeWorktreeDrop]
[
clearWorktreeDrag,
computeWorktreeDrop,
refreshWorktreeDragSession,
startWorktreeNativeAutoscroll
]
)
const handleWorktreeDrop = useCallback(
@@ -1724,6 +1895,10 @@ const VirtualizedWorktreeViewport = React.memo(function VirtualizedWorktreeViewp
if (!session) {
return
}
if (!refreshWorktreeDragSession()) {
clearWorktreeDrag()
return
}
const drop = computeWorktreeDrop(event.clientY)
if (!drop) {
clearWorktreeDrag()
@@ -1746,6 +1921,7 @@ const VirtualizedWorktreeViewport = React.memo(function VirtualizedWorktreeViewp
clearWorktreeDrag,
computeWorktreeDrop,
onReorderWorktrees,
refreshWorktreeDragSession,
worktreeDragGroups,
worktreeDragUnitGroups
]
@@ -1870,8 +2046,13 @@ const VirtualizedWorktreeViewport = React.memo(function VirtualizedWorktreeViewp
if (!session) {
return
}
if (!refreshWorktreeDragSession()) {
clearWorktreeDrag()
return
}
const drop = computeWorktreeDrop(event.clientY)
if (!drop) {
clearWorktreeDrag()
return
}
// Why: status-group drops are captured before React sees them. When the
@@ -1898,10 +2079,35 @@ const VirtualizedWorktreeViewport = React.memo(function VirtualizedWorktreeViewp
clearWorktreeDrag,
computeWorktreeDrop,
onReorderWorktrees,
refreshWorktreeDragSession,
worktreeDragGroups,
worktreeDragUnitGroups
])
useEffect(() => {
const handleDocumentDragEnd = (): void => {
if (worktreeDragSessionRef.current) {
clearWorktreeDrag()
}
}
document.addEventListener('dragend', handleDocumentDragEnd, true)
return () => document.removeEventListener('dragend', handleDocumentDragEnd, true)
}, [clearWorktreeDrag])
useEffect(() => {
const handleVisibilityChange = (): void => {
if (document.visibilityState !== 'visible' && worktreeDragSessionRef.current) {
clearWorktreeDrag()
}
}
document.addEventListener('visibilitychange', handleVisibilityChange)
return () => document.removeEventListener('visibilitychange', handleVisibilityChange)
}, [clearWorktreeDrag])
useEffect(() => () => clearWorktreeDrag(), [clearWorktreeDrag])
useWorkspaceStatusDocumentDrop(
scrollRef,
onMoveWorktreeToStatus,
@@ -2399,7 +2605,9 @@ const VirtualizedWorktreeViewport = React.memo(function VirtualizedWorktreeViewp
highlightedRevealWorktreeId === itemRow.worktree.id &&
'scroll-to-current-workspace-reveal-highlight',
worktreeDragState.draggingWorktreeId === itemRow.worktree.id &&
'z-20 scale-[0.985] opacity-35 saturate-75'
// Why: the fixed drag preview is the visible affordance; leaving the
// source row translucent lets it bleed through sticky headers/footers.
'pointer-events-none opacity-0'
)}
data-scroll-reveal-highlight={
highlightedRevealWorktreeId === itemRow.worktree.id ? 'true' : undefined
@@ -2600,6 +2808,7 @@ const VirtualizedWorktreeViewport = React.memo(function VirtualizedWorktreeViewp
role="presentation"
data-worktree-virtual-row
data-worktree-virtual-row-key={String(vItem.key)}
data-worktree-virtual-row-start={vItem.start}
data-index={vItem.index}
ref={measureVirtualRowElement}
className={cn(
@@ -2640,6 +2849,7 @@ const VirtualizedWorktreeViewport = React.memo(function VirtualizedWorktreeViewp
role="presentation"
data-worktree-virtual-row
data-worktree-virtual-row-key={String(vItem.key)}
data-worktree-virtual-row-start={vItem.start}
data-index={vItem.index}
ref={measureVirtualRowElement}
data-workspace-status-drop-target={itemWorkspaceStatus ? '' : undefined}
@@ -0,0 +1,255 @@
import { describe, expect, it } from 'vitest'
import {
getWorktreeSidebarDragAutoscroll,
getWorktreeSidebarBoundaryDrop,
getWorktreeSidebarDragRectsForGroup,
refreshWorktreeSidebarDragSession,
type WorktreeSidebarDragRect,
type WorktreeSidebarDragSession
} from './worktree-sidebar-drag-autoscroll'
const CONTAINER_RECT = {
left: 10,
right: 210,
top: 100,
bottom: 500
}
const SESSION: WorktreeSidebarDragSession = {
draggingWorktreeId: 'b',
sourceGroupKey: 'repo:one',
draggedIds: ['b'],
reorderDraggedIds: ['b'],
reorderUnitDraggedIds: ['b'],
rects: [{ worktreeId: 'b', groupIndex: 1, top: 48, bottom: 88 }]
}
describe('getWorktreeSidebarDragAutoscroll', () => {
it('scrolls up near the top edge', () => {
expect(getAutoscroll({ clientX: 80, clientY: 112 })?.scrollTop).toBeCloseTo(187.93, 2)
})
it('scrolls down near the bottom edge', () => {
expect(getAutoscroll({ clientX: 80, clientY: 488 })?.scrollTop).toBeCloseTo(212.07, 2)
})
it('does nothing away from the vertical edge zones', () => {
expect(getAutoscroll({ clientX: 80, clientY: 300 })).toBeNull()
})
it('does nothing when the pointer is outside horizontally', () => {
expect(getAutoscroll({ clientX: 4, clientY: 488 })).toBeNull()
})
it('does not write past scroll bounds', () => {
expect(getAutoscroll({ clientX: 80, clientY: 100 }, { scrollTop: 0 })).toBeNull()
expect(getAutoscroll({ clientX: 80, clientY: 500 }, { scrollTop: 600 })).toBeNull()
})
it('allows capped scrolling slightly beyond the vertical edge', () => {
expect(getAutoscroll({ clientX: 80, clientY: 530 })?.scrollTop).toBeCloseTo(215.36, 2)
expect(getAutoscroll({ clientX: 80, clientY: 560 })).toBeNull()
})
it('scales by elapsed frame time and clamps delayed frames', () => {
const normal = getAutoscroll({ clientX: 80, clientY: 500 })
const delayed = getAutoscroll({ clientX: 80, clientY: 500 }, { elapsedMs: 200 })
expect(normal?.scrollTop).toBeCloseTo(215.36, 2)
expect(delayed?.scrollTop).toBeCloseTo(230.72, 2)
})
})
describe('getWorktreeSidebarBoundaryDrop', () => {
it('clamps near the group start instead of clearing the edge preview', () => {
expect(
getWorktreeSidebarBoundaryDrop({
localY: 70,
firstRect: { worktreeId: 'a', groupIndex: 0, top: 100, bottom: 140 },
lastRect: { worktreeId: 'c', groupIndex: 2, top: 200, bottom: 240 },
sourceGroupSize: 3
})
).toEqual({ kind: 'drop', dropIndex: 0, indicatorY: 97 })
})
it('clamps near the group end instead of clearing the edge preview', () => {
expect(
getWorktreeSidebarBoundaryDrop({
localY: 270,
firstRect: { worktreeId: 'a', groupIndex: 0, top: 100, bottom: 140 },
lastRect: { worktreeId: 'c', groupIndex: 2, top: 200, bottom: 240 },
sourceGroupSize: 3
})
).toEqual({ kind: 'drop', dropIndex: 3, indicatorY: 243 })
})
it('still rejects gaps that are not the real group edge', () => {
for (const localY of [70, 270]) {
expect(
getWorktreeSidebarBoundaryDrop({
localY,
firstRect: { worktreeId: 'b', groupIndex: 1, top: 100, bottom: 140 },
lastRect: { worktreeId: 'c', groupIndex: 2, top: 200, bottom: 240 },
sourceGroupSize: 4
})
).toEqual({ kind: 'outside' })
}
})
it('keeps normal in-range hover handling unchanged', () => {
expect(
getWorktreeSidebarBoundaryDrop({
localY: 160,
firstRect: { worktreeId: 'a', groupIndex: 0, top: 100, bottom: 140 },
lastRect: { worktreeId: 'c', groupIndex: 2, top: 200, bottom: 240 },
sourceGroupSize: 3
})
).toEqual({ kind: 'inside' })
})
})
describe('getWorktreeSidebarDragRectsForGroup', () => {
it('refreshes mounted rects for the source group only', () => {
const container = makeContainer([
makeDragElement('a', 'repo:one', '0', 140, 180),
makeDragElement('x', 'repo:two', '0', 80, 120),
makeDragElement('b', 'repo:one', '1', 90, 130)
])
expect(getWorktreeSidebarDragRectsForGroup(container, 'repo:one')).toEqual([
{ worktreeId: 'b', groupIndex: 1, top: 40, bottom: 80 },
{ worktreeId: 'a', groupIndex: 0, top: 90, bottom: 130 }
])
})
it('anchors rects to virtual row slots so animated transforms do not perturb hit testing', () => {
const container = makeContainer([
makeDragElement('a', 'repo:one', '0', 320, 360, { start: 240, top: 310 }),
makeDragElement('b', 'repo:one', '1', 380, 420, { start: 298, top: 368 })
])
expect(getWorktreeSidebarDragRectsForGroup(container, 'repo:one')).toEqual([
{ worktreeId: 'a', groupIndex: 0, top: 250, bottom: 290 },
{ worktreeId: 'b', groupIndex: 1, top: 310, bottom: 350 }
])
})
})
describe('refreshWorktreeSidebarDragSession', () => {
it('keeps the dragged set stable while refreshing rects', () => {
const rects: WorktreeSidebarDragRect[] = [
{ worktreeId: 'a', groupIndex: 0, top: 0, bottom: 40 },
{ worktreeId: 'b', groupIndex: 1, top: 48, bottom: 88 }
]
expect(
refreshWorktreeSidebarDragSession({
session: SESSION,
groups: [{ key: 'repo:one', worktreeIds: ['a', 'b', 'child'] }],
unitGroups: [
{
key: 'repo:one',
worktreeIds: ['a', 'b'],
units: [
{ worktreeId: 'a', worktreeIds: ['a'] },
{ worktreeId: 'b', worktreeIds: ['b', 'child'] }
]
}
],
rects
})
).toEqual({ ...SESSION, rects })
})
it('clears when the source group is missing', () => {
expect(
refreshWorktreeSidebarDragSession({
session: SESSION,
groups: [{ key: 'repo:two', worktreeIds: ['b'] }],
unitGroups: [{ key: 'repo:one', worktreeIds: ['b'], units: [] }],
rects: []
})
).toBeNull()
})
it('clears when the dragged worktree or reordered unit disappears', () => {
expect(
refreshWorktreeSidebarDragSession({
session: SESSION,
groups: [{ key: 'repo:one', worktreeIds: ['a'] }],
unitGroups: [{ key: 'repo:one', worktreeIds: ['b'], units: [] }],
rects: []
})
).toBeNull()
expect(
refreshWorktreeSidebarDragSession({
session: SESSION,
groups: [{ key: 'repo:one', worktreeIds: ['a', 'b'] }],
unitGroups: [{ key: 'repo:one', worktreeIds: ['a'], units: [] }],
rects: []
})
).toBeNull()
})
it('keeps a valid session when mounted rects are temporarily empty', () => {
expect(
refreshWorktreeSidebarDragSession({
session: SESSION,
groups: [{ key: 'repo:one', worktreeIds: ['a', 'b'] }],
unitGroups: [{ key: 'repo:one', worktreeIds: ['a', 'b'], units: [] }],
rects: []
})
).toEqual({ ...SESSION, rects: [] })
})
})
function makeContainer(elements: readonly ReturnType<typeof makeDragElement>[]): HTMLElement {
return {
scrollTop: 50,
getBoundingClientRect: () => ({ top: 100 }),
querySelectorAll: () => elements
} as unknown as HTMLElement
}
function getAutoscroll(
point: { clientX: number; clientY: number },
overrides: Partial<Parameters<typeof getWorktreeSidebarDragAutoscroll>[0]> = {}
) {
return getWorktreeSidebarDragAutoscroll({
point,
containerRect: CONTAINER_RECT,
scrollTop: 200,
scrollHeight: 1000,
clientHeight: 400,
elapsedMs: 16,
...overrides
})
}
function makeDragElement(
worktreeId: string,
groupKey: string,
groupIndex: string,
top: number,
bottom: number,
virtualRow?: { start: number; top: number }
): HTMLElement {
const attributes = new Map([
['data-worktree-drag-id', worktreeId],
['data-worktree-drag-group-key', groupKey],
['data-worktree-drag-group-index', groupIndex]
])
const virtualRowElement = virtualRow
? ({
getAttribute: (name: string) =>
name === 'data-worktree-virtual-row-start' ? String(virtualRow.start) : null,
getBoundingClientRect: () => ({ top: virtualRow.top })
} as unknown as HTMLElement)
: null
return {
getAttribute: (name: string) => attributes.get(name) ?? null,
getBoundingClientRect: () => ({ top, bottom, height: bottom - top }),
closest: (selector: string) =>
selector === '[data-worktree-virtual-row]' ? virtualRowElement : null
} as unknown as HTMLElement
}
@@ -0,0 +1,214 @@
import type { WorktreeDragGroup } from './worktree-manual-order'
import type { WorktreeDragUnitGroup } from './worktree-drag-units'
const EDGE_ZONE_PX = 56
const MAX_OUTSIDE_EDGE_PX = 48
const MAX_SCROLL_SPEED_PX_PER_SECOND = 960
const MAX_FRAME_MS = 32
const DROP_BOUNDS_PADDING_PX = 8
export type WorktreeSidebarDragPoint = {
clientX: number
clientY: number
}
export type WorktreeSidebarDragRect = {
worktreeId: string
groupIndex: number
top: number
bottom: number
}
export type WorktreeSidebarDragSession = {
draggingWorktreeId: string
sourceGroupKey: string
draggedIds: readonly string[]
reorderDraggedIds: readonly string[]
reorderUnitDraggedIds: readonly string[]
rects: readonly WorktreeSidebarDragRect[]
}
export type WorktreeSidebarAutoscrollResult = {
scrollTop: number
}
export type WorktreeSidebarBoundaryDropResult =
| {
kind: 'drop'
dropIndex: number
indicatorY: number
}
| { kind: 'inside' }
| { kind: 'outside' }
export function getWorktreeSidebarDragAutoscroll(args: {
point: WorktreeSidebarDragPoint
containerRect: Pick<DOMRect, 'left' | 'right' | 'top' | 'bottom'>
scrollTop: number
scrollHeight: number
clientHeight: number
elapsedMs: number
}): WorktreeSidebarAutoscrollResult | null {
const { point, containerRect } = args
if (point.clientX < containerRect.left || point.clientX > containerRect.right) {
return null
}
const maxScrollTop = Math.max(0, args.scrollHeight - args.clientHeight)
if (maxScrollTop <= 0) {
return null
}
const scrollTop = Math.max(0, Math.min(maxScrollTop, args.scrollTop))
const elapsedMs = Math.max(0, Math.min(MAX_FRAME_MS, args.elapsedMs))
if (elapsedMs <= 0) {
return null
}
const edge = getVerticalEdgeIntensity(point.clientY, containerRect)
if (!edge) {
return null
}
const nextScrollTop = Math.max(
0,
Math.min(
maxScrollTop,
scrollTop +
edge.direction * edge.intensity * MAX_SCROLL_SPEED_PX_PER_SECOND * (elapsedMs / 1000)
)
)
return nextScrollTop === scrollTop ? null : { scrollTop: nextScrollTop }
}
export function getWorktreeSidebarBoundaryDrop(args: {
localY: number
firstRect: WorktreeSidebarDragRect
lastRect: WorktreeSidebarDragRect
sourceGroupSize: number
}): WorktreeSidebarBoundaryDropResult {
if (args.localY < args.firstRect.top - DROP_BOUNDS_PADDING_PX) {
if (args.firstRect.groupIndex === 0 && args.localY >= args.firstRect.top - EDGE_ZONE_PX) {
return {
kind: 'drop',
dropIndex: 0,
indicatorY: Math.max(0, args.firstRect.top - 3)
}
}
return { kind: 'outside' }
}
if (args.localY > args.lastRect.bottom + DROP_BOUNDS_PADDING_PX) {
const lastGroupIndex = args.sourceGroupSize - 1
if (
args.lastRect.groupIndex === lastGroupIndex &&
args.localY <= args.lastRect.bottom + EDGE_ZONE_PX
) {
return {
kind: 'drop',
dropIndex: args.sourceGroupSize,
indicatorY: args.lastRect.bottom + 3
}
}
return { kind: 'outside' }
}
return { kind: 'inside' }
}
export function getWorktreeSidebarDragRectsForGroup(
container: HTMLElement,
groupKey: string
): WorktreeSidebarDragRect[] {
const containerRect = container.getBoundingClientRect()
const rects: WorktreeSidebarDragRect[] = []
container.querySelectorAll<HTMLElement>('[data-worktree-drag-id]').forEach((element) => {
if (element.getAttribute('data-worktree-drag-group-key') !== groupKey) {
return
}
const worktreeId = element.getAttribute('data-worktree-drag-id')
const rawGroupIndex = element.getAttribute('data-worktree-drag-group-index')
const groupIndex = rawGroupIndex === null ? Number.NaN : Number(rawGroupIndex)
if (!worktreeId || !Number.isFinite(groupIndex)) {
return
}
const rect = element.getBoundingClientRect()
const virtualRow = element.closest<HTMLElement>('[data-worktree-virtual-row]')
const virtualRowStart = getWorktreeVirtualRowStart(virtualRow)
const top =
virtualRow && virtualRowStart !== null
? virtualRowStart + rect.top - virtualRow.getBoundingClientRect().top
: rect.top - containerRect.top + container.scrollTop
rects.push({
worktreeId,
groupIndex,
// Why: drop previews animate via row transforms. Anchor hit-testing to
// the virtual row's static slot so animated offsets cannot perturb it.
top,
bottom: top + rect.height
})
})
rects.sort((a, b) => a.top - b.top)
return rects
}
function getWorktreeVirtualRowStart(virtualRow: HTMLElement | null): number | null {
if (!virtualRow) {
return null
}
const rawStart = virtualRow.getAttribute('data-worktree-virtual-row-start')
if (rawStart === null) {
return null
}
const start = Number(rawStart)
return Number.isFinite(start) ? start : null
}
export function refreshWorktreeSidebarDragSession(args: {
session: WorktreeSidebarDragSession
groups: readonly WorktreeDragGroup[]
unitGroups: readonly WorktreeDragUnitGroup[]
rects: readonly WorktreeSidebarDragRect[]
}): WorktreeSidebarDragSession | null {
const sourceGroup = args.groups.find((group) => group.key === args.session.sourceGroupKey)
if (!sourceGroup || !sourceGroup.worktreeIds.includes(args.session.draggingWorktreeId)) {
return null
}
const sourceUnitGroup = args.unitGroups.find((group) => group.key === args.session.sourceGroupKey)
if (!sourceUnitGroup) {
return null
}
const sourceUnitIds = new Set(sourceUnitGroup.worktreeIds)
if (args.session.reorderUnitDraggedIds.some((worktreeId) => !sourceUnitIds.has(worktreeId))) {
return null
}
return { ...args.session, rects: args.rects }
}
function getVerticalEdgeIntensity(
clientY: number,
containerRect: Pick<DOMRect, 'top' | 'bottom'>
): { direction: -1 | 1; intensity: number } | null {
if (clientY < containerRect.top - MAX_OUTSIDE_EDGE_PX) {
return null
}
if (clientY > containerRect.bottom + MAX_OUTSIDE_EDGE_PX) {
return null
}
if (clientY <= containerRect.top + EDGE_ZONE_PX) {
return {
direction: -1,
intensity: Math.min(1, (containerRect.top + EDGE_ZONE_PX - clientY) / EDGE_ZONE_PX)
}
}
if (clientY >= containerRect.bottom - EDGE_ZONE_PX) {
return {
direction: 1,
intensity: Math.min(1, (clientY - (containerRect.bottom - EDGE_ZONE_PX)) / EDGE_ZONE_PX)
}
}
return null
}