Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

refactor(dashboards): share drag auto-scroll between dashboard grids (#122812)

Paul D'Ambracd26680c8453
diff --git a/frontend/src/scenes/dashboard/DashboardItems.tsx b/frontend/src/scenes/dashboard/DashboardItems.tsx
index 3209d32ec244..dc563dc9a6ad 100644
--- a/frontend/src/scenes/dashboard/DashboardItems.tsx
+++ b/frontend/src/scenes/dashboard/DashboardItems.tsx
@@ -30,6 +30,7 @@ import {
whenPressBecomesDrag,
} from 'scenes/dashboard/editLayoutGesture'
import { useDashboardLayoutInteraction } from 'scenes/dashboard/useDashboardLayoutInteraction'
+import { useDragAutoScroll } from 'scenes/dashboard/useDragAutoScroll'
import { useSurveyLinkedInsights } from 'scenes/surveys/hooks/useSurveyLinkedInsights'
import { getBestSurveyOpportunityFunnel } from 'scenes/surveys/utils/opportunityDetection'
import { urls } from 'scenes/urls'
@@ -49,9 +50,6 @@ import { useDashboardContainerWidth } from 'products/dashboards/frontend/useDash
import { DashboardButtonTileItem } from './items/DashboardButtonTileItem'
import { DashboardErrorTileItem } from './items/DashboardErrorTileItem'
-const DRAG_AUTO_SCROLL_THRESHOLD = 100
-const DRAG_AUTO_SCROLL_SPEED = 50
-
const BASE_ROW_HEIGHT = 80
const BASE_MARGIN: [number, number] = [16, 16]
const CONTAINER_PADDING: [number, number] = [0, 0]
@@ -153,21 +151,14 @@ export function DashboardItems({ showCreateAnomalyAlertButton }: DashboardItemsP
// `layouts` prop, so pushing layout updates to the store mid-gesture only triggers expensive full re-renders
// (every InsightCard) that make the dragged tile lag the cursor. Stash the latest layout and commit once on stop.
const dragEndTimeout = useRef<number | null>(null)
- const scrollAnimationRef = useRef<number | null>(null)
- const scrollContainerRef = useRef<HTMLElement | null>(null)
- const scrollContainerRectRef = useRef<DOMRect | null>(null)
+ const { startAutoScroll, autoScrollOnDrag, stopAutoScroll } = useDragAutoScroll()
const lastScrollSignalRef = useRef(scrollToBottomSignal)
useEffect(() => {
return () => {
- if (scrollAnimationRef.current) {
- cancelAnimationFrame(scrollAnimationRef.current)
- }
if (dragEndTimeout.current) {
window.clearTimeout(dragEndTimeout.current)
}
- scrollContainerRef.current = null
- scrollContainerRectRef.current = null
}
}, [])
@@ -484,63 +475,24 @@ export function DashboardItems({ showCreateAnomalyAlertButton }: DashboardItemsP
return
}
startInteraction(layout, newItem, 'drag')
- scrollContainerRef.current = document.getElementById('main-content')
- scrollContainerRectRef.current = scrollContainerRef.current?.getBoundingClientRect() ?? null
+ startAutoScroll()
},
- [startInteraction]
+ [startInteraction, startAutoScroll]
)
const handleDrag = useCallback(
- (_layout: unknown, _oldItem: unknown, _newItem: unknown, _placeholder: unknown, e: unknown) => {
+ (_layout: unknown, _oldItem: unknown, _newItem: unknown, _placeholder: unknown, e: Event) => {
isDragging.current = true
if (dragEndTimeout.current) {
window.clearTimeout(dragEndTimeout.current)
}
- if (scrollAnimationRef.current) {
- cancelAnimationFrame(scrollAnimationRef.current)
- scrollAnimationRef.current = null
- }
-
- const scrollContainer = scrollContainerRef.current
- const containerRect = scrollContainerRectRef.current
- if (!scrollContainer || !containerRect) {
- return
- }
-
- const mouseY = (e as MouseEvent).clientY
-
- let scrollSpeed = 0
- if (mouseY < containerRect.top + DRAG_AUTO_SCROLL_THRESHOLD) {
- scrollSpeed = -DRAG_AUTO_SCROLL_SPEED
- } else if (mouseY > containerRect.bottom - DRAG_AUTO_SCROLL_THRESHOLD) {
- scrollSpeed = DRAG_AUTO_SCROLL_SPEED
- }
-
- if (scrollSpeed !== 0) {
- const scroll = (): void => {
- const atTop = scrollSpeed < 0 && scrollContainer.scrollTop === 0
- const atBottom =
- scrollSpeed > 0 &&
- scrollContainer.scrollTop + scrollContainer.clientHeight >= scrollContainer.scrollHeight
- if (atTop || atBottom) {
- return
- }
- scrollContainer.scrollBy(0, scrollSpeed)
- scrollAnimationRef.current = requestAnimationFrame(scroll)
- }
- scrollAnimationRef.current = requestAnimationFrame(scroll)
- }
+ autoScrollOnDrag(e)
},
- []
+ [autoScrollOnDrag]
)
const handleDragStop = useCallback(() => {
- if (scrollAnimationRef.current) {
- cancelAnimationFrame(scrollAnimationRef.current)
- scrollAnimationRef.current = null
- }
- scrollContainerRef.current = null
- scrollContainerRectRef.current = null
+ stopAutoScroll()
if (dragEndTimeout.current) {
window.clearTimeout(dragEndTimeout.current)
}
@@ -551,7 +503,7 @@ export function DashboardItems({ showCreateAnomalyAlertButton }: DashboardItemsP
if (dashboard?.id) {
reportDashboardTileRepositioned(dashboard.id, 'moved', effectiveZoom)
}
- }, [dashboard?.id, reportDashboardTileRepositioned, effectiveZoom, flushPendingLayouts])
+ }, [dashboard?.id, reportDashboardTileRepositioned, effectiveZoom, flushPendingLayouts, stopAutoScroll])
const renderTile = (tile: DashboardTile): JSX.Element | undefined => {
const { insight, text, button_tile, widget } = tile
diff --git a/frontend/src/scenes/dashboard/useDragAutoScroll.test.ts b/frontend/src/scenes/dashboard/useDragAutoScroll.test.ts
new file mode 100644
index 000000000000..e07cfeb6e752
--- /dev/null
+++ b/frontend/src/scenes/dashboard/useDragAutoScroll.test.ts
@@ -0,0 +1,64 @@
+import { renderHook } from '@testing-library/react'
+
+import { useDragAutoScroll } from './useDragAutoScroll'
+
+describe('useDragAutoScroll', () => {
+ let frames: FrameRequestCallback[]
+ let container: HTMLDivElement
+
+ beforeEach(() => {
+ frames = []
+ jest.spyOn(window, 'requestAnimationFrame').mockImplementation((callback: FrameRequestCallback) => {
+ frames.push(callback)
+ return frames.length
+ })
+ jest.spyOn(window, 'cancelAnimationFrame').mockImplementation(() => {})
+ container = document.createElement('div')
+ container.id = 'main-content'
+ jest.spyOn(container, 'getBoundingClientRect').mockReturnValue({ top: 0, bottom: 1000 } as DOMRect)
+ Object.defineProperty(container, 'clientHeight', { value: 1000 })
+ Object.defineProperty(container, 'scrollHeight', { value: 3000 })
+ Object.defineProperty(container, 'scrollTop', { value: 0, writable: true })
+ container.scrollBy = jest.fn((_x: number, y: number) => {
+ container.scrollTop += y
+ }) as unknown as typeof container.scrollBy
+ document.body.appendChild(container)
+ })
+
+ afterEach(() => {
+ container.remove()
+ jest.restoreAllMocks()
+ })
+
+ const runFrames = (count: number): void => {
+ for (let i = 0; i < count && frames.length > 0; i++) {
+ frames.shift()!(0)
+ }
+ }
+
+ it.each([
+ { name: 'scrolls down near the bottom edge until the end', clientY: 950, scrollTop: 1900, expected: 2000 },
+ { name: 'scrolls up near the top edge until the start', clientY: 50, scrollTop: 100, expected: 0 },
+ { name: 'does not scroll away from the edges', clientY: 500, scrollTop: 1000, expected: 1000 },
+ ])('$name', ({ clientY, scrollTop, expected }) => {
+ container.scrollTop = scrollTop
+ const { result } = renderHook(() => useDragAutoScroll())
+
+ result.current.startAutoScroll()
+ result.current.autoScrollOnDrag(new MouseEvent('mousemove', { clientY }))
+ runFrames(10)
+
+ expect(container.scrollTop).toBe(expected)
+ expect(frames).toHaveLength(0)
+ })
+
+ it('does nothing when the scroll container is missing', () => {
+ container.remove()
+ const { result } = renderHook(() => useDragAutoScroll())
+
+ result.current.startAutoScroll()
+ result.current.autoScrollOnDrag(new MouseEvent('mousemove', { clientY: 950 }))
+
+ expect(frames).toHaveLength(0)
+ })
+})
diff --git a/frontend/src/scenes/dashboard/useDragAutoScroll.ts b/frontend/src/scenes/dashboard/useDragAutoScroll.ts
new file mode 100644
index 000000000000..55b41fe5913b
--- /dev/null
+++ b/frontend/src/scenes/dashboard/useDragAutoScroll.ts
@@ -0,0 +1,76 @@
+import { useCallback, useEffect, useRef } from 'react'
+
+const DRAG_AUTO_SCROLL_THRESHOLD = 100
+const DRAG_AUTO_SCROLL_SPEED = 50
+
+export interface DragAutoScroll {
+ startAutoScroll: () => void
+ autoScrollOnDrag: (event: Event) => void
+ stopAutoScroll: () => void
+}
+
+/** Scrolls `#main-content` while a dragged tile is near its top or bottom edge. */
+export function useDragAutoScroll(): DragAutoScroll {
+ const scrollContainerRef = useRef<HTMLElement | null>(null)
+ const scrollContainerRectRef = useRef<DOMRect | null>(null)
+ const scrollAnimationRef = useRef<number | null>(null)
+
+ const cancelScroll = useCallback((): void => {
+ if (scrollAnimationRef.current) {
+ cancelAnimationFrame(scrollAnimationRef.current)
+ scrollAnimationRef.current = null
+ }
+ }, [])
+
+ const stopAutoScroll = useCallback((): void => {
+ cancelScroll()
+ scrollContainerRef.current = null
+ scrollContainerRectRef.current = null
+ }, [cancelScroll])
+
+ useEffect(() => stopAutoScroll, [stopAutoScroll])
+
+ const startAutoScroll = useCallback((): void => {
+ scrollContainerRef.current = document.getElementById('main-content')
+ scrollContainerRectRef.current = scrollContainerRef.current?.getBoundingClientRect() ?? null
+ }, [])
+
+ const autoScrollOnDrag = useCallback(
+ (event: Event): void => {
+ cancelScroll()
+
+ const scrollContainer = scrollContainerRef.current
+ const containerRect = scrollContainerRectRef.current
+ if (!scrollContainer || !containerRect) {
+ return
+ }
+
+ const mouseY = (event as MouseEvent).clientY
+
+ let scrollSpeed = 0
+ if (mouseY < containerRect.top + DRAG_AUTO_SCROLL_THRESHOLD) {
+ scrollSpeed = -DRAG_AUTO_SCROLL_SPEED
+ } else if (mouseY > containerRect.bottom - DRAG_AUTO_SCROLL_THRESHOLD) {
+ scrollSpeed = DRAG_AUTO_SCROLL_SPEED
+ }
+
+ if (scrollSpeed !== 0) {
+ const scroll = (): void => {
+ const atTop = scrollSpeed < 0 && scrollContainer.scrollTop === 0
+ const atBottom =
+ scrollSpeed > 0 &&
+ scrollContainer.scrollTop + scrollContainer.clientHeight >= scrollContainer.scrollHeight
+ if (atTop || atBottom) {
+ return
+ }
+ scrollContainer.scrollBy(0, scrollSpeed)
+ scrollAnimationRef.current = requestAnimationFrame(scroll)
+ }
+ scrollAnimationRef.current = requestAnimationFrame(scroll)
+ }
+ },
+ [cancelScroll]
+ )
+
+ return { startAutoScroll, autoScrollOnDrag, stopAutoScroll }
+}
diff --git a/products/cross_project_dashboards/frontend/CrossProjectDashboardGrid.tsx b/products/cross_project_dashboards/frontend/CrossProjectDashboardGrid.tsx
index b067c30041a5..87dcc24cc903 100644
--- a/products/cross_project_dashboards/frontend/CrossProjectDashboardGrid.tsx
+++ b/products/cross_project_dashboards/frontend/CrossProjectDashboardGrid.tsx
@@ -1,4 +1,4 @@
-import { type RefObject, useCallback, useEffect, useMemo, useRef, useState } from 'react'
+import { type RefObject, useCallback, useEffect, useMemo, useState } from 'react'
import { Responsive as ReactGridLayout, useContainerWidth } from 'react-grid-layout'
import type { Layout, LayoutItem } from 'react-grid-layout'
import { GridBackground } from 'react-grid-layout/extras'
@@ -13,6 +13,7 @@ import {
whenPressBecomesDrag,
} from 'scenes/dashboard/editLayoutGesture'
import { useDashboardLayoutInteraction } from 'scenes/dashboard/useDashboardLayoutInteraction'
+import { useDragAutoScroll } from 'scenes/dashboard/useDragAutoScroll'
import type { DashboardLayoutSize, InsightColor } from '~/types'
@@ -27,8 +28,6 @@ import {
import { CrossProjectTile } from './CrossProjectTile'
import type { CrossProjectDashboardTileApi } from './generated/api.schemas'
-const DRAG_AUTO_SCROLL_THRESHOLD = 100
-const DRAG_AUTO_SCROLL_SPEED = 50
const CONTAINER_PADDING: [number, number] = [0, 0]
// Single-project edit mode's handle, cancel and edge set.
@@ -69,9 +68,7 @@ export function CrossProjectDashboardGrid({
}: CrossProjectDashboardGridProps): JSX.Element {
const { width, containerRef, mounted } = useContainerWidth()
const [containerHeight, setContainerHeight] = useState(0)
- const scrollContainerRef = useRef<HTMLElement | null>(null)
- const scrollContainerRectRef = useRef<DOMRect | null>(null)
- const scrollAnimationRef = useRef<number | null>(null)
+ const { startAutoScroll, autoScrollOnDrag, stopAutoScroll } = useDragAutoScroll()
const updateLayouts = useCallback(
(next: Partial<Record<DashboardLayoutSize, Layout>>) => onLayoutsChange(next as Partial<ResponsiveTileLayouts>),
@@ -180,57 +177,21 @@ export function CrossProjectDashboardGrid({
return
}
startInteraction(layout, newItem, 'drag')
- scrollContainerRef.current = document.getElementById('main-content')
- scrollContainerRectRef.current = scrollContainerRef.current?.getBoundingClientRect() ?? null
+ startAutoScroll()
},
- [startInteraction]
+ [startInteraction, startAutoScroll]
)
const handleDrag = useCallback(
- (_layout: unknown, _oldItem: unknown, _newItem: unknown, _placeholder: unknown, e: unknown) => {
- if (scrollAnimationRef.current) {
- cancelAnimationFrame(scrollAnimationRef.current)
- scrollAnimationRef.current = null
- }
- const scrollContainer = scrollContainerRef.current
- const containerRect = scrollContainerRectRef.current
- if (!scrollContainer || !containerRect) {
- return
- }
- const mouseY = (e as MouseEvent).clientY
- let scrollSpeed = 0
- if (mouseY < containerRect.top + DRAG_AUTO_SCROLL_THRESHOLD) {
- scrollSpeed = -DRAG_AUTO_SCROLL_SPEED
- } else if (mouseY > containerRect.bottom - DRAG_AUTO_SCROLL_THRESHOLD) {
- scrollSpeed = DRAG_AUTO_SCROLL_SPEED
- }
- if (scrollSpeed !== 0) {
- const scroll = (): void => {
- const atTop = scrollSpeed < 0 && scrollContainer.scrollTop === 0
- const atBottom =
- scrollSpeed > 0 &&
- scrollContainer.scrollTop + scrollContainer.clientHeight >= scrollContainer.scrollHeight
- if (atTop || atBottom) {
- return
- }
- scrollContainer.scrollBy(0, scrollSpeed)
- scrollAnimationRef.current = requestAnimationFrame(scroll)
- }
- scrollAnimationRef.current = requestAnimationFrame(scroll)
- }
- },
- []
+ (_layout: unknown, _oldItem: unknown, _newItem: unknown, _placeholder: unknown, e: Event) =>
+ autoScrollOnDrag(e),
+ [autoScrollOnDrag]
)
const handleDragStop = useCallback(() => {
- if (scrollAnimationRef.current) {
- cancelAnimationFrame(scrollAnimationRef.current)
- scrollAnimationRef.current = null
- }
- scrollContainerRef.current = null
- scrollContainerRectRef.current = null
+ stopAutoScroll()
finishGesture()
- }, [finishGesture])
+ }, [finishGesture, stopAutoScroll])
return (
<div