Extract swipe gesture logic and improve push notification handling (#135)

This commit is contained in:
Chris Scott authored and GitHub committed 2026-02-14 23:19:37 -05:00
1 parent 24609ef6c3
commit 687ad405ae
13 files changed
+259 -78

No files matched your search

+13 -1
View File
@@ -1,6 +1,7 @@
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { createBrowserRouter, RouterProvider, Outlet } from 'react-router-dom'
import { createBrowserRouter, RouterProvider, Outlet, useNavigate } from 'react-router-dom'
import { useEffect } from 'react'
import { Toaster } from 'sonner'
import { Repos } from './pages/Repos'
import { RepoDetail } from './pages/RepoDetail'
@@ -61,8 +62,19 @@ function PermissionDialogWrapper() {
}
function AppShell() {
const navigate = useNavigate()
useTheme()
useEffect(() => {
const channel = new BroadcastChannel('notification-click')
channel.onmessage = (event: MessageEvent) => {
if (event.data?.url) {
navigate(event.data.url)
}
}
return () => channel.close()
}, [navigate])
return (
<AuthProvider>
<EventProvider>
+13 -50
View File
@@ -1,10 +1,11 @@
import { useState, useRef } from "react";
import { useRef, useEffect } from "react";
import { Card } from "@/components/ui/card";
import { Checkbox } from "@/components/ui/checkbox";
import { MiniScanner } from "@/components/ui/mini-scanner";
import { Trash2, Clock } from "lucide-react";
import { formatDistanceToNow } from "date-fns";
import type { Session } from "@/api/types";
import { useSwipe } from "@/hooks/useSwipe";
interface SessionCardProps {
session: Session;
@@ -25,57 +26,26 @@ export const SessionCard = ({
onToggleSelection,
onDelete,
}: SessionCardProps) => {
const [swipeOffset, setSwipeOffset] = useState(0);
const [isSwipeOpen, setIsSwipeOpen] = useState(false);
const touchStartX = useRef<number | null>(null);
const cardRef = useRef<HTMLDivElement>(null);
const { bind, swipeOffset, isOpen, isSwipingBack, close, swipeStyles } = useSwipe();
const handleTouchStart = (e: React.TouchEvent) => {
touchStartX.current = e.touches[0].clientX;
};
const handleTouchMove = (e: React.TouchEvent) => {
if (touchStartX.current === null) return;
const currentX = e.touches[0].clientX;
const diff = touchStartX.current - currentX;
if (diff > 0) {
const newOffset = Math.min(diff, 80);
setSwipeOffset(newOffset);
} else if (diff < 0 && isSwipeOpen) {
const newOffset = Math.max(0, 80 + diff);
setSwipeOffset(newOffset);
useEffect(() => {
if (cardRef.current) {
return bind(cardRef.current);
}
};
const handleTouchEnd = () => {
if (swipeOffset > 50) {
setIsSwipeOpen(true);
setSwipeOffset(80);
} else if (swipeOffset < 30) {
setIsSwipeOpen(false);
setSwipeOffset(0);
}
touchStartX.current = null;
};
const closeSwipe = () => {
setSwipeOffset(0);
setIsSwipeOpen(false);
};
}, [bind]);
const handleDeleteClick = (e: React.MouseEvent<HTMLButtonElement>) => {
e.stopPropagation();
onDelete(e);
closeSwipe();
close();
};
return (
<div className="relative" onClick={closeSwipe}>
<div className="relative" onClick={close}>
<div
className={`absolute top-0.5 right-0 bottom-0.5 w-20 bg-red-600 flex items-center justify-center rounded-r-lg transition-opacity ${
swipeOffset > 20 || isSwipeOpen ? "opacity-100" : "opacity-0"
!isSwipingBack && (isOpen || swipeOffset > 40) ? "opacity-100" : "opacity-0"
}`}
>
<button
@@ -85,17 +55,10 @@ export const SessionCard = ({
<Trash2 className="w-5 h-5" />
</button>
</div>
<div
ref={cardRef}
onTouchStart={handleTouchStart}
onTouchMove={handleTouchMove}
onTouchEnd={handleTouchEnd}
style={{ transform: `translateX(-${swipeOffset}px)` }}
className="transition-transform"
>
<div ref={cardRef} style={swipeStyles}>
<Card
className={`p-2 cursor-pointer transition-all overflow-hidden ${
isSwipeOpen
isOpen
? "rounded-none"
: "rounded-r-lg"
} ${
@@ -106,7 +69,7 @@ export const SessionCard = ({
: "bg-card border-border hover:bg-accent hover:border-border"
} hover:shadow-lg`}
onClick={() => {
if (!isSwipeOpen) {
if (!isOpen) {
onSelect(session.id);
}
}}
@@ -167,8 +167,8 @@ export const SessionList = ({
/>
</div>
<div className="flex-1 overflow-y-auto px-4 pt-4 pb-4 min-h-0 [mask-image:linear-gradient(to_bottom,transparent,black_16px,black)]">
<div className="flex flex-col gap-2">
<div className="flex-1 overflow-y-auto overflow-x-hidden px-4 pt-4 pb-4 min-h-0 [mask-image:linear-gradient(to_bottom,transparent,black_16px,black)]">
<div className="flex flex-col gap-4">
{filteredSessions.length === 0 ? (
<div className="text-sm text-muted-foreground text-center py-4">
No sessions found
+10 -2
View File
@@ -43,6 +43,8 @@ export const useSSE = (opcodeUrl: string | null | undefined, directory?: string,
const client = useOpenCodeClient(opcodeUrl, directory)
const queryClient = useQueryClient()
const mountedRef = useRef(true)
const sessionIdRef = useRef(currentSessionId)
sessionIdRef.current = currentSessionId
const [isConnected, setIsConnected] = useState(false)
const [error, setError] = useState<string | null>(null)
const [isReconnecting, setIsReconnecting] = useState(false)
@@ -363,7 +365,7 @@ export const useSSE = (opcodeUrl: string | null | undefined, directory?: string,
if (connected) {
setError(null)
fetchInitialData()
sseManager.reportVisibility(document.visibilityState === 'visible')
sseManager.reportVisibility(document.visibilityState === 'visible', sessionIdRef.current)
} else {
setError('Connection lost. Reconnecting...')
}
@@ -378,7 +380,7 @@ export const useSSE = (opcodeUrl: string | null | undefined, directory?: string,
}
const handleVisibilityChange = () => {
sseManager.reportVisibility(document.visibilityState === 'visible')
sseManager.reportVisibility(document.visibilityState === 'visible', sessionIdRef.current)
}
document.addEventListener('visibilitychange', handleVisibilityChange)
@@ -395,5 +397,11 @@ export const useSSE = (opcodeUrl: string | null | undefined, directory?: string,
}
}, [opcodeUrl, directory, handleSSEEvent, fetchInitialData])
useEffect(() => {
if (isConnected && document.visibilityState === 'visible') {
sseManager.reportVisibility(true, currentSessionId)
}
}, [currentSessionId, isConnected])
return { isConnected, error, isReconnecting }
}
+179
View File
@@ -0,0 +1,179 @@
import { useState, useRef, useCallback } from 'react'
interface SwipeOptions {
threshold?: number
directionRatio?: number
enabled?: boolean
onSwipeStart?: () => void
onSwipeEnd?: () => void
}
interface SwipeState {
startX: number
startY: number
currentX: number
isSwiping: boolean
directionLocked: 'horizontal' | 'vertical' | null
}
export function useSwipe(options: SwipeOptions = {}) {
const {
threshold = 80,
directionRatio = 1.5,
enabled = true,
onSwipeStart,
onSwipeEnd,
} = options
const swipeRef = useRef<SwipeState>({
startX: 0,
startY: 0,
currentX: 0,
isSwiping: false,
directionLocked: null,
})
const [swipeOffset, setSwipeOffset] = useState(0)
const [isOpen, setIsOpen] = useState(false)
const isSwipingBackRef = useRef(false)
const isAnimatingRef = useRef(false)
const handleTouchStart = useCallback((e: TouchEvent) => {
if (!enabled) return
const touch = e.touches[0]
swipeRef.current = {
startX: touch.clientX,
startY: touch.clientY,
currentX: touch.clientX,
isSwiping: false,
directionLocked: null,
}
isAnimatingRef.current = false
}, [enabled])
const handleTouchMove = useCallback((e: TouchEvent) => {
if (!enabled) return
const state = swipeRef.current
const touch = e.touches[0]
const deltaX = state.startX - touch.clientX
const deltaY = touch.clientY - state.startY
const absDeltaX = Math.abs(deltaX)
const absDeltaY = Math.abs(deltaY)
if (!state.directionLocked && absDeltaX > 10 || absDeltaY > 10) {
if (absDeltaX > absDeltaY * directionRatio) {
state.directionLocked = 'horizontal'
} else {
state.directionLocked = 'vertical'
}
}
if (state.directionLocked === 'vertical') {
return
}
if (state.directionLocked === 'horizontal') {
if (!state.isSwiping) {
state.isSwiping = true
onSwipeStart?.()
}
e.preventDefault()
let newOffset: number
if (deltaX > 0) {
isSwipingBackRef.current = false
newOffset = Math.min(deltaX, threshold)
} else if (deltaX < 0 && isOpen) {
isSwipingBackRef.current = true
newOffset = Math.max(0, threshold + deltaX)
} else {
isSwipingBackRef.current = false
newOffset = 0
}
state.currentX = touch.clientX
setSwipeOffset(newOffset)
}
}, [enabled, threshold, directionRatio, isOpen, onSwipeStart])
const handleTouchEnd = useCallback(() => {
if (!enabled) return
isAnimatingRef.current = true
onSwipeEnd?.()
const state = swipeRef.current
if (swipeOffset > threshold / 2) {
setIsOpen(true)
setSwipeOffset(threshold)
} else {
setIsOpen(false)
setSwipeOffset(0)
}
state.startX = 0
state.startY = 0
state.currentX = 0
state.isSwiping = false
state.directionLocked = null
}, [enabled, threshold, swipeOffset, onSwipeEnd])
const handleTouchCancel = useCallback(() => {
if (!enabled) return
isAnimatingRef.current = true
setIsOpen(false)
setSwipeOffset(0)
swipeRef.current = {
startX: 0,
startY: 0,
currentX: 0,
isSwiping: false,
directionLocked: null,
}
}, [enabled])
const bind = useCallback((element: HTMLElement | null) => {
if (!element || !enabled) return
element.addEventListener('touchstart', handleTouchStart, { passive: true })
element.addEventListener('touchmove', handleTouchMove, { passive: false })
element.addEventListener('touchend', handleTouchEnd, { passive: true })
element.addEventListener('touchcancel', handleTouchCancel, { passive: true })
return () => {
element.removeEventListener('touchstart', handleTouchStart)
element.removeEventListener('touchmove', handleTouchMove)
element.removeEventListener('touchend', handleTouchEnd)
element.removeEventListener('touchcancel', handleTouchCancel)
}
}, [enabled, handleTouchStart, handleTouchMove, handleTouchEnd, handleTouchCancel])
const close = useCallback(() => {
isAnimatingRef.current = true
setIsOpen(false)
setSwipeOffset(0)
}, [])
const swipeStyles = {
transform: swipeOffset > 0 ? `translateX(-${swipeOffset}px)` : undefined,
transition: isAnimatingRef.current ? 'transform 0.2s ease-out' : undefined,
touchAction: 'pan-y',
}
const isSwipingBack = isSwipingBackRef.current
return {
bind,
swipeOffset,
isOpen,
isSwipingBack,
close,
swipeStyles,
}
}
+2 -2
View File
@@ -266,12 +266,12 @@ class SSEManager {
return this.isConnected
}
reportVisibility(visible: boolean): void {
reportVisibility(visible: boolean, activeSessionId?: string): void {
if (!this.clientId || !this.isConnected) return
fetch('/api/sse/visibility', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ clientId: this.clientId, visible })
body: JSON.stringify({ clientId: this.clientId, visible, activeSessionId: activeSessionId ?? null })
}).catch(() => {})
}
+6 -3
View File
@@ -25,6 +25,8 @@ interface PushNotificationData {
eventType: string;
sessionId?: string;
directory?: string;
repoId?: number;
repoName?: string;
};
}
@@ -65,9 +67,10 @@ self.addEventListener("notificationclick", (event) => {
.then((clientList) => {
for (const client of clientList) {
if (new URL(client.url).origin === self.location.origin) {
(client as WindowClient).focus();
(client as WindowClient).navigate(url);
return;
const channel = new BroadcastChannel("notification-click");
channel.postMessage({ url });
channel.close();
return (client as WindowClient).focus();
}
}
return self.clients.openWindow(url);