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
const easeOutApple = [0.16, 1, 0.3, 1];
const easeOutApple = [0.16, 1, 0.3, 1] as const;
export function TextAnimate({
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"
>
{/* Window Container with strictly locked pixel height & landscape aspect */}
<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"
/>
{item.mediaType === 'comparison' ? (
<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">
{/* GPU-Composited Shadow Elevation Layer */}
<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} />
{/* Media Renderer (Interactive comparison slider with touch-action: none) */}
<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 === 'comparison' && <Sliders className="w-3 h-3 text-amber-400" />}
{item.mediaType === 'photo' && <ImageIcon className="w-3 h-3 text-emerald-400" />}
<span>{item.mediaType}</span>
</span>
{/* Dedicated Tool Link Pill on top right so sliding never accidentally navigates */}
<Link
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"
aria-label={`Open ${item.title}`}
>
<span>TRY TOOL</span>
<ArrowRight className="w-2.5 h-2.5" />
</Link>
{/* 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>
</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) */}
<Link
@@ -234,6 +266,9 @@ function ToolWindowMedia({ item, isHovered }: { item: ToolMediaItem; isHovered:
// High performance refs - completely eliminates per-frame React re-renders!
const isManualRef = useRef(false);
const isInteractedRef = useRef(false);
const isPointerDownRef = useRef(false);
const currentPercentRef = useRef(50);
const animFrameRef = useRef<number | null>(null);
const pointerRafRef = useRef<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
const setSliderDOM = useCallback((percent: number) => {
const clamped = Math.max(8, Math.min(92, percent));
currentPercentRef.current = clamped;
if (dividerRef.current) {
dividerRef.current.style.left = `${clamped}%`;
}
if (afterImgRef.current) {
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)
@@ -267,18 +306,22 @@ function ToolWindowMedia({ item, isHovered }: { item: ToolMediaItem; isHovered:
if (item.mediaType !== 'comparison') return;
if (!isHovered) {
isManualRef.current = false;
if (animFrameRef.current) {
cancelAnimationFrame(animFrameRef.current);
animFrameRef.current = null;
if (!isInteractedRef.current) {
if (animFrameRef.current) {
cancelAnimationFrame(animFrameRef.current);
animFrameRef.current = null;
}
setSliderDOM(50);
}
setSliderDOM(50);
return;
}
// If user has already interacted, do not overwrite their position
if (isInteractedRef.current) return;
const startTime = performance.now();
const sweep = (now: number) => {
if (!isManualRef.current) {
if (!isManualRef.current && !isInteractedRef.current) {
const elapsed = (now - startTime) / 1000;
// Calm, breathing oscillation: 1.4 rad/s sine wave with 22% sweep amplitude
const pos = 50 + Math.sin(elapsed * 1.4) * 22;
@@ -298,17 +341,49 @@ function ToolWindowMedia({ item, isHovered }: { item: ToolMediaItem; isHovered:
}, [isHovered, item.mediaType, setSliderDOM]);
// Pointer position tracking:
// Caches container bounding rect on enter to avoid layout thrashing in pointermove.
// Updates slider DOM in requestAnimationFrame with zero React state calls.
// Caches container bounding rect on pointer down to eliminate layout thrashing in pointermove.
// Updates slider DOM directly in requestAnimationFrame with zero React state calls.
const handlePointerEnter = (e: React.PointerEvent<HTMLDivElement>) => {
if (item.mediaType !== 'comparison') return;
const rect = e.currentTarget.getBoundingClientRect();
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>) => {
if (item.mediaType !== 'comparison') return;
if (!isPointerDownRef.current) return;
isManualRef.current = true;
isInteractedRef.current = true;
const clientX = e.clientX;
if (pointerRafRef.current) {
@@ -330,13 +405,44 @@ function ToolWindowMedia({ item, isHovered }: { item: ToolMediaItem; isHovered:
});
};
const handlePointerLeave = () => {
isManualRef.current = false;
const handlePointerUp = (e: React.PointerEvent<HTMLDivElement>) => {
if (item.mediaType !== 'comparison') return;
isPointerDownRef.current = false;
cachedRectRef.current = null;
if (pointerRafRef.current) {
cancelAnimationFrame(pointerRafRef.current);
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)
@@ -364,9 +470,20 @@ function ToolWindowMedia({ item, isHovered }: { item: ToolMediaItem; isHovered:
<div
ref={containerRef}
onPointerEnter={handlePointerEnter}
onPointerDown={handlePointerDown}
onPointerMove={handlePointerMove}
onPointerUp={handlePointerUp}
onPointerCancel={handlePointerUp}
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) */}
<img
@@ -391,25 +508,23 @@ function ToolWindowMedia({ item, isHovered }: { item: ToolMediaItem; isHovered:
{/* Glowing Slider Divider Line (Direct GPU transform & position) */}
<div
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%' }}
>
{/* Circular Grab Handle with Before/After Arrow Cue */}
<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">
{/* 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-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>
{/* Badges with Smooth GPU Opacity Transition (No DOM mounting/unmounting) */}
{/* Badges with Smooth Contrast */}
<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)] ${
isHovered ? 'opacity-100' : 'opacity-0'
}`}
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"
>
<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
</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
</span>
</div>
+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)' }}
+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');
});
});