fix(slider): add pointer capture, touch-action none, link isolation, and zero-reflow RAF tracking for ultra-smooth mobile responsiveness

This commit is contained in:
2026-11-05 13:03:19 +05:30
parent f579b263b4
commit 3d147dd3de
5 changed files with 375 additions and 159 deletions
+72 -63
View File
@@ -21,7 +21,9 @@ export function CardBeforeAfterSlider({
const isHoveredRef = useRef(false);
const isDraggingRef = useRef(false);
const isInteractedRef = useRef(false);
const cachedRectRef = useRef<{ left: number; width: number } | null>(null);
const animIdRef = useRef<number>(0);
const rafIdRef = useRef<number | null>(null);
const [isHoveredState, setIsHoveredState] = useState(false);
const setSplit = useCallback((percent: number) => {
@@ -32,28 +34,15 @@ export function CardBeforeAfterSlider({
}
}, []);
const updateSplitFromClientX = useCallback(
(clientX: number) => {
if (!containerRef.current) return;
const rect = containerRef.current.getBoundingClientRect();
const x = Math.max(0, Math.min(clientX - rect.left, rect.width));
const percent = (x / rect.width) * 100;
setSplit(percent);
},
[setSplit]
);
// Smooth, gentle before/after slide sweep: RUNS ONLY ON HOVER OVER THIS SPECIFIC CARD!
// Smooth gentle oscillation: runs on desktop when hovered before user manually drags
useEffect(() => {
let startTime: number | null = null;
const animate = (time: number) => {
// ONLY animate when actively hovered and not manually dragging
if (isHoveredRef.current && !isDraggingRef.current && !isInteractedRef.current) {
if (startTime === null) startTime = time;
const elapsed = time - startTime;
// Calm, luxurious 3.6-second oscillation between 28% and 72%
const currentSplit = 50 + 22 * Math.sin((elapsed / 3600) * 2 * Math.PI);
const currentSplit = 50 + 22 * Math.sin((elapsed / 3200) * 2 * Math.PI);
setSplit(currentSplit);
animIdRef.current = requestAnimationFrame(animate);
}
@@ -78,62 +67,79 @@ export function CardBeforeAfterSlider({
const handleMouseLeave = useCallback(() => {
isHoveredRef.current = false;
isDraggingRef.current = false;
setIsHoveredState(false);
// Smoothly return to clean 50% rest state
if (!isInteractedRef.current) {
if (!isDraggingRef.current && !isInteractedRef.current) {
setSplit(50);
}
}, [setSplit]);
// Click & Drag handlers: manual inspection when user clicks or drags
const handleMouseDown = useCallback(
(e: React.MouseEvent<HTMLDivElement>) => {
e.preventDefault();
// Unified Pointer Handlers (Flawless on iOS/Android touchscreens and desktop mouse)
const handlePointerDown = useCallback(
(e: React.PointerEvent<HTMLDivElement>) => {
if (e.button !== 0 && e.pointerType === 'mouse') return;
isDraggingRef.current = true;
isInteractedRef.current = true;
cancelAnimationFrame(animIdRef.current);
updateSplitFromClientX(e.clientX);
const handleGlobalMouseMove = (moveEvent: MouseEvent) => {
if (!isDraggingRef.current) return;
updateSplitFromClientX(moveEvent.clientX);
};
try {
e.currentTarget.setPointerCapture(e.pointerId);
} catch {
// Fallback
}
const handleGlobalMouseUp = () => {
isDraggingRef.current = false;
window.removeEventListener('mousemove', handleGlobalMouseMove);
window.removeEventListener('mouseup', handleGlobalMouseUp);
};
// Cache rect on pointer down to eliminate layout thrashing
const rect = e.currentTarget.getBoundingClientRect();
cachedRectRef.current = { left: rect.left, width: rect.width };
window.addEventListener('mousemove', handleGlobalMouseMove);
window.addEventListener('mouseup', handleGlobalMouseUp);
const x = Math.max(0, Math.min(e.clientX - rect.left, rect.width));
const percent = (x / rect.width) * 100;
setSplit(percent);
},
[updateSplitFromClientX]
[setSplit]
);
// Touch handlers for mobile/tablets
const handleTouchStart = useCallback(
(e: React.TouchEvent<HTMLDivElement>) => {
if (!e.touches[0]) return;
isDraggingRef.current = true;
isInteractedRef.current = true;
cancelAnimationFrame(animIdRef.current);
updateSplitFromClientX(e.touches[0].clientX);
const handlePointerMove = useCallback(
(e: React.PointerEvent<HTMLDivElement>) => {
if (!isDraggingRef.current) return;
const clientX = e.clientX;
if (rafIdRef.current) {
cancelAnimationFrame(rafIdRef.current);
}
rafIdRef.current = requestAnimationFrame(() => {
let rect = cachedRectRef.current;
if (!rect && containerRef.current) {
const r = containerRef.current.getBoundingClientRect();
rect = { left: r.left, width: r.width };
cachedRectRef.current = rect;
}
if (!rect || rect.width <= 0) return;
const x = Math.max(0, Math.min(clientX - rect.left, rect.width));
const percent = (x / rect.width) * 100;
setSplit(percent);
});
},
[updateSplitFromClientX]
[setSplit]
);
const handleTouchMove = useCallback(
(e: React.TouchEvent<HTMLDivElement>) => {
if (!isDraggingRef.current || !e.touches[0]) return;
updateSplitFromClientX(e.touches[0].clientX);
},
[updateSplitFromClientX]
);
const handleTouchEnd = useCallback(() => {
const handlePointerUp = useCallback((e: React.PointerEvent<HTMLDivElement>) => {
if (!isDraggingRef.current) return;
isDraggingRef.current = false;
cachedRectRef.current = null;
if (rafIdRef.current) {
cancelAnimationFrame(rafIdRef.current);
rafIdRef.current = null;
}
try {
e.currentTarget.releasePointerCapture(e.pointerId);
} catch {
// Fallback
}
}, []);
return (
@@ -141,16 +147,19 @@ export function CardBeforeAfterSlider({
ref={containerRef}
onMouseEnter={handleMouseEnter}
onMouseLeave={handleMouseLeave}
onMouseDown={handleMouseDown}
onTouchStart={handleTouchStart}
onTouchMove={handleTouchMove}
onTouchEnd={handleTouchEnd}
onPointerDown={handlePointerDown}
onPointerMove={handlePointerMove}
onPointerUp={handlePointerUp}
onPointerCancel={handlePointerUp}
role="slider"
aria-label="Before and after transformation slider"
aria-valuenow={50}
tabIndex={0}
style={{ '--split': '50%' } as React.CSSProperties}
className={`relative w-full ${aspectRatio} overflow-hidden cursor-ew-resize select-none bg-slate-900 group/slider transition-shadow duration-300 hover:shadow-cream-lg`}
style={{
'--split': '50%',
touchAction: 'none', // Strictly prevents mobile touch scrolling interference
} as React.CSSProperties}
className={`relative w-full ${aspectRatio} overflow-hidden cursor-ew-resize select-none bg-slate-900 group/slider transition-shadow duration-300 hover:shadow-cream-lg touch-none`}
>
{/* Layer 1: After Image (Transformed Neural Result) */}
{/* eslint-disable-next-line @next/next/no-img-element */}
@@ -179,14 +188,14 @@ export function CardBeforeAfterSlider({
{/* Layer 3: Vertical Split Divider Line */}
<div
className="absolute top-0 bottom-0 w-[2.5px] bg-white z-20 pointer-events-none shadow-[0_0_10px_rgba(0,0,0,0.8)]"
className="absolute top-0 bottom-0 w-[2.5px] bg-white z-20 pointer-events-none shadow-[0_0_10px_rgba(0,0,0,0.8)] -translate-x-1/2"
style={{ left: 'var(--split)' }}
>
{/* Glowing Aura */}
<div className="absolute -top-4 -bottom-4 -left-1.5 w-3.5 bg-gradient-to-r from-blue-500/30 via-white/70 to-amber-400/30 blur-[2px]" />
{/* Center Pill Handle with Left/Right Arrows */}
<div className="absolute top-1/2 -translate-y-1/2 -translate-x-1/2 w-8 h-8 sm:w-9 sm:h-9 rounded-full bg-white text-slate-800 shadow-xl border border-slate-900/15 flex items-center justify-center transition-transform group-hover/slider:scale-110">
{/* Center Pill Handle with Left/Right Arrows & Touch Pad */}
<div className="absolute top-1/2 -translate-y-1/2 -translate-x-1/2 w-9 h-9 sm:w-10 sm:h-10 rounded-full bg-white text-slate-800 shadow-xl border border-slate-900/15 flex items-center justify-center transition-transform group-hover/slider:scale-110 before:absolute before:-inset-3 before:content-['']">
<svg className="w-3.5 h-3.5 text-blue-700" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2.5} d="M8 9l-3 3 3 3m8-6l3 3-3 3" />
</svg>
@@ -201,7 +210,7 @@ export function CardBeforeAfterSlider({
{afterLabel}
</div>
{/* Hover & Slide Hint */}
{/* Slide Hint */}
<div className="pointer-events-none absolute top-2.5 right-2.5 z-20 rounded-full bg-white/92 px-2.5 py-0.5 text-[9px] font-semibold text-slate-700 shadow-sm backdrop-blur-xs opacity-0 group-hover/slider:opacity-100 transition-opacity">
Drag to inspect
</div>
+94 -53
View File
@@ -29,15 +29,22 @@ export function Cinematic3DComparison({
const containerRef = useRef<HTMLDivElement>(null);
const scanLabelRef = useRef<HTMLSpanElement>(null);
const isPointerDownRef = useRef(false);
const cachedRectRef = useRef<{ left: number; width: number } | null>(null);
const rafIdRef = useRef<number | null>(null);
const updatePosition = useCallback((position: number) => {
sliderPosition.current = Math.max(0, Math.min(100, position));
containerRef.current?.style.setProperty('--split', `${sliderPosition.current}%`);
if (scanLabelRef.current) scanLabelRef.current.textContent = `SCAN: ${Math.round(sliderPosition.current)}%`;
if (containerRef.current) {
containerRef.current.style.setProperty('--split', `${sliderPosition.current}%`);
}
if (scanLabelRef.current) {
scanLabelRef.current.textContent = `SCAN: ${Math.round(sliderPosition.current)}%`;
}
containerRef.current?.setAttribute('aria-valuenow', `${Math.round(sliderPosition.current)}`);
}, []);
// Auto-slide smooth sine oscillation loop (only when explicitly requested)
// Auto-slide smooth sine oscillation loop (only when explicitly requested and not dragging)
useEffect(() => {
if (!autoSlide || isDragging) return;
@@ -46,24 +53,26 @@ export function Cinematic3DComparison({
let visible = true;
let lastUpdate = 0;
const animate = (time: number) => {
if (!visible || document.hidden) {
if (!visible || document.hidden || isPointerDownRef.current) {
animId = 0;
return;
}
animId = requestAnimationFrame(animate);
if (time - lastUpdate < 50) return;
if (time - lastUpdate < 30) return;
lastUpdate = time;
if (!start) start = time;
updatePosition(50 + 16 * Math.sin((time - start) * 0.001));
updatePosition(50 + 18 * Math.sin((time - start) * 0.0012));
};
const observer = new IntersectionObserver(([entry]) => {
visible = entry.isIntersecting;
if (visible && !animId) animId = requestAnimationFrame(animate);
if (visible && !animId && !isPointerDownRef.current) animId = requestAnimationFrame(animate);
if (!visible && animId) {
cancelAnimationFrame(animId);
animId = 0;
}
});
if (containerRef.current) observer.observe(containerRef.current);
animId = requestAnimationFrame(animate);
@@ -73,43 +82,70 @@ export function Cinematic3DComparison({
};
}, [autoSlide, isDragging, updatePosition]);
// Handle position calculation
const handleMove = useCallback((clientX: number) => {
if (!containerRef.current) return;
const rect = containerRef.current.getBoundingClientRect();
const x = Math.max(0, Math.min(clientX - rect.left, rect.width));
const percent = Math.max(0, Math.min(100, (x / rect.width) * 100));
updatePosition(percent);
}, [updatePosition]);
// Unified Pointer Handlers (Works with mouse on desktop + touches/pens on mobile/iOS/tablets)
const handlePointerDown = (e: React.PointerEvent<HTMLDivElement>) => {
if (e.button !== 0 && e.pointerType === 'mouse') return;
const handleTouchMove = useCallback((e: TouchEvent) => {
if (!isDragging) return;
handleMove(e.touches[0].clientX);
}, [isDragging, handleMove]);
isPointerDownRef.current = true;
setIsDragging(true);
const handleMouseMove = useCallback((e: MouseEvent) => {
if (!isDragging) return;
handleMove(e.clientX);
}, [isDragging, handleMove]);
const handleMouseUp = useCallback(() => {
setIsDragging(false);
}, []);
useEffect(() => {
if (isDragging) {
window.addEventListener('mousemove', handleMouseMove, { passive: true });
window.addEventListener('mouseup', handleMouseUp);
window.addEventListener('touchmove', handleTouchMove, { passive: true });
window.addEventListener('touchend', handleMouseUp);
// Capture pointer so fast drags outside the element bounds never lose tracking
try {
e.currentTarget.setPointerCapture(e.pointerId);
} catch {
// Fallback
}
return () => {
window.removeEventListener('mousemove', handleMouseMove);
window.removeEventListener('mouseup', handleMouseUp);
window.removeEventListener('touchmove', handleTouchMove);
window.removeEventListener('touchend', handleMouseUp);
};
}, [isDragging, handleMouseMove, handleMouseUp, handleTouchMove]);
// Cache rect on pointer down to eliminate layout thrashing during drag
const rect = e.currentTarget.getBoundingClientRect();
cachedRectRef.current = { left: rect.left, width: rect.width };
// Instantly update to pointer position
const x = Math.max(0, Math.min(e.clientX - rect.left, rect.width));
const percent = (x / rect.width) * 100;
updatePosition(percent);
};
const handlePointerMove = (e: React.PointerEvent<HTMLDivElement>) => {
if (!isPointerDownRef.current) return;
const clientX = e.clientX;
if (rafIdRef.current) {
cancelAnimationFrame(rafIdRef.current);
}
rafIdRef.current = requestAnimationFrame(() => {
let rect = cachedRectRef.current;
if (!rect && containerRef.current) {
const r = containerRef.current.getBoundingClientRect();
rect = { left: r.left, width: r.width };
cachedRectRef.current = rect;
}
if (!rect || rect.width <= 0) return;
const x = Math.max(0, Math.min(clientX - rect.left, rect.width));
const percent = (x / rect.width) * 100;
updatePosition(percent);
});
};
const handlePointerUp = (e: React.PointerEvent<HTMLDivElement>) => {
if (!isPointerDownRef.current) return;
isPointerDownRef.current = false;
cachedRectRef.current = null;
setIsDragging(false);
if (rafIdRef.current) {
cancelAnimationFrame(rafIdRef.current);
rafIdRef.current = null;
}
try {
e.currentTarget.releasePointerCapture(e.pointerId);
} catch {
// Fallback
}
};
const handleKeyDown = (event: React.KeyboardEvent<HTMLDivElement>) => {
const step = event.shiftKey ? 10 : 2;
@@ -127,11 +163,13 @@ export function Cinematic3DComparison({
return (
<div className={`w-full perspective-1400 select-none ${className}`}>
{/* 3D Kinetic Tilt Stage */}
{/* 3D Kinetic Tilt Stage with Locked Touch-Action for Flawless Mobile Swiping */}
<div
ref={containerRef}
onMouseDown={() => setIsDragging(true)}
onTouchStart={() => setIsDragging(true)}
onPointerDown={handlePointerDown}
onPointerMove={handlePointerMove}
onPointerUp={handlePointerUp}
onPointerCancel={handlePointerUp}
onKeyDown={handleKeyDown}
role="slider"
aria-label="Before and after comparison"
@@ -139,8 +177,11 @@ export function Cinematic3DComparison({
aria-valuemax={100}
aria-valuenow={50}
tabIndex={0}
className={`relative w-full ${aspectRatio} rounded-2xl sm:rounded-3xl overflow-hidden cursor-ew-resize preserve-3d transition-transform duration-150 ease-out shadow-cinematic-3d hover:shadow-cinematic-hover border border-slate-900/[0.08] bg-slate-950`}
style={{ '--split': '50%', touchAction: 'pan-y' } as React.CSSProperties}
className={`relative w-full ${aspectRatio} rounded-2xl sm:rounded-3xl overflow-hidden cursor-ew-resize preserve-3d transition-transform duration-150 ease-out shadow-cinematic-3d hover:shadow-cinematic-hover border border-slate-900/[0.08] bg-slate-950 touch-none`}
style={{
'--split': '50%',
touchAction: 'none', // Strictly prevents iOS/Android touch scrolling conflict on the slider
} as React.CSSProperties}
>
{/* Layer 1: After Image (Full Reconstructed Neural Result) */}
{/* eslint-disable-next-line @next/next/no-img-element */}
@@ -167,17 +208,17 @@ export function Cinematic3DComparison({
/>
</div>
{/* Layer 3: Illuminated Holographic Laser Split Line (Champagne Gold + Electric Sapphire) */}
{/* Layer 3: Illuminated Holographic Laser Split Line */}
<div
className="absolute top-0 bottom-0 w-[2px] bg-gradient-to-b from-blue-400 via-white to-amber-300 z-20 pointer-events-none"
className="absolute top-0 bottom-0 w-[2px] bg-gradient-to-b from-blue-400 via-white to-amber-300 z-20 pointer-events-none -translate-x-1/2"
style={{ left: 'var(--split)' }}
>
{/* Subtle Vertical Caustic Glow Beam */}
{/* Vertical Caustic Glow Beam */}
<div className="absolute -top-4 -bottom-4 -left-1.5 w-3.5 bg-gradient-to-r from-blue-500/20 via-white/40 to-amber-400/20 blur-[3px]" />
{/* 3D Tactile Center Control Handle floating at translateZ */}
{/* 3D Tactile Center Control Handle with generous touch-target area */}
<div
className="absolute top-1/2 -translate-y-1/2 -translate-x-1/2 w-9 h-9 sm:w-11 sm:h-11 rounded-full bg-white/95 backdrop-blur-md border border-slate-900/10 shadow-2xl flex items-center justify-center pointer-events-auto cursor-ew-resize hover:scale-110 active:scale-95 transition-transform duration-150 preserve-3d"
className="absolute top-1/2 -translate-y-1/2 -translate-x-1/2 w-10 h-10 sm:w-11 sm:h-11 rounded-full bg-white/95 backdrop-blur-md border border-slate-900/10 shadow-2xl flex items-center justify-center cursor-ew-resize hover:scale-110 active:scale-95 transition-transform duration-150 preserve-3d before:absolute before:-inset-3 before:content-['']"
style={{ transform: 'translateZ(28px)' }}
>
{/* Outer Metallic Ring */}
@@ -195,7 +236,7 @@ export function Cinematic3DComparison({
</div>
</div>
{/* Layer 4: Floating 3D Telemetry Badges (Floating at translateZ(32px)) */}
{/* Layer 4: Floating 3D Telemetry Badges */}
<div
className="absolute top-3.5 left-3.5 sm:top-5 sm:left-5 bg-white/85 backdrop-blur-md px-3 py-1.5 rounded-xl text-[10px] sm:text-[11px] font-mono font-bold text-slate-800 border border-slate-900/[0.08] pointer-events-none z-20 flex items-center gap-1.5 shadow-sm preserve-3d"
style={{ transform: 'translateZ(30px)' }}
@@ -212,7 +253,7 @@ export function Cinematic3DComparison({
<span>{afterLabel}</span>
</div>
{/* Lower Spatial Telemetry Chips (Enigma Archive Aesthetic) */}
{/* Lower Spatial Telemetry Chips */}
<div
className="absolute bottom-3.5 left-3.5 sm:bottom-4 sm:left-4 hidden sm:flex items-center gap-2 pointer-events-none z-20 preserve-3d"
style={{ transform: 'translateZ(26px)' }}