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
+1 -1
View File
@@ -28,7 +28,7 @@ interface TextAnimateProps {
} }
// Ultra-smooth Apple-grade exponential easing // Ultra-smooth Apple-grade exponential easing
const easeOutApple = [0.16, 1, 0.3, 1]; const easeOutApple = [0.16, 1, 0.3, 1] as const;
export function TextAnimate({ export function TextAnimate({
children, children,
@@ -185,31 +185,63 @@ function ShiftableRow({ items }: { items: ToolMediaItem[] }) {
className="w-full transition-[flex-grow] duration-1000 ease-[cubic-bezier(0.16,1,0.3,1)] will-change-[flex-grow] flex flex-col min-w-0" className="w-full transition-[flex-grow] duration-1000 ease-[cubic-bezier(0.16,1,0.3,1)] will-change-[flex-grow] flex flex-col min-w-0"
> >
{/* Window Container with strictly locked pixel height & landscape aspect */} {/* Window Container with strictly locked pixel height & landscape aspect */}
<Link {item.mediaType === 'comparison' ? (
href={`/tools/${item.slug}`} <div className="group block relative w-full h-[220px] sm:h-[240px] lg:h-[260px] rounded-2xl sm:rounded-3xl overflow-hidden bg-slate-950 border border-slate-900/[0.08] shadow-cream-sm">
className="group block relative w-full h-[220px] sm:h-[240px] lg:h-[260px] rounded-2xl sm:rounded-3xl overflow-hidden bg-slate-950 border border-slate-900/[0.08] shadow-cream-sm" {/* GPU-Composited Shadow Elevation Layer */}
> <div
{/* GPU-Composited Shadow Elevation Layer (Opacity-only transition, zero paint thrash) */} className="absolute -inset-px rounded-2xl sm:rounded-3xl shadow-cream-lg opacity-0 group-hover:opacity-100 transition-opacity duration-700 ease-[cubic-bezier(0.16,1,0.3,1)] pointer-events-none z-30"
<div aria-hidden="true"
className="absolute -inset-px rounded-2xl sm:rounded-3xl shadow-cream-lg opacity-0 group-hover:opacity-100 transition-opacity duration-700 ease-[cubic-bezier(0.16,1,0.3,1)] pointer-events-none z-30" />
aria-hidden="true"
/>
{/* Media Renderer */} {/* Media Renderer (Interactive comparison slider with touch-action: none) */}
<ToolWindowMedia item={item} isHovered={isHovered} /> <ToolWindowMedia item={item} isHovered={isHovered} />
{/* Hover Media Type Pill (Smooth GPU Opacity Transition) */} {/* Dedicated Tool Link Pill on top right so sliding never accidentally navigates */}
<div <Link
className="absolute top-3 left-3 z-20 pointer-events-none opacity-0 group-hover:opacity-100 transition-opacity duration-500 ease-[cubic-bezier(0.16,1,0.3,1)]" href={`/tools/${item.slug}`}
> className="absolute top-3 right-3 z-30 inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-[10px] font-mono font-bold tracking-wider uppercase bg-slate-950/85 backdrop-blur-md text-white border border-white/20 hover:bg-blue-600 transition-colors shadow-sm"
<span className="inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-[10px] font-mono font-bold tracking-wider uppercase bg-slate-950/85 backdrop-blur-md text-white border border-white/20"> aria-label={`Open ${item.title}`}
{item.mediaType === 'video' && <Video className="w-3 h-3 text-cyan-400" />} >
{item.mediaType === 'comparison' && <Sliders className="w-3 h-3 text-amber-400" />} <span>TRY TOOL</span>
{item.mediaType === 'photo' && <ImageIcon className="w-3 h-3 text-emerald-400" />} <ArrowRight className="w-2.5 h-2.5" />
<span>{item.mediaType}</span> </Link>
</span>
{/* Hover Media Type Pill */}
<div
className="absolute top-3 left-3 z-20 pointer-events-none opacity-0 group-hover:opacity-100 transition-opacity duration-500 ease-[cubic-bezier(0.16,1,0.3,1)]"
>
<span className="inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-[10px] font-mono font-bold tracking-wider uppercase bg-slate-950/85 backdrop-blur-md text-white border border-white/20">
<Sliders className="w-3 h-3 text-amber-400" />
<span>comparison</span>
</span>
</div>
</div> </div>
</Link> ) : (
<Link
href={`/tools/${item.slug}`}
className="group block relative w-full h-[220px] sm:h-[240px] lg:h-[260px] rounded-2xl sm:rounded-3xl overflow-hidden bg-slate-950 border border-slate-900/[0.08] shadow-cream-sm"
>
{/* GPU-Composited Shadow Elevation Layer (Opacity-only transition, zero paint thrash) */}
<div
className="absolute -inset-px rounded-2xl sm:rounded-3xl shadow-cream-lg opacity-0 group-hover:opacity-100 transition-opacity duration-700 ease-[cubic-bezier(0.16,1,0.3,1)] pointer-events-none z-30"
aria-hidden="true"
/>
{/* Media Renderer */}
<ToolWindowMedia item={item} isHovered={isHovered} />
{/* Hover Media Type Pill (Smooth GPU Opacity Transition) */}
<div
className="absolute top-3 left-3 z-20 pointer-events-none opacity-0 group-hover:opacity-100 transition-opacity duration-500 ease-[cubic-bezier(0.16,1,0.3,1)]"
>
<span className="inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-[10px] font-mono font-bold tracking-wider uppercase bg-slate-950/85 backdrop-blur-md text-white border border-white/20">
{item.mediaType === 'video' && <Video className="w-3 h-3 text-cyan-400" />}
{item.mediaType === 'photo' && <ImageIcon className="w-3 h-3 text-emerald-400" />}
<span>{item.mediaType}</span>
</span>
</div>
</Link>
)}
{/* Little Title Below Window (Fixed height, no vertical jumping) */} {/* Little Title Below Window (Fixed height, no vertical jumping) */}
<Link <Link
@@ -234,6 +266,9 @@ function ToolWindowMedia({ item, isHovered }: { item: ToolMediaItem; isHovered:
// High performance refs - completely eliminates per-frame React re-renders! // High performance refs - completely eliminates per-frame React re-renders!
const isManualRef = useRef(false); const isManualRef = useRef(false);
const isInteractedRef = useRef(false);
const isPointerDownRef = useRef(false);
const currentPercentRef = useRef(50);
const animFrameRef = useRef<number | null>(null); const animFrameRef = useRef<number | null>(null);
const pointerRafRef = useRef<number | null>(null); const pointerRafRef = useRef<number | null>(null);
const cachedRectRef = useRef<{ left: number; width: number } | null>(null); const cachedRectRef = useRef<{ left: number; width: number } | null>(null);
@@ -241,12 +276,16 @@ function ToolWindowMedia({ item, isHovered }: { item: ToolMediaItem; isHovered:
// Directly mutate DOM styles on the GPU layer without triggering React reconciliation // Directly mutate DOM styles on the GPU layer without triggering React reconciliation
const setSliderDOM = useCallback((percent: number) => { const setSliderDOM = useCallback((percent: number) => {
const clamped = Math.max(8, Math.min(92, percent)); const clamped = Math.max(8, Math.min(92, percent));
currentPercentRef.current = clamped;
if (dividerRef.current) { if (dividerRef.current) {
dividerRef.current.style.left = `${clamped}%`; dividerRef.current.style.left = `${clamped}%`;
} }
if (afterImgRef.current) { if (afterImgRef.current) {
afterImgRef.current.style.clipPath = `inset(0 ${100 - clamped}% 0 0)`; afterImgRef.current.style.clipPath = `inset(0 ${100 - clamped}% 0 0)`;
} }
if (containerRef.current) {
containerRef.current.setAttribute('aria-valuenow', `${Math.round(clamped)}`);
}
}, []); }, []);
// Video Autoplay Muted Loop only on Hover (No zoom, no scale) // Video Autoplay Muted Loop only on Hover (No zoom, no scale)
@@ -267,18 +306,22 @@ function ToolWindowMedia({ item, isHovered }: { item: ToolMediaItem; isHovered:
if (item.mediaType !== 'comparison') return; if (item.mediaType !== 'comparison') return;
if (!isHovered) { if (!isHovered) {
isManualRef.current = false; if (!isInteractedRef.current) {
if (animFrameRef.current) { if (animFrameRef.current) {
cancelAnimationFrame(animFrameRef.current); cancelAnimationFrame(animFrameRef.current);
animFrameRef.current = null; animFrameRef.current = null;
}
setSliderDOM(50);
} }
setSliderDOM(50);
return; return;
} }
// If user has already interacted, do not overwrite their position
if (isInteractedRef.current) return;
const startTime = performance.now(); const startTime = performance.now();
const sweep = (now: number) => { const sweep = (now: number) => {
if (!isManualRef.current) { if (!isManualRef.current && !isInteractedRef.current) {
const elapsed = (now - startTime) / 1000; const elapsed = (now - startTime) / 1000;
// Calm, breathing oscillation: 1.4 rad/s sine wave with 22% sweep amplitude // Calm, breathing oscillation: 1.4 rad/s sine wave with 22% sweep amplitude
const pos = 50 + Math.sin(elapsed * 1.4) * 22; const pos = 50 + Math.sin(elapsed * 1.4) * 22;
@@ -298,17 +341,49 @@ function ToolWindowMedia({ item, isHovered }: { item: ToolMediaItem; isHovered:
}, [isHovered, item.mediaType, setSliderDOM]); }, [isHovered, item.mediaType, setSliderDOM]);
// Pointer position tracking: // Pointer position tracking:
// Caches container bounding rect on enter to avoid layout thrashing in pointermove. // Caches container bounding rect on pointer down to eliminate layout thrashing in pointermove.
// Updates slider DOM in requestAnimationFrame with zero React state calls. // Updates slider DOM directly in requestAnimationFrame with zero React state calls.
const handlePointerEnter = (e: React.PointerEvent<HTMLDivElement>) => { const handlePointerEnter = (e: React.PointerEvent<HTMLDivElement>) => {
if (item.mediaType !== 'comparison') return; if (item.mediaType !== 'comparison') return;
const rect = e.currentTarget.getBoundingClientRect(); const rect = e.currentTarget.getBoundingClientRect();
cachedRectRef.current = { left: rect.left, width: rect.width }; cachedRectRef.current = { left: rect.left, width: rect.width };
}; };
const handlePointerDown = (e: React.PointerEvent<HTMLDivElement>) => {
if (item.mediaType !== 'comparison') return;
if (e.button !== 0 && e.pointerType === 'mouse') return;
// Prevent container click bubbling and vertical scrolling
e.stopPropagation();
isManualRef.current = true;
isInteractedRef.current = true;
isPointerDownRef.current = true;
if (animFrameRef.current) {
cancelAnimationFrame(animFrameRef.current);
animFrameRef.current = null;
}
try {
e.currentTarget.setPointerCapture(e.pointerId);
} catch {
// Fallback
}
const rect = e.currentTarget.getBoundingClientRect();
cachedRectRef.current = { left: rect.left, width: rect.width };
const x = Math.max(0, Math.min(e.clientX - rect.left, rect.width));
const percent = (x / rect.width) * 100;
setSliderDOM(percent);
};
const handlePointerMove = (e: React.PointerEvent<HTMLDivElement>) => { const handlePointerMove = (e: React.PointerEvent<HTMLDivElement>) => {
if (item.mediaType !== 'comparison') return; if (item.mediaType !== 'comparison') return;
if (!isPointerDownRef.current) return;
isManualRef.current = true; isManualRef.current = true;
isInteractedRef.current = true;
const clientX = e.clientX; const clientX = e.clientX;
if (pointerRafRef.current) { if (pointerRafRef.current) {
@@ -330,13 +405,44 @@ function ToolWindowMedia({ item, isHovered }: { item: ToolMediaItem; isHovered:
}); });
}; };
const handlePointerLeave = () => { const handlePointerUp = (e: React.PointerEvent<HTMLDivElement>) => {
isManualRef.current = false; if (item.mediaType !== 'comparison') return;
isPointerDownRef.current = false;
cachedRectRef.current = null; cachedRectRef.current = null;
if (pointerRafRef.current) { if (pointerRafRef.current) {
cancelAnimationFrame(pointerRafRef.current); cancelAnimationFrame(pointerRafRef.current);
pointerRafRef.current = null; pointerRafRef.current = null;
} }
try {
e.currentTarget.releasePointerCapture(e.pointerId);
} catch {
// Fallback
}
};
const handlePointerLeave = () => {
if (isPointerDownRef.current) return; // Keep tracking if pointer capture is active
cachedRectRef.current = null;
if (pointerRafRef.current) {
cancelAnimationFrame(pointerRafRef.current);
pointerRafRef.current = null;
}
};
const handleKeyDown = (e: React.KeyboardEvent<HTMLDivElement>) => {
if (item.mediaType !== 'comparison') return;
const step = e.shiftKey ? 10 : 2;
if (e.key === 'ArrowLeft' || e.key === 'ArrowDown') {
e.preventDefault();
isInteractedRef.current = true;
isManualRef.current = true;
setSliderDOM(currentPercentRef.current - step);
} else if (e.key === 'ArrowRight' || e.key === 'ArrowUp') {
e.preventDefault();
isInteractedRef.current = true;
isManualRef.current = true;
setSliderDOM(currentPercentRef.current + step);
}
}; };
// 1. VIDEO (Strictly locked to fixed 680px centered width - ZERO ZOOM) // 1. VIDEO (Strictly locked to fixed 680px centered width - ZERO ZOOM)
@@ -364,9 +470,20 @@ function ToolWindowMedia({ item, isHovered }: { item: ToolMediaItem; isHovered:
<div <div
ref={containerRef} ref={containerRef}
onPointerEnter={handlePointerEnter} onPointerEnter={handlePointerEnter}
onPointerDown={handlePointerDown}
onPointerMove={handlePointerMove} onPointerMove={handlePointerMove}
onPointerUp={handlePointerUp}
onPointerCancel={handlePointerUp}
onPointerLeave={handlePointerLeave} onPointerLeave={handlePointerLeave}
className="relative w-full h-full select-none cursor-ew-resize overflow-hidden bg-slate-950 transform-gpu [backface-visibility:hidden]" onKeyDown={handleKeyDown}
role="slider"
aria-label="Before and after comparison slider"
aria-valuemin={8}
aria-valuemax={92}
aria-valuenow={50}
tabIndex={0}
style={{ touchAction: 'none' }}
className="relative w-full h-full select-none cursor-ew-resize overflow-hidden bg-slate-950 transform-gpu [backface-visibility:hidden] touch-none"
> >
{/* BEFORE Image (Base layer, fixed scale & position, 0% zoom) */} {/* BEFORE Image (Base layer, fixed scale & position, 0% zoom) */}
<img <img
@@ -391,25 +508,23 @@ function ToolWindowMedia({ item, isHovered }: { item: ToolMediaItem; isHovered:
{/* Glowing Slider Divider Line (Direct GPU transform & position) */} {/* Glowing Slider Divider Line (Direct GPU transform & position) */}
<div <div
ref={dividerRef} ref={dividerRef}
className="absolute top-0 bottom-0 w-[2px] bg-white shadow-[0_0_12px_rgba(255,255,255,1)] pointer-events-none z-10 will-change-transform transform-gpu -translate-x-1/2" className="absolute top-0 bottom-0 w-[2.5px] bg-white shadow-[0_0_12px_rgba(255,255,255,1)] pointer-events-none z-10 will-change-transform transform-gpu -translate-x-1/2"
style={{ left: '50%' }} style={{ left: '50%' }}
> >
{/* Circular Grab Handle with Before/After Arrow Cue */} {/* Circular Grab Handle with Before/After Arrow Cue & Touch Padding */}
<div className="absolute top-1/2 -translate-y-1/2 -translate-x-1/2 left-1/2 w-7 h-7 rounded-full bg-white shadow-lg border border-slate-200/90 flex items-center justify-center text-[10px] font-bold text-slate-900 pointer-events-none"> <div className="absolute top-1/2 -translate-y-1/2 -translate-x-1/2 left-1/2 w-8 h-8 rounded-full bg-white shadow-xl border border-slate-200/90 flex items-center justify-center text-xs font-bold text-blue-600 pointer-events-none before:absolute before:-inset-3 before:content-['']">
↔ ↔
</div> </div>
</div> </div>
{/* Badges with Smooth GPU Opacity Transition (No DOM mounting/unmounting) */} {/* Badges with Smooth Contrast */}
<div <div
className={`absolute bottom-3 inset-x-3 flex justify-between pointer-events-none z-20 text-[9px] font-mono font-bold uppercase tracking-wider text-white transition-opacity duration-300 ease-[cubic-bezier(0.16,1,0.3,1)] ${ className="absolute bottom-3 inset-x-3 flex justify-between pointer-events-none z-20 text-[9px] font-mono font-bold uppercase tracking-wider text-white"
isHovered ? 'opacity-100' : 'opacity-0'
}`}
> >
<span className="bg-slate-950/80 px-2 py-0.5 rounded backdrop-blur border border-white/10"> <span className="bg-slate-950/80 px-2 py-0.5 rounded backdrop-blur border border-white/10 shadow-xs">
AFTER AFTER
</span> </span>
<span className="bg-slate-950/80 px-2 py-0.5 rounded backdrop-blur border border-white/10"> <span className="bg-slate-950/80 px-2 py-0.5 rounded backdrop-blur border border-white/10 shadow-xs">
BEFORE BEFORE
</span> </span>
</div> </div>
+72 -63
View File
@@ -21,7 +21,9 @@ export function CardBeforeAfterSlider({
const isHoveredRef = useRef(false); const isHoveredRef = useRef(false);
const isDraggingRef = useRef(false); const isDraggingRef = useRef(false);
const isInteractedRef = useRef(false); const isInteractedRef = useRef(false);
const cachedRectRef = useRef<{ left: number; width: number } | null>(null);
const animIdRef = useRef<number>(0); const animIdRef = useRef<number>(0);
const rafIdRef = useRef<number | null>(null);
const [isHoveredState, setIsHoveredState] = useState(false); const [isHoveredState, setIsHoveredState] = useState(false);
const setSplit = useCallback((percent: number) => { const setSplit = useCallback((percent: number) => {
@@ -32,28 +34,15 @@ export function CardBeforeAfterSlider({
} }
}, []); }, []);
const updateSplitFromClientX = useCallback( // Smooth gentle oscillation: runs on desktop when hovered before user manually drags
(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!
useEffect(() => { useEffect(() => {
let startTime: number | null = null; let startTime: number | null = null;
const animate = (time: number) => { const animate = (time: number) => {
// ONLY animate when actively hovered and not manually dragging
if (isHoveredRef.current && !isDraggingRef.current && !isInteractedRef.current) { if (isHoveredRef.current && !isDraggingRef.current && !isInteractedRef.current) {
if (startTime === null) startTime = time; if (startTime === null) startTime = time;
const elapsed = time - startTime; const elapsed = time - startTime;
// Calm, luxurious 3.6-second oscillation between 28% and 72% const currentSplit = 50 + 22 * Math.sin((elapsed / 3200) * 2 * Math.PI);
const currentSplit = 50 + 22 * Math.sin((elapsed / 3600) * 2 * Math.PI);
setSplit(currentSplit); setSplit(currentSplit);
animIdRef.current = requestAnimationFrame(animate); animIdRef.current = requestAnimationFrame(animate);
} }
@@ -78,62 +67,79 @@ export function CardBeforeAfterSlider({
const handleMouseLeave = useCallback(() => { const handleMouseLeave = useCallback(() => {
isHoveredRef.current = false; isHoveredRef.current = false;
isDraggingRef.current = false;
setIsHoveredState(false); setIsHoveredState(false);
// Smoothly return to clean 50% rest state if (!isDraggingRef.current && !isInteractedRef.current) {
if (!isInteractedRef.current) {
setSplit(50); setSplit(50);
} }
}, [setSplit]); }, [setSplit]);
// Click & Drag handlers: manual inspection when user clicks or drags // Unified Pointer Handlers (Flawless on iOS/Android touchscreens and desktop mouse)
const handleMouseDown = useCallback( const handlePointerDown = useCallback(
(e: React.MouseEvent<HTMLDivElement>) => { (e: React.PointerEvent<HTMLDivElement>) => {
e.preventDefault(); if (e.button !== 0 && e.pointerType === 'mouse') return;
isDraggingRef.current = true; isDraggingRef.current = true;
isInteractedRef.current = true; isInteractedRef.current = true;
cancelAnimationFrame(animIdRef.current); cancelAnimationFrame(animIdRef.current);
updateSplitFromClientX(e.clientX);
const handleGlobalMouseMove = (moveEvent: MouseEvent) => { try {
if (!isDraggingRef.current) return; e.currentTarget.setPointerCapture(e.pointerId);
updateSplitFromClientX(moveEvent.clientX); } catch {
}; // Fallback
}
const handleGlobalMouseUp = () => { // Cache rect on pointer down to eliminate layout thrashing
isDraggingRef.current = false; const rect = e.currentTarget.getBoundingClientRect();
window.removeEventListener('mousemove', handleGlobalMouseMove); cachedRectRef.current = { left: rect.left, width: rect.width };
window.removeEventListener('mouseup', handleGlobalMouseUp);
};
window.addEventListener('mousemove', handleGlobalMouseMove); const x = Math.max(0, Math.min(e.clientX - rect.left, rect.width));
window.addEventListener('mouseup', handleGlobalMouseUp); const percent = (x / rect.width) * 100;
setSplit(percent);
}, },
[updateSplitFromClientX] [setSplit]
); );
// Touch handlers for mobile/tablets const handlePointerMove = useCallback(
const handleTouchStart = useCallback( (e: React.PointerEvent<HTMLDivElement>) => {
(e: React.TouchEvent<HTMLDivElement>) => { if (!isDraggingRef.current) return;
if (!e.touches[0]) return;
isDraggingRef.current = true; const clientX = e.clientX;
isInteractedRef.current = true; if (rafIdRef.current) {
cancelAnimationFrame(animIdRef.current); cancelAnimationFrame(rafIdRef.current);
updateSplitFromClientX(e.touches[0].clientX); }
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( const handlePointerUp = useCallback((e: React.PointerEvent<HTMLDivElement>) => {
(e: React.TouchEvent<HTMLDivElement>) => { if (!isDraggingRef.current) return;
if (!isDraggingRef.current || !e.touches[0]) return;
updateSplitFromClientX(e.touches[0].clientX);
},
[updateSplitFromClientX]
);
const handleTouchEnd = useCallback(() => {
isDraggingRef.current = false; isDraggingRef.current = false;
cachedRectRef.current = null;
if (rafIdRef.current) {
cancelAnimationFrame(rafIdRef.current);
rafIdRef.current = null;
}
try {
e.currentTarget.releasePointerCapture(e.pointerId);
} catch {
// Fallback
}
}, []); }, []);
return ( return (
@@ -141,16 +147,19 @@ export function CardBeforeAfterSlider({
ref={containerRef} ref={containerRef}
onMouseEnter={handleMouseEnter} onMouseEnter={handleMouseEnter}
onMouseLeave={handleMouseLeave} onMouseLeave={handleMouseLeave}
onMouseDown={handleMouseDown} onPointerDown={handlePointerDown}
onTouchStart={handleTouchStart} onPointerMove={handlePointerMove}
onTouchMove={handleTouchMove} onPointerUp={handlePointerUp}
onTouchEnd={handleTouchEnd} onPointerCancel={handlePointerUp}
role="slider" role="slider"
aria-label="Before and after transformation slider" aria-label="Before and after transformation slider"
aria-valuenow={50} aria-valuenow={50}
tabIndex={0} tabIndex={0}
style={{ '--split': '50%' } as React.CSSProperties} style={{
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`} '--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) */} {/* Layer 1: After Image (Transformed Neural Result) */}
{/* eslint-disable-next-line @next/next/no-img-element */} {/* eslint-disable-next-line @next/next/no-img-element */}
@@ -179,14 +188,14 @@ export function CardBeforeAfterSlider({
{/* Layer 3: Vertical Split Divider Line */} {/* Layer 3: Vertical Split Divider Line */}
<div <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)' }} style={{ left: 'var(--split)' }}
> >
{/* Glowing Aura */} {/* 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]" /> <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 */} {/* Center Pill Handle with Left/Right Arrows & Touch Pad */}
<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"> <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"> <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" /> <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2.5} d="M8 9l-3 3 3 3m8-6l3 3-3 3" />
</svg> </svg>
@@ -201,7 +210,7 @@ export function CardBeforeAfterSlider({
{afterLabel} {afterLabel}
</div> </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"> <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 Drag to inspect
</div> </div>
+94 -53
View File
@@ -29,15 +29,22 @@ export function Cinematic3DComparison({
const containerRef = useRef<HTMLDivElement>(null); const containerRef = useRef<HTMLDivElement>(null);
const scanLabelRef = useRef<HTMLSpanElement>(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) => { const updatePosition = useCallback((position: number) => {
sliderPosition.current = Math.max(0, Math.min(100, position)); sliderPosition.current = Math.max(0, Math.min(100, position));
containerRef.current?.style.setProperty('--split', `${sliderPosition.current}%`); if (containerRef.current) {
if (scanLabelRef.current) scanLabelRef.current.textContent = `SCAN: ${Math.round(sliderPosition.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)}`); 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(() => { useEffect(() => {
if (!autoSlide || isDragging) return; if (!autoSlide || isDragging) return;
@@ -46,24 +53,26 @@ export function Cinematic3DComparison({
let visible = true; let visible = true;
let lastUpdate = 0; let lastUpdate = 0;
const animate = (time: number) => { const animate = (time: number) => {
if (!visible || document.hidden) { if (!visible || document.hidden || isPointerDownRef.current) {
animId = 0; animId = 0;
return; return;
} }
animId = requestAnimationFrame(animate); animId = requestAnimationFrame(animate);
if (time - lastUpdate < 50) return; if (time - lastUpdate < 30) return;
lastUpdate = time; lastUpdate = time;
if (!start) start = 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]) => { const observer = new IntersectionObserver(([entry]) => {
visible = entry.isIntersecting; visible = entry.isIntersecting;
if (visible && !animId) animId = requestAnimationFrame(animate); if (visible && !animId && !isPointerDownRef.current) animId = requestAnimationFrame(animate);
if (!visible && animId) { if (!visible && animId) {
cancelAnimationFrame(animId); cancelAnimationFrame(animId);
animId = 0; animId = 0;
} }
}); });
if (containerRef.current) observer.observe(containerRef.current); if (containerRef.current) observer.observe(containerRef.current);
animId = requestAnimationFrame(animate); animId = requestAnimationFrame(animate);
@@ -73,43 +82,70 @@ export function Cinematic3DComparison({
}; };
}, [autoSlide, isDragging, updatePosition]); }, [autoSlide, isDragging, updatePosition]);
// Handle position calculation // Unified Pointer Handlers (Works with mouse on desktop + touches/pens on mobile/iOS/tablets)
const handleMove = useCallback((clientX: number) => { const handlePointerDown = (e: React.PointerEvent<HTMLDivElement>) => {
if (!containerRef.current) return; if (e.button !== 0 && e.pointerType === 'mouse') 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]);
const handleTouchMove = useCallback((e: TouchEvent) => { isPointerDownRef.current = true;
if (!isDragging) return; setIsDragging(true);
handleMove(e.touches[0].clientX);
}, [isDragging, handleMove]);
const handleMouseMove = useCallback((e: MouseEvent) => { // Capture pointer so fast drags outside the element bounds never lose tracking
if (!isDragging) return; try {
handleMove(e.clientX); e.currentTarget.setPointerCapture(e.pointerId);
}, [isDragging, handleMove]); } catch {
// Fallback
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);
} }
return () => {
window.removeEventListener('mousemove', handleMouseMove); // Cache rect on pointer down to eliminate layout thrashing during drag
window.removeEventListener('mouseup', handleMouseUp); const rect = e.currentTarget.getBoundingClientRect();
window.removeEventListener('touchmove', handleTouchMove); cachedRectRef.current = { left: rect.left, width: rect.width };
window.removeEventListener('touchend', handleMouseUp);
}; // Instantly update to pointer position
}, [isDragging, handleMouseMove, handleMouseUp, handleTouchMove]); 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 handleKeyDown = (event: React.KeyboardEvent<HTMLDivElement>) => {
const step = event.shiftKey ? 10 : 2; const step = event.shiftKey ? 10 : 2;
@@ -127,11 +163,13 @@ export function Cinematic3DComparison({
return ( return (
<div className={`w-full perspective-1400 select-none ${className}`}> <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 <div
ref={containerRef} ref={containerRef}
onMouseDown={() => setIsDragging(true)} onPointerDown={handlePointerDown}
onTouchStart={() => setIsDragging(true)} onPointerMove={handlePointerMove}
onPointerUp={handlePointerUp}
onPointerCancel={handlePointerUp}
onKeyDown={handleKeyDown} onKeyDown={handleKeyDown}
role="slider" role="slider"
aria-label="Before and after comparison" aria-label="Before and after comparison"
@@ -139,8 +177,11 @@ export function Cinematic3DComparison({
aria-valuemax={100} aria-valuemax={100}
aria-valuenow={50} aria-valuenow={50}
tabIndex={0} 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`} 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: 'pan-y' } as React.CSSProperties} 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) */} {/* Layer 1: After Image (Full Reconstructed Neural Result) */}
{/* eslint-disable-next-line @next/next/no-img-element */} {/* eslint-disable-next-line @next/next/no-img-element */}
@@ -167,17 +208,17 @@ export function Cinematic3DComparison({
/> />
</div> </div>
{/* Layer 3: Illuminated Holographic Laser Split Line (Champagne Gold + Electric Sapphire) */} {/* Layer 3: Illuminated Holographic Laser Split Line */}
<div <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)' }} 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]" /> <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 <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)' }} style={{ transform: 'translateZ(28px)' }}
> >
{/* Outer Metallic Ring */} {/* Outer Metallic Ring */}
@@ -195,7 +236,7 @@ export function Cinematic3DComparison({
</div> </div>
</div> </div>
{/* Layer 4: Floating 3D Telemetry Badges (Floating at translateZ(32px)) */} {/* Layer 4: Floating 3D Telemetry Badges */}
<div <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" 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)' }} style={{ transform: 'translateZ(30px)' }}
@@ -212,7 +253,7 @@ export function Cinematic3DComparison({
<span>{afterLabel}</span> <span>{afterLabel}</span>
</div> </div>
{/* Lower Spatial Telemetry Chips (Enigma Archive Aesthetic) */} {/* Lower Spatial Telemetry Chips */}
<div <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" 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)' }} style={{ transform: 'translateZ(26px)' }}
+51
View File
@@ -0,0 +1,51 @@
import { describe, it, expect } from 'vitest';
import React from 'react';
import { renderToString } from 'react-dom/server';
import { Cinematic3DComparison } from '@/components/ui/Cinematic3DComparison';
import { CardBeforeAfterSlider } from '@/components/ui/CardBeforeAfterSlider';
import { ShiftableToolsGridSection } from '@/components/sections/ShiftableToolsGridSection';
describe('Before/After Comparison Sliders (Mobile & Touch Responsiveness)', () => {
it('Cinematic3DComparison renders with touch-none, role="slider", and touchAction: none', () => {
const html = renderToString(
<Cinematic3DComparison
beforeUrl="/before.jpg"
afterUrl="/after.jpg"
beforeLabel="Original"
afterLabel="Enhanced"
/>
);
expect(html).toContain('role="slider"');
expect(html).toContain('aria-label="Before and after comparison"');
expect(html).toContain('touch-none');
expect(html).toContain('touch-action:none');
});
it('CardBeforeAfterSlider renders with touch-none, role="slider", and touchAction: none', () => {
const html = renderToString(
<CardBeforeAfterSlider
beforeUrl="/before.jpg"
afterUrl="/after.jpg"
/>
);
expect(html).toContain('role="slider"');
expect(html).toContain('aria-label="Before and after transformation slider"');
expect(html).toContain('touch-none');
expect(html).toContain('touch-action:none');
expect(html).toContain('--split:50%');
});
it('ShiftableToolsGridSection renders comparison sliders as standalone interactive cards with touch-action: none', () => {
const html = renderToString(
<ShiftableToolsGridSection />
);
expect(html).toContain('role="slider"');
expect(html).toContain('aria-label="Before and after comparison slider"');
expect(html).toContain('touch-none');
expect(html).toContain('touch-action:none');
expect(html).toContain('TRY TOOL');
});
});