previewzoomoverlay

This commit is contained in:
2025-10-26 21:01:48 +01:00
parent 518b79bec6
commit 40e45f3a01
4 changed files with 521 additions and 498 deletions
+388
View File
@@ -0,0 +1,388 @@
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { createPortal } from 'react-dom';
import { ArrowLeftIcon, ArrowRightIcon } from '../ui/icons';
const noop = () => {};
const clamp = (value, min, max) => {
if (value < min) return min;
if (value > max) return max;
return value;
};
const ensureDocumentRoot = () => {
if (typeof document === 'undefined') {
return null;
}
return document.body;
};
const PreviewZoomOverlay = ({ open = false, display = null, onClose = noop }) => {
const portalTarget = ensureDocumentRoot();
const isActive = Boolean(open && display?.url && portalTarget);
const stageRef = useRef(null);
const imageMetricsRef = useRef({ naturalWidth: 0, naturalHeight: 0 });
const dragRef = useRef(null);
const skipClickRef = useRef(false);
const [isNativeScale, setIsNativeScale] = useState(false);
const [pan, setPan] = useState({ x: 0, y: 0 });
const [isDragging, setIsDragging] = useState(false);
const resetInteraction = useCallback(() => {
setIsNativeScale(false);
setPan({ x: 0, y: 0 });
setIsDragging(false);
dragRef.current = null;
skipClickRef.current = false;
imageMetricsRef.current = { naturalWidth: 0, naturalHeight: 0 };
}, []);
useEffect(() => {
if (!open) {
resetInteraction();
}
}, [open, resetInteraction]);
useEffect(() => {
if (!isActive) {
return;
}
resetInteraction();
}, [isActive, display?.url, resetInteraction]);
const clampPan = useCallback(
(x, y) => {
const stage = stageRef.current;
const { naturalWidth, naturalHeight } = imageMetricsRef.current;
if (!stage || !naturalWidth || !naturalHeight) {
return { x: 0, y: 0 };
}
const stageRect = stage.getBoundingClientRect();
if (stageRect.width <= 0 || stageRect.height <= 0) {
return { x: 0, y: 0 };
}
const imageWidth = isNativeScale
? naturalWidth
: Math.min(naturalWidth, stageRect.width);
const imageHeight = isNativeScale
? naturalHeight
: Math.min(naturalHeight, stageRect.height);
const limitX = Math.max(0, (imageWidth - stageRect.width) / 2);
const limitY = Math.max(0, (imageHeight - stageRect.height) / 2);
return {
x: clamp(x, -limitX, limitX),
y: clamp(y, -limitY, limitY),
};
},
[isNativeScale],
);
const handleBackdropClick = useCallback(() => {
onClose();
}, [onClose]);
const handleStageClick = useCallback((event) => {
event.stopPropagation();
}, []);
const handleImageLoad = useCallback(
(event) => {
imageMetricsRef.current = {
naturalWidth: event.currentTarget.naturalWidth || 0,
naturalHeight: event.currentTarget.naturalHeight || 0,
};
setPan((current) => {
const clamped = clampPan(current.x, current.y);
if (clamped.x === current.x && clamped.y === current.y) {
return current;
}
return clamped;
});
},
[clampPan],
);
const handleImageClick = useCallback(
(event) => {
event.stopPropagation();
if (skipClickRef.current) {
skipClickRef.current = false;
return;
}
if (!isNativeScale) {
const stage = stageRef.current;
const { naturalWidth, naturalHeight } = imageMetricsRef.current;
if (stage && naturalWidth && naturalHeight) {
const stageRect = stage.getBoundingClientRect();
const imageRect = event.currentTarget.getBoundingClientRect();
const clickX = event.clientX - imageRect.left;
const clickY = event.clientY - imageRect.top;
const ratioX = imageRect.width ? clickX / imageRect.width : 0.5;
const ratioY = imageRect.height ? clickY / imageRect.height : 0.5;
const focusX = naturalWidth * ratioX;
const focusY = naturalHeight * ratioY;
const halfWidth = naturalWidth / 2;
const halfHeight = naturalHeight / 2;
const limitX = Math.max(0, (naturalWidth - stageRect.width) / 2);
const limitY = Math.max(0, (naturalHeight - stageRect.height) / 2);
const targetPanX = clamp(-(focusX - halfWidth), -limitX, limitX);
const targetPanY = clamp(-(focusY - halfHeight), -limitY, limitY);
setPan({ x: targetPanX, y: targetPanY });
} else {
setPan({ x: 0, y: 0 });
}
setIsNativeScale(true);
} else {
setIsNativeScale(false);
}
},
[isNativeScale],
);
const endDrag = useCallback(() => {
dragRef.current = null;
setIsDragging(false);
}, []);
const handlePointerDown = useCallback(
(event) => {
if (!isNativeScale || event.button !== 0) {
return;
}
event.preventDefault();
skipClickRef.current = false;
dragRef.current = {
pointerId: event.pointerId,
originX: pan.x,
originY: pan.y,
startX: event.clientX,
startY: event.clientY,
moved: false,
};
event.currentTarget.setPointerCapture(event.pointerId);
},
[isNativeScale, pan.x, pan.y],
);
const handlePointerMove = useCallback(
(event) => {
const drag = dragRef.current;
if (!drag || drag.pointerId !== event.pointerId) {
return;
}
const deltaX = event.clientX - drag.startX;
const deltaY = event.clientY - drag.startY;
if (!drag.moved && (Math.abs(deltaX) > 2 || Math.abs(deltaY) > 2)) {
drag.moved = true;
setIsDragging(true);
}
if (drag.moved) {
const clamped = clampPan(drag.originX + deltaX, drag.originY + deltaY);
setPan((current) =>
current.x === clamped.x && current.y === clamped.y ? current : clamped,
);
}
},
[clampPan],
);
const handlePointerUp = useCallback(
(event) => {
const drag = dragRef.current;
if (!drag || drag.pointerId !== event.pointerId) {
return;
}
event.currentTarget.releasePointerCapture(event.pointerId);
skipClickRef.current = Boolean(drag.moved);
endDrag();
},
[endDrag],
);
const handlePointerCancel = useCallback(
(event) => {
const drag = dragRef.current;
if (!drag || drag.pointerId !== event.pointerId) {
return;
}
event.currentTarget.releasePointerCapture(event.pointerId);
skipClickRef.current = true;
endDrag();
},
[endDrag],
);
const handleWheel = useCallback(
(event) => {
if (!isNativeScale) {
return;
}
const deltaX = Number.isFinite(event.deltaX) ? event.deltaX : 0;
const deltaY = Number.isFinite(event.deltaY) ? event.deltaY : 0;
if (!deltaX && !deltaY) {
return;
}
let updated = false;
setPan((current) => {
const clamped = clampPan(current.x - deltaX, current.y - deltaY);
if (clamped.x === current.x && clamped.y === current.y) {
return current;
}
updated = true;
return clamped;
});
if (updated) {
event.preventDefault();
event.stopPropagation();
}
},
[isNativeScale, clampPan],
);
useEffect(() => {
if (!isActive) {
return undefined;
}
const handleKeyDown = (event) => {
if (event.key === 'Escape') {
event.preventDefault();
event.stopPropagation();
onClose();
return;
}
if (event.key === 'ArrowLeft') {
event.preventDefault();
event.stopPropagation();
if (display?.canGoPrev && display?.goPrev) {
display.goPrev();
}
return;
}
if (event.key === 'ArrowRight') {
event.preventDefault();
event.stopPropagation();
if (display?.canGoNext && display?.goNext) {
display.goNext();
}
}
};
window.addEventListener('keydown', handleKeyDown);
return () => window.removeEventListener('keydown', handleKeyDown);
}, [isActive, display, onClose]);
const imageStyle = useMemo(() => {
if (!isNativeScale) {
return {
cursor: 'zoom-in',
transform: 'none',
maxWidth: '95vw',
maxHeight: '95vh',
};
}
const { naturalWidth, naturalHeight } = imageMetricsRef.current;
return {
cursor: isDragging ? 'grabbing' : 'grab',
width: naturalWidth ? `${naturalWidth}px` : 'auto',
height: naturalHeight ? `${naturalHeight}px` : 'auto',
maxWidth: 'none',
maxHeight: 'none',
transform: `translate3d(${pan.x}px, ${pan.y}px, 0)`,
};
}, [isNativeScale, pan.x, pan.y, isDragging]);
const stageClassName = useMemo(
() =>
[
'preview-zoom__stage',
isNativeScale ? 'preview-zoom__stage--native' : '',
isDragging ? 'preview-zoom__stage--dragging' : '',
]
.filter(Boolean)
.join(' '),
[isNativeScale, isDragging],
);
if (!isActive) {
return null;
}
return createPortal(
(
<div
className="preview-zoom-backdrop"
role="dialog"
aria-modal="true"
aria-label="Enlarged document preview"
onClick={handleBackdropClick}
>
<div
ref={stageRef}
className={stageClassName}
onClick={handleStageClick}
onWheel={handleWheel}
>
<img
src={display?.url}
alt={display?.alt || 'Document preview'}
className="preview-zoom__image"
style={imageStyle}
onLoad={handleImageLoad}
onClick={handleImageClick}
onPointerDown={handlePointerDown}
onPointerMove={handlePointerMove}
onPointerUp={handlePointerUp}
onPointerCancel={handlePointerCancel}
draggable={false}
/>
<div className="preview-zoom__nav">
<button
type="button"
className="preview-zoom__nav-button"
onClick={(event) => {
event.stopPropagation();
if (display?.goPrev) {
display.goPrev();
}
}}
aria-label="Previous preview"
disabled={!display?.canGoPrev}
>
<ArrowLeftIcon />
</button>
<button
type="button"
className="preview-zoom__nav-button"
onClick={(event) => {
event.stopPropagation();
if (display?.goNext) {
display.goNext();
}
}}
aria-label="Next preview"
disabled={!display?.canGoNext}
>
<ArrowRightIcon />
</button>
</div>
</div>
</div>
),
portalTarget,
);
};
export default PreviewZoomOverlay;