fix(image-zoom): refine gesture handling and zoom limits

- Introduced minimum and maximum scale limits for zoom functionality to prevent excessive scaling.
- Enhanced gesture state management for pinch and drag interactions, improving user experience during zoom.
- Updated event handling to ensure smoother transitions between single and multi-touch interactions, including better tap detection logic.
- Adjusted logic to maintain consistent pan behavior during zoom adjustments, ensuring a more intuitive interaction.
This commit is contained in:
Xin
2025-10-05 13:27:31 +01:00
parent 1c13e24535
commit 26569738f7

View File

@@ -47,16 +47,23 @@
let pinchEndTimer = null; let pinchEndTimer = null;
const pointers = new Map(); // pointerId -> {x, y, startX, startY} const pointers = new Map(); // pointerId -> {x, y, startX, startY}
const SCALE_MIN = 1;
const SCALE_MAX = 5;
let gestureState = { let gestureState = {
scale: 1, scale: 1,
panX: 0, panX: 0,
panY: 0, panY: 0,
lastScale: 1, startScale: 1,
lastPanX: 0, startPanX: 0,
lastPanY: 0, startPanY: 0,
initialDistance: 0, initialDistance: 0,
midpointX: 0, initialMidpointX: 0,
midpointY: 0 initialMidpointY: 0,
dragStartX: 0,
dragStartY: 0,
dragPanX: 0,
dragPanY: 0
}; };
// Utility functions // Utility functions
@@ -91,37 +98,54 @@
function onPointerDown(e) { function onPointerDown(e) {
e.preventDefault(); e.preventDefault();
pointers.set(e.pointerId, { if (typeof overlay.setPointerCapture === 'function') {
try {
overlay.setPointerCapture(e.pointerId);
} catch (err) {
// ignore pointer capture failures (e.g. Safari)
}
}
const pointerData = {
x: e.clientX, x: e.clientX,
y: e.clientY, y: e.clientY,
startX: e.clientX, startX: e.clientX,
startY: e.clientY startY: e.clientY
}); };
pointers.set(e.pointerId, pointerData);
if (pointers.size === 1) { if (pointers.size === 1) {
isDragging = false; isDragging = false;
setInteracting(true); if (gestureState.scale > SCALE_MIN) {
gestureState.lastPanX = gestureState.panX; setInteracting(true);
gestureState.lastPanY = gestureState.panY; }
// Set drag baseline so a single finger can pan when zoomed
gestureState.dragStartX = e.clientX;
gestureState.dragStartY = e.clientY;
gestureState.dragPanX = gestureState.panX;
gestureState.dragPanY = gestureState.panY;
// Tap detection setup
tapCandidate = true; tapCandidate = true;
tapStartX = e.clientX; tapStartX = e.clientX;
tapStartY = e.clientY; tapStartY = e.clientY;
tapStartTime = (typeof performance !== 'undefined' ? performance.now() : Date.now()); tapStartTime = (typeof performance !== 'undefined' ? performance.now() : Date.now());
} else if (pointers.size === 2) { } else if (pointers.size === 2) {
// Two touches - start pinch
isDragging = false;
isPinching = true; isPinching = true;
isDragging = false;
setInteracting(true); setInteracting(true);
tapCandidate = false;
const pts = Array.from(pointers.values()); const pts = Array.from(pointers.values());
gestureState.initialDistance = getDistance(pts[0], pts[1]); gestureState.initialDistance = getDistance(pts[0], pts[1]) || 1;
gestureState.lastScale = gestureState.scale; gestureState.startScale = gestureState.scale;
gestureState.startPanX = gestureState.panX;
gestureState.startPanY = gestureState.panY;
const midpoint = getMidpoint(pts[0], pts[1]); const midpoint = getMidpoint(pts[0], pts[1]);
gestureState.midpointX = midpoint.x; gestureState.initialMidpointX = midpoint.x;
gestureState.midpointY = midpoint.y; gestureState.initialMidpointY = midpoint.y;
if (pinchEndTimer) { if (pinchEndTimer) {
clearTimeout(pinchEndTimer); clearTimeout(pinchEndTimer);
@@ -131,77 +155,132 @@
} }
function onPointerMove(e) { function onPointerMove(e) {
if (!pointers.has(e.pointerId)) return; const pointer = pointers.get(e.pointerId);
if (!pointer) return;
e.preventDefault(); e.preventDefault();
const pointer = pointers.get(e.pointerId);
pointer.x = e.clientX; pointer.x = e.clientX;
pointer.y = e.clientY; pointer.y = e.clientY;
if (isPinching && pointers.size === 2) { if (pointers.size === 2) {
// Handle pinch zoom
const pts = Array.from(pointers.values()); const pts = Array.from(pointers.values());
const currentDistance = getDistance(pts[0], pts[1]); const currentDistance = getDistance(pts[0], pts[1]);
const scaleDelta = currentDistance / gestureState.initialDistance; if (!currentDistance) return;
// Calculate new scale with limits - minimum is 1 (original zoom level) const currentMidpoint = getMidpoint(pts[0], pts[1]);
const newScale = Math.max(1, Math.min(5, gestureState.lastScale * scaleDelta));
// Only update pan if scale is actually changing const distanceRatio = currentDistance / (gestureState.initialDistance || currentDistance);
// This prevents drift when pinching at minimum scale let nextScale = gestureState.startScale * distanceRatio;
if (Math.abs(newScale - gestureState.scale) > 0.001) { nextScale = Math.max(SCALE_MIN, Math.min(SCALE_MAX, nextScale));
gestureState.scale = newScale;
// Calculate pan based on pinch center movement const totalStart = baseScale * gestureState.startScale;
const currentMidpoint = getMidpoint(pts[0], pts[1]); const totalNext = baseScale * nextScale;
const panDeltaX = currentMidpoint.x - gestureState.midpointX;
const panDeltaY = currentMidpoint.y - gestureState.midpointY;
gestureState.panX = gestureState.lastPanX + panDeltaX; let nextPanX = gestureState.panX;
gestureState.panY = gestureState.lastPanY + panDeltaY; let nextPanY = gestureState.panY;
if (totalStart > 0) {
const startOffsetX = gestureState.initialMidpointX - final.cx - gestureState.startPanX;
const startOffsetY = gestureState.initialMidpointY - final.cy - gestureState.startPanY;
const currentOffsetX = currentMidpoint.x - final.cx;
const currentOffsetY = currentMidpoint.y - final.cy;
const ratio = totalNext / totalStart;
nextPanX = currentOffsetX - ratio * startOffsetX;
nextPanY = currentOffsetY - ratio * startOffsetY;
} }
// Any multi-touch movement cancels tap gestureState.scale = nextScale;
gestureState.panX = nextPanX;
gestureState.panY = nextPanY;
tapCandidate = false; tapCandidate = false;
applyTransform(); applyTransform();
} else if (pointers.size === 1) { } else if (pointers.size === 1) {
// Single pointer: no drag; only cancel tap if large move const moveX = pointer.x - gestureState.dragStartX;
const moveThreshold = 10; const moveY = pointer.y - gestureState.dragStartY;
if (Math.abs(pointer.x - tapStartX) > moveThreshold || Math.abs(pointer.y - tapStartY) > moveThreshold) { const dragThreshold = 6;
tapCandidate = false;
if (!isDragging) {
const distanceSq = moveX * moveX + moveY * moveY;
if (gestureState.scale > SCALE_MIN && distanceSq > dragThreshold * dragThreshold) {
isDragging = true;
tapCandidate = false;
setInteracting(true);
gestureState.dragPanX = gestureState.panX;
gestureState.dragPanY = gestureState.panY;
}
}
if (isDragging) {
gestureState.panX = gestureState.dragPanX + moveX;
gestureState.panY = gestureState.dragPanY + moveY;
applyTransform();
} else {
const cancelTapThreshold = 10;
if (
Math.abs(pointer.x - tapStartX) > cancelTapThreshold ||
Math.abs(pointer.y - tapStartY) > cancelTapThreshold
) {
tapCandidate = false;
}
} }
} }
} }
function onPointerUp(e) { function onPointerUp(e) {
if (typeof overlay.releasePointerCapture === 'function') {
try {
overlay.releasePointerCapture(e.pointerId);
} catch (err) {
// ignore release failures
}
}
pointers.delete(e.pointerId); pointers.delete(e.pointerId);
if (pointers.size === 0) { if (pointers.size === 0) {
// All pointers released
isDragging = false;
setInteracting(false);
// Tap-to-close when there was minimal movement and short duration
const now = (typeof performance !== 'undefined' ? performance.now() : Date.now()); const now = (typeof performance !== 'undefined' ? performance.now() : Date.now());
const duration = now - tapStartTime; const duration = now - tapStartTime;
if (tapCandidate && !isPinching && duration < 300) { const shouldClose = tapCandidate && !isPinching && !isDragging && duration < 300;
if (shouldClose) {
close(); close();
} }
tapCandidate = false; tapCandidate = false;
isDragging = false;
if (isPinching) { if (isPinching) {
pinchEndTimer = setTimeout(() => { pinchEndTimer = setTimeout(() => {
isPinching = false; isPinching = false;
}, 300); }, 180);
} else {
isPinching = false;
} }
gestureState.startScale = gestureState.scale;
gestureState.startPanX = gestureState.panX;
gestureState.startPanY = gestureState.panY;
setTimeout(() => setInteracting(false), 120);
} else if (pointers.size === 1) { } else if (pointers.size === 1) {
// Going from pinch to single touch — keep dragging disabled
isPinching = false; isPinching = false;
isDragging = false; isDragging = false;
const remaining = Array.from(pointers.values())[0]; const remaining = Array.from(pointers.values())[0];
gestureState.lastPanX = gestureState.panX;
gestureState.lastPanY = gestureState.panY;
remaining.startX = remaining.x; remaining.startX = remaining.x;
remaining.startY = remaining.y; remaining.startY = remaining.y;
gestureState.dragStartX = remaining.x;
gestureState.dragStartY = remaining.y;
gestureState.dragPanX = gestureState.panX;
gestureState.dragPanY = gestureState.panY;
if (gestureState.scale <= SCALE_MIN) {
setTimeout(() => setInteracting(false), 120);
}
} }
} }
@@ -227,24 +306,26 @@
const prevScale = gestureState.scale; const prevScale = gestureState.scale;
const unclamped = prevScale * zoomSpeed; const unclamped = prevScale * zoomSpeed;
const nextScale = Math.max(1, Math.min(5, unclamped)); const nextScale = Math.max(SCALE_MIN, Math.min(SCALE_MAX, unclamped));
// Effective scale ratio (applied), use it to anchor zoom around cursor if (Math.abs(nextScale - prevScale) > 0.0001) {
const f = prevScale === 0 ? 1 : (nextScale / prevScale); const totalPrev = baseScale * prevScale;
if (f !== 1) { const totalNext = baseScale * nextScale;
// Zoom towards mouse position
const rect = img.getBoundingClientRect();
const centerX = rect.left + rect.width / 2;
const centerY = rect.top + rect.height / 2;
const offsetX = e.clientX - centerX;
const offsetY = e.clientY - centerY;
// Adjust pan to keep cursor's point stable if (totalPrev > 0) {
gestureState.panX -= offsetX * (f - 1); const anchorOffsetX = e.clientX - final.cx;
gestureState.panY -= offsetY * (f - 1); const anchorOffsetY = e.clientY - final.cy;
const ratio = totalNext / totalPrev;
gestureState.panX = anchorOffsetX + (gestureState.panX - anchorOffsetX) * ratio;
gestureState.panY = anchorOffsetY + (gestureState.panY - anchorOffsetY) * ratio;
}
} }
gestureState.scale = nextScale; gestureState.scale = nextScale;
gestureState.startScale = nextScale;
gestureState.startPanX = gestureState.panX;
gestureState.startPanY = gestureState.panY;
setInteracting(true); setInteracting(true);
applyTransform(); applyTransform();
@@ -256,15 +337,24 @@
if (e.key === "Escape") { if (e.key === "Escape") {
close(); close();
} else if (e.key === "+" || e.key === "=") { } else if (e.key === "+" || e.key === "=") {
gestureState.scale = Math.min(5, gestureState.scale * 1.2); gestureState.scale = Math.min(SCALE_MAX, gestureState.scale * 1.2);
gestureState.startScale = gestureState.scale;
gestureState.startPanX = gestureState.panX;
gestureState.startPanY = gestureState.panY;
applyTransform(); applyTransform();
} else if (e.key === "-") { } else if (e.key === "-") {
gestureState.scale = Math.max(1, gestureState.scale / 1.2); gestureState.scale = Math.max(SCALE_MIN, gestureState.scale / 1.2);
gestureState.startScale = gestureState.scale;
gestureState.startPanX = gestureState.panX;
gestureState.startPanY = gestureState.panY;
applyTransform(); applyTransform();
} else if (e.key === "0") { } else if (e.key === "0") {
gestureState.scale = 1; gestureState.scale = 1;
gestureState.panX = 0; gestureState.panX = 0;
gestureState.panY = 0; gestureState.panY = 0;
gestureState.startScale = gestureState.scale;
gestureState.startPanX = 0;
gestureState.startPanY = 0;
applyTransform(); applyTransform();
} }
} }
@@ -295,10 +385,9 @@
img.style.left = final.cx + "px"; img.style.left = final.cx + "px";
img.style.top = final.cy + "px"; img.style.top = final.cy + "px";
const overlayScale = Math.max(1, gestureState.scale); overlay.style.transform = "none";
overlay.style.transform = overlayScale > 1 ? `scale(${overlayScale})` : "none";
const totalScale = baseScale; const totalScale = baseScale * gestureState.scale;
const transform = `translate3d(-50%, -50%, 0) translate3d(${gestureState.panX}px, ${gestureState.panY}px, 0) scale(${totalScale})`; const transform = `translate3d(-50%, -50%, 0) translate3d(${gestureState.panX}px, ${gestureState.panY}px, 0) scale(${totalScale})`;
img.style.transform = transform; img.style.transform = transform;
} }
@@ -354,6 +443,9 @@
function onResize() { function onResize() {
final = computeFinal(); final = computeFinal();
baseScale = final.scale; baseScale = final.scale;
gestureState.startScale = gestureState.scale;
gestureState.startPanX = gestureState.panX;
gestureState.startPanY = gestureState.panY;
applyTransform(); applyTransform();
} }
@@ -391,10 +483,18 @@
if (!(target instanceof HTMLImageElement)) return; if (!(target instanceof HTMLImageElement)) return;
// Only allow images inside `.content` that are NOT within a `.not-prose` block // Only allow images inside `.content` that are NOT within a `.not-prose` block
if (target.closest('.not-prose')) return; if (target.closest('.not-prose')) return;
if (target.dataset.noZoom === "" || target.dataset.noZoom === "true") return; if (target.hasAttribute('data-no-zoom')) return;
if (e.defaultPrevented) return;
if (typeof e.button === 'number' && e.button !== 0) return;
if (e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) return;
const interactiveParent = target.closest('a[href], button, [role="button"], summary, label');
if (interactiveParent && interactiveParent !== target) {
return;
}
e.preventDefault(); e.preventDefault();
e.stopPropagation();
createOverlayFromTarget(target); createOverlayFromTarget(target);
}, true); }, true);