: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(mobile): drag pinned views into place after a longer hold (#129693)
Chris Volzer6a4fc7a881e7
diff --git a/products/mobile/docs/VIEWS.md b/products/mobile/docs/VIEWS.mdindex 7dd9298b2af3..a933453e280c 100644--- a/products/mobile/docs/VIEWS.md+++ b/products/mobile/docs/VIEWS.md@@ -121,6 +121,7 @@ A pin whose tile is gone (its insight answers 404, or the cached dashboard no lo### Pin actions+- Hold a pin’s title for about 1.3 seconds to drag it directly in Views. The normal long-press menu appears first; keep holding for a second haptic cue, then drag to the highlighted tile and release to insert there. Holding near the top or bottom scrolls the list. This works with mixed tile heights and the two-column layout. Releasing without moving or cancelling leaves the order unchanged. Dragging is disabled while searching; Move up/down and Edit pins remain available, including for screen readers.- Long press any pin for its menu: Show as Row, Number or Chart, Choose tile (dashboards), Move up, Move down, Unpin.- Long press a Recent, Browse or search row for Pin to Views (or Unpin) and Open.- Every Recent, Browse and search row has a pin button. Tap it to pin or unpin the view; rows have no swipe action.diff --git a/products/mobile/src/features/views/list/PinDragOverlay.tsx b/products/mobile/src/features/views/list/PinDragOverlay.tsxnew file mode 100644index 000000000000..fcbe0f3c121b--- /dev/null+++ b/products/mobile/src/features/views/list/PinDragOverlay.tsx@@ -0,0 +1,92 @@+import { type ReactElement, type ReactNode, useCallback } from 'react'+import { Text, View } from 'react-native'+import Animated, { useAnimatedStyle } from 'react-native-reanimated'++import { GripIcon } from '@/ui/icons/GripIcon'+import { createStyles, useTheme } from '@/ui/theme'+import { radii, type } from '@/ui/tokens'+import { useSceneDimensions } from '@/ui/useSceneDimensions'+import type { PinDrag } from './usePinDrag'+import { ViewIcon } from './viewMeta'++export function PinDragTile({ id, drag, children }: { id: string; drag: PinDrag; children: ReactNode }): ReactElement {+ const { register, measureAll } = drag+ const ref = useCallback((node: View | null) => register(id, node), [id, register])+ return (+ <View+ ref={ref}+ collapsable={false}+ onLayout={measureAll}+ style={{ opacity: drag.dragged?.shortcutId === id ? 0.35 : 1 }}+ >+ {children}+ </View>+ )+}++/** A compact label follows the finger without mounting a second live chart or stealing its canvas budget. */+export function PinDragOverlay({ drag }: { drag: PinDrag }): ReactElement | null {+ const { colors, shadows } = useTheme()+ const styles = useStyles()+ const { width } = useSceneDimensions()+ const { x, y, targetX, targetY, targetWidth, targetHeight } = drag+ const preview = useAnimatedStyle(() => ({+ transform: [{ translateX: Math.max(8, Math.min(width - 268, x.value - 130)) }, { translateY: y.value - 78 }],+ }))+ const target = useAnimatedStyle(() => ({+ left: targetX.value,+ top: targetY.value,+ width: targetWidth.value,+ height: targetHeight.value,+ }))+ if (!drag.dragged) return null+ return (+ <View+ pointerEvents="none"+ style={styles.overlay}+ accessibilityElementsHidden+ importantForAccessibility="no-hide-descendants"+ testID="views-pin-drag"+ >+ <Animated.View style={[styles.target, target]} />+ <Animated.View style={[styles.preview, shadows.floatingSheet, preview]}>+ <ViewIcon kind={drag.dragged.kind} size={20} />+ <View style={styles.text}>+ <Text style={styles.title} numberOfLines={1}>+ {drag.dragged.name}+ </Text>+ <Text style={styles.hint}>Release to place here</Text>+ </View>+ <GripIcon size={20} color={colors.tertiary} />+ </Animated.View>+ </View>+ )+}++const useStyles = createStyles(({ colors }) => ({+ overlay: { position: 'absolute', top: 0, left: 0, right: 0, bottom: 0 },+ target: {+ position: 'absolute',+ borderWidth: 2,+ borderColor: colors.blue,+ borderRadius: radii.option,+ backgroundColor: colors.blueHighlight,+ },+ preview: {+ position: 'absolute',+ left: 0,+ top: 0,+ width: 260,+ padding: 12,+ flexDirection: 'row',+ alignItems: 'center',+ gap: 10,+ borderRadius: radii.option,+ backgroundColor: colors.surface,+ borderWidth: 1,+ borderColor: colors.blue,+ },+ text: { flex: 1, minWidth: 0 },+ title: { ...type.bodySmallStrong, color: colors.ink },+ hint: { ...type.meta, color: colors.secondary },+}))diff --git a/products/mobile/src/features/views/list/ViewsScreen.tsx b/products/mobile/src/features/views/list/ViewsScreen.tsxindex 98f9ce899d13..ab36136b8b82 100644--- a/products/mobile/src/features/views/list/ViewsScreen.tsx+++ b/products/mobile/src/features/views/list/ViewsScreen.tsx@@ -1,6 +1,7 @@import { useIsFocused, useRouter } from 'expo-router'import { type ReactElement, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react'import { Platform, RefreshControl, SectionList, Text, View, type ViewToken } from 'react-native'+import { GestureDetector } from 'react-native-gesture-handler'import type { RowAnchor } from '@/features/inbox/contextMenuPlacement'import { useMobileProductFlags } from '@/lib/featureFlags'import { useNow } from '@/lib/useNow'@@ -49,8 +50,10 @@ import { ChooseTileSheet, type ChooseTileTarget } from './ChooseTileSheet'import { EditPinsList } from './EditPinsList'import { EmptyPins } from './EmptyPins'import { PinCard } from './PinCard'+import { PinDragOverlay, PinDragTile } from './PinDragOverlay'import { PinHint } from './PinHint'import { PinScrollAnchor, pinAnchorOffset } from './PinScrollAnchor'+import { usePinDrag } from './usePinDrag'import { usePinFlows } from './usePinFlows'import { type GroupPosition, groupPosition, ViewRow } from './ViewRow'import { PinMenu, RowMenu } from './ViewsMenu'@@ -149,6 +152,7 @@ function ViewsBody(): ReactElement {const colors = useColors()const styles = useStyles()const router = useRouter()+ const focused = useIsFocused()const insets = useScreenInsets()const now = useNow()const context = useViewsContext()@@ -250,6 +254,22 @@ function ViewsBody(): ReactElement {explicit: list.displayPrefs,enabled: !editing && !search.active,})+ const drag = usePinDrag({+ pins,+ enabled: focused && !editing && !search.active && !text && !chooseTile,+ scope: `${context.identity}|${context.dataScope}`,+ width,+ top: contentTop,+ bottom: bottomOffset(insets, 120),+ metrics: scrollMetrics,+ scrollTo: (y) => listRef.current?.getScrollResponder()?.scrollTo({ y, animated: false }),+ onStart: () => {+ cancelAnchorRestore()+ setMenu(null)+ motion.onScroll()+ },+ onReorder: (ids) => actions.reorder(ids),+ })const hintTargetId = hint.target?.shortcutId ?? nullconst { dismiss: dismissHint } = hint@@ -274,6 +294,7 @@ function ViewsBody(): ReactElement {viewable.current.list(expanded)viewable.current.budget(expanded)scheduleAnchorRestore()+ drag.measureAll()}).current// Row callbacks read the latest values through a ref, so they stay stable and memoized cards skip re-rendering.@@ -674,15 +695,17 @@ function ViewsBody(): ReactElement {>{item.items.map((pin) => (<View key={pin.key} style={[{ flex: 1, minWidth: 0 }, !pin.last && styles.pinGap]}>- <PinCard- pin={pin.pin}- index={pin.index}- onOpen={openPin}- onMenu={openPinMenu}- onChooseTile={chooseTileFromCard}- onUnpin={unpinFromCard}- onPressTooltip={openPinPoint}- />+ <PinDragTile id={pin.shortcutId} drag={drag}>+ <PinCard+ pin={pin.pin}+ index={pin.index}+ onOpen={openPin}+ onMenu={openPinMenu}+ onChooseTile={chooseTileFromCard}+ onUnpin={unpinFromCard}+ onPressTooltip={openPinPoint}+ />+ </PinDragTile></View>))}</View>@@ -696,15 +719,17 @@ function ViewsBody(): ReactElement {ref={(node) => setPinRow([item.shortcutId], node)}onLayout={() => onPinLayout([item.shortcutId])}>- <PinCard- pin={item.pin}- index={item.index}- onOpen={openPin}- onMenu={openPinMenu}- onChooseTile={chooseTileFromCard}- onUnpin={unpinFromCard}- onPressTooltip={openPinPoint}- />+ <PinDragTile id={item.shortcutId} drag={drag}>+ <PinCard+ pin={item.pin}+ index={item.index}+ onOpen={openPin}+ onMenu={openPinMenu}+ onChooseTile={chooseTileFromCard}+ onUnpin={unpinFromCard}+ onPressTooltip={openPinPoint}+ />+ </PinDragTile></View>)case 'pin-hint':@@ -746,6 +771,7 @@ function ViewsBody(): ReactElement {}},[+ drag,setPinRow,onPinLayout,openPin,@@ -859,73 +885,80 @@ function ViewsBody(): ReactElement {)} else {body = (- <SectionList- ref={listRef}- sections={displaySections}- keyExtractor={keyOf}- renderItem={renderItem}- onScrollToIndexFailed={({ averageItemLength, index }) => {- if (!pinAnchor.current.restoration.target) return- pinAnchor.current.restoration.fail()- listRef.current?.getScrollResponder()?.scrollTo({ y: averageItemLength * index, animated: false })- }}- onContentSizeChange={(_width, height) => {- scrollMetrics.current.contentHeight = height- scheduleAnchorRestore()- }}- onLayout={(event) => {- scrollMetrics.current.viewportHeight = event.nativeEvent.layout.height- scheduleAnchorRestore()- }}- onScrollBeginDrag={cancelAnchorRestore}- renderSectionHeader={renderSectionHeader}- stickySectionHeadersEnabled={false}- ListHeaderComponent={- <View style={styles.search}>- <SearchField- value={text}- onChangeText={setText}- placeholder="Search views"- testID="views-search"+ <GestureDetector gesture={drag.gesture}>+ <SectionList+ ref={listRef}+ scrollEnabled={!drag.dragged}+ sections={displaySections}+ keyExtractor={keyOf}+ renderItem={renderItem}+ onScrollToIndexFailed={({ averageItemLength, index }) => {+ if (!pinAnchor.current.restoration.target) return+ pinAnchor.current.restoration.fail()+ listRef.current+ ?.getScrollResponder()+ ?.scrollTo({ y: averageItemLength * index, animated: false })+ }}+ onContentSizeChange={(_width, height) => {+ scrollMetrics.current.contentHeight = height+ scheduleAnchorRestore()+ }}+ onLayout={(event) => {+ scrollMetrics.current.viewportHeight = event.nativeEvent.layout.height+ scheduleAnchorRestore()+ }}+ onScrollBeginDrag={cancelAnchorRestore}+ renderSectionHeader={renderSectionHeader}+ stickySectionHeadersEnabled={false}+ ListHeaderComponent={+ <View style={styles.search}>+ <SearchField+ value={text}+ onChangeText={setText}+ placeholder="Search views"+ testID="views-search"+ />+ </View>+ }+ keyboardShouldPersistTaps="handled"+ keyboardDismissMode="on-drag"+ onViewableItemsChanged={onViewableItemsChanged}+ viewabilityConfig={list.viewabilityConfig}+ onScroll={(event) => {+ const { contentOffset, contentSize, layoutMeasurement } = event.nativeEvent+ scrollMetrics.current = {+ offset: contentOffset.y,+ contentHeight: contentSize.height,+ viewportHeight: layoutMeasurement.height,+ }+ motion.onScroll()+ scheduleAnchorRestore()+ }}+ scrollEventThrottle={16}+ initialNumToRender={INITIAL_VISIBLE_ROWS}+ windowSize={5}+ removeClippedSubviews={Platform.OS === 'android' && !drag.dragged}+ contentContainerStyle={[styles.content, { paddingTop: contentTop, paddingBottom: contentBottom }]}+ refreshControl={+ <RefreshControl+ enabled={!drag.dragged}+ refreshing={refresh.pulling}+ onRefresh={refresh.onPull}+ tintColor={colors.tertiary}+ progressBackgroundColor={colors.surface}+ colors={[colors.tertiary]}+ progressViewOffset={contentTop}/>- </View>- }- keyboardShouldPersistTaps="handled"- keyboardDismissMode="on-drag"- onViewableItemsChanged={onViewableItemsChanged}- viewabilityConfig={list.viewabilityConfig}- onScroll={(event) => {- const { contentOffset, contentSize, layoutMeasurement } = event.nativeEvent- scrollMetrics.current = {- offset: contentOffset.y,- contentHeight: contentSize.height,- viewportHeight: layoutMeasurement.height,}- motion.onScroll()- scheduleAnchorRestore()- }}- scrollEventThrottle={16}- initialNumToRender={INITIAL_VISIBLE_ROWS}- windowSize={5}- removeClippedSubviews={Platform.OS === 'android'}- contentContainerStyle={[styles.content, { paddingTop: contentTop, paddingBottom: contentBottom }]}- refreshControl={- <RefreshControl- refreshing={refresh.pulling}- onRefresh={refresh.onPull}- tintColor={colors.tertiary}- progressBackgroundColor={colors.surface}- colors={[colors.tertiary]}- progressViewOffset={contentTop}- />- }- />+ />+ </GestureDetector>)}return (- <View style={styles.fill}>+ <View ref={drag.root} collapsable={false} onLayout={drag.measureAll} style={styles.fill}>{body}+ <PinDragOverlay drag={drag} />{menu?.kind === 'pin' && menuPin ? (<PinMenuForpin={menuPin}diff --git a/products/mobile/src/features/views/list/pinDrag.test.ts b/products/mobile/src/features/views/list/pinDrag.test.tsnew file mode 100644index 000000000000..19672276f284--- /dev/null+++ b/products/mobile/src/features/views/list/pinDrag.test.ts@@ -0,0 +1,43 @@+import { dragScrollStep, dropPin, nearestPin, type PinFrame } from './pinDrag'++const ids = ['chart', 'number', 'row', 'dashboard']++test.each([+ ['chart', 'dashboard', ['number', 'row', 'dashboard', 'chart']],+ ['dashboard', 'number', ['chart', 'dashboard', 'number', 'row']],+ ['number', 'number', ids],+ ['removed', 'row', ids],+ ['chart', 'removed', ids],+])('drops %s at %s without losing or swapping other pins', (source, target, expected) => {+ expect(dropPin(ids, source, target)).toEqual(expected)+ expect(ids).toEqual(['chart', 'number', 'row', 'dashboard'])+})++const frames: PinFrame[] = [+ { id: 'chart', x: 16, y: 100, width: 300, height: 280 },+ { id: 'number', x: 332, y: 100, width: 300, height: 160 },+ { id: 'row', x: 16, y: 396, width: 616, height: 64 },+]++test.each([+ [200, 300, 'chart'],+ [450, 180, 'number'],+ [450, 300, 'number'],+ [450, 430, 'row'],+ [200, 50, 'chart'],+ [200, 600, 'row'],+])('finds a destination at (%s, %s) across unequal tiles and columns', (x, y, id) => {+ expect(nearestPin(frames, x, y)?.id).toBe(id)+})++test('has no drop target before any tiles are measured', () => {+ expect(nearestPin([], 20, 20)).toBeNull()+})++test('edge scrolling is bounded and stops in the middle of the viewport', () => {+ expect(dragScrollStep(100, 100, 700)).toBe(-8)+ expect(dragScrollStep(132, 100, 700)).toBe(-4)+ expect(dragScrollStep(400, 100, 700)).toBe(0)+ expect(dragScrollStep(668, 100, 700)).toBe(4)+ expect(dragScrollStep(800, 100, 700)).toBe(8)+})diff --git a/products/mobile/src/features/views/list/pinDrag.ts b/products/mobile/src/features/views/list/pinDrag.tsnew file mode 100644index 000000000000..7208427950b1--- /dev/null+++ b/products/mobile/src/features/views/list/pinDrag.ts@@ -0,0 +1,38 @@+import type { RowAnchor } from '@/features/inbox/contextMenuPlacement'++export interface PinFrame extends RowAnchor {+ id: string+}++/** Insert at the target's position; preserve the relative order of every other pin. */+export function dropPin(ids: readonly string[], source: string, target: string): string[] {+ const from = ids.indexOf(source)+ const to = ids.indexOf(target)+ if (from < 0 || to < 0 || from === to) return [...ids]+ const next = ids.filter((id) => id !== source)+ next.splice(to, 0, source)+ return next+}++/** Rectangle distance handles mixed-height cards and the two-column layout without assuming row sizes. */+export function nearestPin(frames: readonly PinFrame[], x: number, y: number): PinFrame | null {+ let closest: PinFrame | null = null+ let distance = Number.POSITIVE_INFINITY+ for (const frame of frames) {+ const dx = Math.max(frame.x - x, 0, x - frame.x - frame.width)+ const dy = Math.max(frame.y - y, 0, y - frame.y - frame.height)+ const next = dx * dx + dy * dy+ if (next < distance) {+ closest = frame+ distance = next+ }+ }+ return closest+}++export function dragScrollStep(y: number, top: number, bottom: number): number {+ const edge = 64+ if (y < top + edge) return -8 * Math.min(1, Math.max(0, (top + edge - y) / edge))+ if (y > bottom - edge) return 8 * Math.min(1, Math.max(0, (y - bottom + edge) / edge))+ return 0+}diff --git a/products/mobile/src/features/views/list/usePinDrag.test.tsx b/products/mobile/src/features/views/list/usePinDrag.test.tsxnew file mode 100644index 000000000000..c65fa2018b75--- /dev/null+++ b/products/mobile/src/features/views/list/usePinDrag.test.tsx@@ -0,0 +1,170 @@+import 'react-native-gesture-handler/jestSetup'+import { act, fireEvent, render, renderHook } from '@testing-library/react-native'+import { Text, type View } from 'react-native'+import { PointerType, State } from 'react-native-gesture-handler'++import type { PinView } from '@/model/views'+import { PinDragTile } from './PinDragOverlay'+import { type PinDrag, usePinDrag } from './usePinDrag'++jest.mock('react-native-reanimated', () => ({+ useSharedValue: (value: number) => {+ const { useRef } = jest.requireActual<typeof import('react')>('react')+ return useRef({ value }).current+ },+}))+jest.mock('react-native-worklets', () => ({ scheduleOnUI: (worklet: () => void) => worklet() }))+jest.mock('@/lib/haptics', () => ({ haptic: jest.fn() }))++const chartId = 'a'+const pins: PinView[] = [chartId, 'b', 'c'].map((id) => ({+ shortcutId: id,+ shortcutIds: [id],+ kind: 'insight',+ ref: id,+ name: id,+ href: `/insights/${id}`,+ rank: null,+ serverOrder: 0,+ display: { mode: 'row' },+}))++type StartEvent = Parameters<NonNullable<PinDrag['gesture']['handlers']['onStart']>>[0]+function event(y: number): StartEvent {+ return {+ handlerTag: 1,+ state: State.ACTIVE,+ oldState: State.BEGAN,+ numberOfPointers: 1,+ pointerType: PointerType.TOUCH,+ x: 50,+ y,+ absoluteX: 50,+ absoluteY: y,+ translationX: 0,+ translationY: 0,+ velocityX: 0,+ velocityY: 0,+ }+}++function pickup(drag: PinDrag, y = 120): void {+ const touch = { id: 1, x: 50, y, absoluteX: 50, absoluteY: y }+ drag.gesture.handlers.onTouchesDown?.(+ {+ handlerTag: 1,+ state: State.BEGAN,+ numberOfTouches: 1,+ pointerType: PointerType.TOUCH,+ eventType: 1,+ allTouches: [touch],+ changedTouches: [touch],+ },+ { handlerTag: 1, begin: jest.fn(), activate: jest.fn(), end: jest.fn(), fail: jest.fn() }+ )+ // Native recognition supplies ACTIVE only after the extra-long hold; simulator coverage checks that timing.+ drag.gesture.handlers.onStart?.(event(y))+}++function setup(tileTop = (index: number): number => 100 + index * 100) {+ const reorder = jest.fn()+ const metrics = { current: { offset: 0, contentHeight: 1000, viewportHeight: 500 } }+ const scrollTo = jest.fn((offset: number) => {+ metrics.current.offset = offset+ })+ const options = {+ pins,+ enabled: true,+ scope: 'project-one',+ width: 400,+ top: 80,+ bottom: 80,+ metrics,+ scrollTo,+ onStart: jest.fn(),+ onReorder: reorder,+ }+ const hook = renderHook((props: Parameters<typeof usePinDrag>[0]) => usePinDrag(props), { initialProps: options })+ act(() => {+ pins.forEach((pin, index) => {+ hook.result.current.register(pin.shortcutId, {+ measureInWindow: (callback: (x: number, y: number, width: number, height: number) => void) =>+ callback(20, tileTop(index), 360, 80),+ } as unknown as View)+ })+ })+ return { ...hook, options, reorder, scrollTo }+}++beforeEach(() => jest.useFakeTimers())+afterEach(() => jest.useRealTimers())++test('saves only on drop and preserves the pins between source and destination', () => {+ const { result, reorder } = setup()+ act(() => pickup(result.current))+ act(() => result.current.gesture.handlers.onUpdate?.(event(320)))+ expect(result.current.dragged?.shortcutId).toBe('a')+ expect(reorder).not.toHaveBeenCalled()+ act(() => result.current.gesture.handlers.onFinalize?.(event(320), true))+ expect(reorder).toHaveBeenCalledWith(['b', 'c', 'a'])+ expect(result.current.dragged).toBeNull()+})++test('picks up the tile below a chart after the chart grows', () => {+ let extraHeight = 0+ const { result } = setup((index) => 100 + index * 100 + (index > 0 ? extraHeight : 0))+ const chart = render(+ <PinDragTile id={chartId} drag={result.current}>+ <Text>Chart</Text>+ </PinDragTile>+ )+ extraHeight = 100+ fireEvent(chart.getByText('Chart'), 'layout')+ act(() => jest.advanceTimersByTime(32))+ act(() => pickup(result.current, 320))+ expect(result.current.dragged?.shortcutId).toBe('b')+})++test.each(['cancel', 'stationary', 'refresh', 'scope', 'disabled'] as const)(+ '%s does not save a stale or unchanged order',+ (reason) => {+ const { result, rerender, options, reorder } = setup()+ act(() => pickup(result.current))+ if (reason !== 'stationary') act(() => result.current.gesture.handlers.onUpdate?.(event(320)))+ if (reason === 'refresh') rerender({ ...options, pins: pins.slice(1) })+ if (reason === 'scope') rerender({ ...options, scope: 'project-two' })+ if (reason === 'disabled') rerender({ ...options, enabled: false })+ act(() => result.current.gesture.handlers.onFinalize?.(event(320), reason !== 'cancel'))+ expect(reorder).not.toHaveBeenCalled()+ expect(result.current.dragged).toBeNull()+ }+)++test('edge scrolling stops at the last pin and after cancellation', () => {+ const { result, scrollTo } = setup()+ act(() =>+ result.current.register('c', {+ measureInWindow: (callback: (x: number, y: number, width: number, height: number) => void) =>+ callback(20, 900, 360, 80),+ } as unknown as View)+ )+ act(() => pickup(result.current))+ act(() => jest.advanceTimersByTime(64))+ expect(scrollTo).not.toHaveBeenCalled()+ act(() => result.current.gesture.handlers.onUpdate?.(event(420)))+ act(() => jest.advanceTimersByTime(64))+ expect(scrollTo).toHaveBeenCalled()+ act(() =>+ result.current.register('c', {+ measureInWindow: (callback: (x: number, y: number, width: number, height: number) => void) =>+ callback(20, 340, 360, 80),+ } as unknown as View)+ )+ scrollTo.mockClear()+ act(() => jest.advanceTimersByTime(64))+ expect(scrollTo).not.toHaveBeenCalled()+ act(() => result.current.gesture.handlers.onFinalize?.(event(420), false))+ scrollTo.mockClear()+ act(() => jest.advanceTimersByTime(64))+ expect(scrollTo).not.toHaveBeenCalled()+})diff --git a/products/mobile/src/features/views/list/usePinDrag.ts b/products/mobile/src/features/views/list/usePinDrag.tsnew file mode 100644index 000000000000..9f7ef7065423--- /dev/null+++ b/products/mobile/src/features/views/list/usePinDrag.ts@@ -0,0 +1,245 @@+import { type RefObject, useCallback, useEffect, useMemo, useRef, useState } from 'react'+import { AppState, type View } from 'react-native'+import { Gesture, type PanGesture } from 'react-native-gesture-handler'+import { type SharedValue, useSharedValue } from 'react-native-reanimated'+import { scheduleOnUI } from 'react-native-worklets'++import { haptic } from '@/lib/haptics'+import type { PinView } from '@/model/views'+import { dragScrollStep, dropPin, nearestPin, type PinFrame } from './pinDrag'++const HOLD_MS = 1300+const HEAD_HEIGHT = 64++interface Options {+ pins: readonly PinView[]+ enabled: boolean+ scope: string+ width: number+ top: number+ bottom: number+ metrics: { current: { offset: number; contentHeight: number; viewportHeight: number } }+ scrollTo: (y: number) => void+ onStart: () => void+ onReorder: (ids: string[]) => void+}++interface Drag {+ pin: PinView+ ids: string[]+ target: string+ startX: number+ startY: number+ moved: boolean+ x: number+ y: number+}++/** The recognizer belongs to the list, so recycling the source tile cannot end an edge-scrolling drag. */+export interface PinDrag {+ gesture: PanGesture+ root: RefObject<View | null>+ dragged: PinView | null+ register: (id: string, node: View | null) => void+ measureAll: () => void+ x: SharedValue<number>+ y: SharedValue<number>+ targetX: SharedValue<number>+ targetY: SharedValue<number>+ targetWidth: SharedValue<number>+ targetHeight: SharedValue<number>+}++export function usePinDrag(options: Options): PinDrag {+ const latest = useRef(options)+ latest.current = options+ const nodes = useRef(new Map<string, View>())+ const frames = useRef(new Map<string, PinFrame & { offset: number }>())+ const root = useRef<View>(null)+ const origin = useRef({ x: 0, y: 0 })+ const candidate = useRef<string | null>(null)+ const active = useRef<Drag | null>(null)+ const [dragged, setDragged] = useState<PinView | null>(null)+ const x = useSharedValue(0)+ const y = useSharedValue(0)+ const targetX = useSharedValue(0)+ const targetY = useSharedValue(0)+ const targetWidth = useSharedValue(0)+ const targetHeight = useSharedValue(0)++ const measure = useCallback((id: string): void => {+ const node = nodes.current.get(id)+ const offset = latest.current.metrics.current.offset+ node?.measureInWindow((x, y, width, height) => {+ if (nodes.current.get(id) === node && width > 0 && height > 0) {+ frames.current.set(id, { id, x, y, width, height, offset })+ }+ })+ }, [])+ const register = useCallback(+ (id: string, node: View | null): void => {+ if (node) {+ nodes.current.set(id, node)+ measure(id)+ } else {+ nodes.current.delete(id)+ frames.current.delete(id)+ }+ },+ [measure]+ )+ const layoutFrame = useRef<number | null>(null)+ const measureAll = useCallback((): void => {+ if (layoutFrame.current !== null) return+ layoutFrame.current = requestAnimationFrame(() => {+ layoutFrame.current = null+ root.current?.measureInWindow((x, y) => {+ origin.current = { x, y }+ })+ for (const id of nodes.current.keys()) measure(id)+ })+ }, [measure])+ useEffect(+ () => () => {+ if (layoutFrame.current !== null) cancelAnimationFrame(layoutFrame.current)+ layoutFrame.current = null+ },+ []+ )+ const visibleFrames = useCallback((): PinFrame[] => {+ const { offset } = latest.current.metrics.current+ const ids = new Set(latest.current.pins.map((pin) => pin.shortcutId))+ return [...frames.current.values()]+ .filter((frame) => ids.has(frame.id))+ .map((frame) => ({ ...frame, y: frame.y + frame.offset - offset }))+ }, [])+ const update = useCallback(+ (absoluteX: number, absoluteY: number): void => {+ const drag = active.current+ if (!drag) return+ drag.moved ||= Math.hypot(absoluteX - drag.startX, absoluteY - drag.startY) > 8+ drag.x = absoluteX+ drag.y = absoluteY+ x.value = absoluteX - origin.current.x+ y.value = absoluteY - origin.current.y+ const frames = visibleFrames()+ const frame = drag.moved+ ? nearestPin(frames, absoluteX, absoluteY)+ : frames.find((frame) => frame.id === drag.pin.shortcutId)+ if (!frame) return+ if (drag.target !== frame.id) haptic('selection')+ drag.target = frame.id+ targetX.value = frame.x - origin.current.x+ targetY.value = frame.y - origin.current.y+ targetWidth.value = frame.width+ targetHeight.value = frame.height+ },+ [visibleFrames, x, y, targetX, targetY, targetWidth, targetHeight]+ )+ const finish = useCallback((save: boolean): void => {+ const drag = active.current+ active.current = null+ candidate.current = null+ setDragged(null)+ if (!save || !drag?.moved) return+ const ids = latest.current.pins.map((pin) => pin.shortcutId)+ // A refresh, project switch, or another ordering action must never be overwritten by an old gesture.+ if (ids.length !== drag.ids.length || ids.some((id, index) => id !== drag.ids[index])) return+ const next = dropPin(ids, drag.pin.shortcutId, drag.target)+ if (next.some((id, index) => id !== ids[index])) latest.current.onReorder(next)+ }, [])+ const gesture = useMemo(+ () =>+ Gesture.Pan()+ .enabled(options.enabled && options.pins.length > 1)+ .activateAfterLongPress(HOLD_MS)+ .maxPointers(1)+ .runOnJS(true)+ .onTouchesDown((event, manager) => {+ const touch = event.allTouches[0]+ if (!touch || event.numberOfTouches !== 1) {+ candidate.current = null+ scheduleOnUI(manager.fail)+ return+ }+ const frame = visibleFrames().find(+ (frame) =>+ touch.absoluteX >= frame.x &&+ touch.absoluteX <= frame.x + frame.width &&+ touch.absoluteY >= frame.y &&+ touch.absoluteY <= frame.y + Math.min(HEAD_HEIGHT, frame.height)+ )+ candidate.current = frame?.id ?? null+ if (!frame) scheduleOnUI(manager.fail)+ })+ .onStart((event) => {+ const pin = latest.current.pins.find((pin) => pin.shortcutId === candidate.current)+ if (!pin || !latest.current.enabled) return+ active.current = {+ pin,+ ids: latest.current.pins.map((pin) => pin.shortcutId),+ target: pin.shortcutId,+ startX: event.absoluteX,+ startY: event.absoluteY,+ moved: false,+ x: event.absoluteX,+ y: event.absoluteY,+ }+ latest.current.onStart()+ setDragged(pin)+ haptic('light')+ update(event.absoluteX, event.absoluteY)+ })+ .onUpdate((event) => update(event.absoluteX, event.absoluteY))+ .onFinalize((_event, success) => finish(success)),+ [options.enabled, options.pins.length, visibleFrames, update, finish]+ )++ useEffect(() => {+ if (!dragged) return+ const timer = setInterval(() => {+ const drag = active.current+ if (!drag?.moved) return+ const { metrics, top, bottom, scrollTo } = latest.current+ const delta = dragScrollStep(+ drag.y,+ origin.current.y + top,+ origin.current.y + metrics.current.viewportHeight - bottom+ )+ const bottomLimit = origin.current.y + metrics.current.viewportHeight - bottom+ const lastId = latest.current.pins.at(-1)?.shortcutId+ const last = visibleFrames().find((frame) => frame.id === lastId)+ const maxOffset = Math.min(+ metrics.current.contentHeight - metrics.current.viewportHeight,+ last ? metrics.current.offset + last.y + last.height - bottomLimit : Number.POSITIVE_INFINITY+ )+ // Stop at the final pin, rather than carrying a held tile into Recent and Browse.+ const next =+ delta > 0+ ? Math.max(metrics.current.offset, Math.min(maxOffset, metrics.current.offset + delta))+ : Math.max(0, metrics.current.offset + delta)+ if (delta !== 0 && next !== metrics.current.offset) scrollTo(next)+ update(drag.x, drag.y)+ }, 16)+ return () => clearInterval(timer)+ }, [dragged, update, visibleFrames])+ // Cancel on navigation, search, rotation, project changes, backgrounding, and unmount.+ useEffect(() => {+ void options.scope+ void options.width+ void options.enabled+ finish(false)+ return () => {+ active.current = null+ candidate.current = null+ }+ }, [options.scope, options.width, options.enabled, finish])+ useEffect(() => {+ const subscription = AppState.addEventListener('change', (state) => {+ if (state !== 'active') finish(false)+ })+ return () => subscription.remove()+ }, [finish])++ return { gesture, root, dragged, register, measureAll, x, y, targetX, targetY, targetWidth, targetHeight }+}diff --git a/products/mobile/src/features/views/pinHooks.test.ts b/products/mobile/src/features/views/pinHooks.test.tsindex 145751dcc9d1..4010599b30e0 100644--- a/products/mobile/src/features/views/pinHooks.test.ts+++ b/products/mobile/src/features/views/pinHooks.test.ts@@ -1,3 +1,4 @@+import AsyncStorage from '@react-native-async-storage/async-storage'import { QueryClient, QueryClientProvider } from '@tanstack/react-query'import { act, renderHook, waitFor } from '@testing-library/react-native'import { createElement, type ReactNode } from 'react'@@ -9,6 +10,7 @@ import { setSessionTokens } from '@/auth/tokens'import { OfflineError, useConnectivity } from '@/lib/connectivity'import { pinView, unpinView, usePinActions } from './pinHooks'+import { usePinPrefs } from './pinPrefsStore'import { useViewsContext } from './useViewsContext'jest.mock('@react-native-async-storage/async-storage', () =>@@ -196,3 +198,35 @@ describe('pin writes', () => {expect(client.getQueryData(listKey)).toBeUndefined()})})++test('drag reorder saves per-project phone preferences without writing server shortcuts', async () => {+ const client = new QueryClient({ defaultOptions: { queries: { gcTime: Infinity } } })+ const scope = { host: 'https://example.com', projectId: 7 }+ jest.mocked(useViewsContext).mockReturnValue({+ mode: 'live',+ offline: false,+ identity: 'example-session',+ scope,+ dataScope: `${scope.host}|${scope.projectId}`,+ ready: false,+ access: { state: 'ok', missingScope: null },+ item: { client, scope, demo: false },+ })+ usePinPrefs.getState().setOrder('https://example.com|8', ['other-pin'])+ jest.mocked(createShortcut).mockClear()+ jest.mocked(deleteShortcut).mockClear()+ const { result, unmount } = renderHook(() => usePinActions(), {+ wrapper: ({ children }: { children: ReactNode }) => createElement(QueryClientProvider, { client }, children),+ })+ act(() => result.current.reorder(['third', 'first', 'second']))+ await waitFor(async () => {+ const saved = JSON.parse((await AsyncStorage.getItem('views-pin-prefs:v2')) ?? '{}')+ expect(saved.state.projects['https://example.com|7'].rank).toEqual({ third: 0, first: 1, second: 2 })+ expect(saved.state.projects['https://example.com|8'].rank).toEqual({ 'other-pin': 0 })+ })+ expect(createShortcut).not.toHaveBeenCalled()+ expect(deleteShortcut).not.toHaveBeenCalled()+ unmount()+ client.clear()+ usePinPrefs.getState().clear()+})