This commit is contained in:
2026-05-25 17:08:18 +08:00
parent df501f6151
commit f1259b71b5
9178 changed files with 1626125 additions and 0 deletions
@@ -0,0 +1,28 @@
/// <reference types="react" />
export type TransformType = {
x: number;
y: number;
rotate: number;
scale: number;
flipX: boolean;
flipY: boolean;
};
export type TransformAction = 'flipY' | 'flipX' | 'rotateLeft' | 'rotateRight' | 'zoomIn' | 'zoomOut' | 'close' | 'prev' | 'next' | 'wheel' | 'doubleClick' | 'move' | 'dragRebound' | 'touchZoom' | 'reset';
export type UpdateTransformFunc = (newTransform: Partial<TransformType>, action: TransformAction) => void;
export type DispatchZoomChangeFunc = (ratio: number, action: TransformAction, centerX?: number, centerY?: number, isTouch?: boolean) => void;
export default function useImageTransform(imgRef: React.MutableRefObject<HTMLImageElement>, minScale: number, maxScale: number, onTransform: (info: {
transform: TransformType;
action: TransformAction;
}) => void): {
transform: {
x: number;
y: number;
rotate: number;
scale: number;
flipX: boolean;
flipY: boolean;
};
resetTransform: (action: TransformAction) => void;
updateTransform: UpdateTransformFunc;
dispatchZoomChange: DispatchZoomChangeFunc;
};
@@ -0,0 +1,118 @@
import { getClientSize } from "../util";
import isEqual from "@rc-component/util/es/isEqual";
import raf from "@rc-component/util/es/raf";
import { useRef, useState } from 'react';
const initialTransform = {
x: 0,
y: 0,
rotate: 0,
scale: 1,
flipX: false,
flipY: false
};
export default function useImageTransform(imgRef, minScale, maxScale, onTransform) {
const frame = useRef(null);
const queue = useRef([]);
const [transform, setTransform] = useState(initialTransform);
const resetTransform = action => {
setTransform(initialTransform);
if (!isEqual(initialTransform, transform)) {
onTransform?.({
transform: initialTransform,
action
});
}
};
/** Direct update transform */
const updateTransform = (newTransform, action) => {
if (frame.current === null) {
queue.current = [];
frame.current = raf(() => {
setTransform(preState => {
let memoState = preState;
queue.current.forEach(queueState => {
memoState = {
...memoState,
...queueState
};
});
frame.current = null;
onTransform?.({
transform: memoState,
action
});
return memoState;
});
});
}
queue.current.push({
...transform,
...newTransform
});
};
/** Scale according to the position of centerX and centerY */
const dispatchZoomChange = (ratio, action, centerX, centerY, isTouch) => {
const {
width,
height,
offsetWidth,
offsetHeight,
offsetLeft,
offsetTop
} = imgRef.current;
let newRatio = ratio;
let newScale = transform.scale * ratio;
if (newScale > maxScale) {
newScale = maxScale;
newRatio = maxScale / transform.scale;
} else if (newScale < minScale) {
// For mobile interactions, allow scaling down to the minimum scale.
newScale = isTouch ? newScale : minScale;
newRatio = newScale / transform.scale;
}
/** Default center point scaling */
const mergedCenterX = centerX ?? innerWidth / 2;
const mergedCenterY = centerY ?? innerHeight / 2;
const diffRatio = newRatio - 1;
/** Deviation calculated from image size */
const diffImgX = diffRatio * width * 0.5;
const diffImgY = diffRatio * height * 0.5;
/** The difference between the click position and the edge of the document */
const diffOffsetLeft = diffRatio * (mergedCenterX - transform.x - offsetLeft);
const diffOffsetTop = diffRatio * (mergedCenterY - transform.y - offsetTop);
/** Final positioning */
let newX = transform.x - (diffOffsetLeft - diffImgX);
let newY = transform.y - (diffOffsetTop - diffImgY);
/**
* When zooming the image
* When the image size is smaller than the width and height of the window, the position is initialized
*/
if (ratio < 1 && newScale === 1) {
const mergedWidth = offsetWidth * newScale;
const mergedHeight = offsetHeight * newScale;
const {
width: clientWidth,
height: clientHeight
} = getClientSize();
if (mergedWidth <= clientWidth && mergedHeight <= clientHeight) {
newX = 0;
newY = 0;
}
}
updateTransform({
x: newX,
y: newY,
scale: newScale
}, action);
};
return {
transform,
resetTransform,
updateTransform,
dispatchZoomChange
};
}
@@ -0,0 +1,9 @@
import type React from 'react';
import type { DispatchZoomChangeFunc, TransformType, UpdateTransformFunc } from './useImageTransform';
export default function useMouseEvent(imgRef: React.MutableRefObject<HTMLImageElement>, movable: boolean, open: boolean, scaleStep: number, transform: TransformType, updateTransform: UpdateTransformFunc, dispatchZoomChange: DispatchZoomChangeFunc): {
isMoving: boolean;
onMouseDown: React.MouseEventHandler<HTMLDivElement>;
onMouseMove: (event: MouseEvent) => void;
onMouseUp: () => void;
onWheel: (event: React.WheelEvent<HTMLImageElement>) => void;
};
@@ -0,0 +1,116 @@
import { warning } from "@rc-component/util/es/warning";
import { useEffect, useRef, useState } from 'react';
import getFixScaleEleTransPosition from "../getFixScaleEleTransPosition";
import { BASE_SCALE_RATIO, WHEEL_MAX_SCALE_RATIO } from "../previewConfig";
export default function useMouseEvent(imgRef, movable, open, scaleStep, transform, updateTransform, dispatchZoomChange) {
const {
rotate,
scale,
x,
y
} = transform;
const [isMoving, setMoving] = useState(false);
const startPositionInfo = useRef({
diffX: 0,
diffY: 0,
transformX: 0,
transformY: 0
});
const onMouseDown = event => {
// Only allow main button
if (!movable || event.button !== 0) return;
event.preventDefault();
event.stopPropagation();
startPositionInfo.current = {
diffX: event.pageX - x,
diffY: event.pageY - y,
transformX: x,
transformY: y
};
setMoving(true);
};
const onMouseMove = event => {
if (open && isMoving) {
updateTransform({
x: event.pageX - startPositionInfo.current.diffX,
y: event.pageY - startPositionInfo.current.diffY
}, 'move');
}
};
const onMouseUp = () => {
if (open && isMoving) {
setMoving(false);
/** No need to restore the position when the picture is not moved, So as not to interfere with the click */
const {
transformX,
transformY
} = startPositionInfo.current;
const hasChangedPosition = x !== transformX && y !== transformY;
if (!hasChangedPosition) return;
const width = imgRef.current.offsetWidth * scale;
const height = imgRef.current.offsetHeight * scale;
// eslint-disable-next-line @typescript-eslint/no-shadow
const {
left,
top
} = imgRef.current.getBoundingClientRect();
const isRotate = rotate % 180 !== 0;
const fixState = getFixScaleEleTransPosition(isRotate ? height : width, isRotate ? width : height, left, top);
if (fixState) {
updateTransform({
...fixState
}, 'dragRebound');
}
}
};
const onWheel = event => {
if (!open || event.deltaY == 0) return;
// Scale ratio depends on the deltaY size
const scaleRatio = Math.abs(event.deltaY / 100);
// Limit the maximum scale ratio
const mergedScaleRatio = Math.min(scaleRatio, WHEEL_MAX_SCALE_RATIO);
// Scale the ratio each time
let ratio = BASE_SCALE_RATIO + mergedScaleRatio * scaleStep;
if (event.deltaY > 0) {
ratio = BASE_SCALE_RATIO / ratio;
}
dispatchZoomChange(ratio, 'wheel', event.clientX, event.clientY);
};
useEffect(() => {
if (movable) {
window.addEventListener('mouseup', onMouseUp, false);
window.addEventListener('mousemove', onMouseMove, false);
try {
// Resolve if in iframe lost event
/* istanbul ignore next */
if (window.top !== window.self) {
window.top.addEventListener('mouseup', onMouseUp, false);
window.top.addEventListener('mousemove', onMouseMove, false);
}
} catch (error) {
/* istanbul ignore next */
warning(false, `[rc-image] ${error}`);
}
}
return () => {
window.removeEventListener('mouseup', onMouseUp);
window.removeEventListener('mousemove', onMouseMove);
/* istanbul ignore next */
try {
window.top?.removeEventListener('mouseup', onMouseUp);
window.top?.removeEventListener('mousemove', onMouseMove);
} catch (error) {
// Do nothing
}
};
}, [open, isMoving, x, y, rotate, movable]);
return {
isMoving,
onMouseDown,
onMouseMove,
onMouseUp,
onWheel
};
}
@@ -0,0 +1,7 @@
import type { PreviewGroupProps } from '../PreviewGroup';
import type { InternalItem, RegisterImage } from '../interface';
export type Items = Omit<InternalItem, 'canPreview'>[];
/**
* Merge props provided `items` or context collected images
*/
export default function usePreviewItems(items?: PreviewGroupProps['items']): [items: Items, registerImage: RegisterImage, fromItems: boolean];
@@ -0,0 +1,65 @@
import * as React from 'react';
import { COMMON_PROPS } from "../common";
/**
* Merge props provided `items` or context collected images
*/
export default function usePreviewItems(items) {
// Context collection image data
const [images, setImages] = React.useState({});
const registerImage = React.useCallback((id, data) => {
setImages(imgs => ({
...imgs,
[id]: data
}));
return () => {
setImages(imgs => {
const cloneImgs = {
...imgs
};
delete cloneImgs[id];
return cloneImgs;
});
};
}, []);
// items
const mergedItems = React.useMemo(() => {
// use `items` first
if (items) {
return items.map(item => {
if (typeof item === 'string') {
return {
data: {
src: item
}
};
}
const data = {};
Object.keys(item).forEach(key => {
if (['src', ...COMMON_PROPS].includes(key)) {
data[key] = item[key];
}
});
return {
data
};
});
}
// use registered images secondly
return Object.keys(images).reduce((total, id) => {
const {
canPreview,
data
} = images[id];
if (canPreview) {
total.push({
data,
id
});
}
return total;
}, []);
}, [items, images]);
return [mergedItems, registerImage, !!items];
}
@@ -0,0 +1,2 @@
import type { ImageElementProps } from '../interface';
export default function useRegisterImage(canPreview: boolean, data: ImageElementProps): string;
@@ -0,0 +1,29 @@
import * as React from 'react';
import { PreviewGroupContext } from "../context";
let uid = 0;
export default function useRegisterImage(canPreview, data) {
const [id] = React.useState(() => {
uid += 1;
return String(uid);
});
const groupContext = React.useContext(PreviewGroupContext);
const registerData = {
data,
canPreview
};
// Keep order start
// Resolve https://github.com/ant-design/ant-design/issues/28881
// Only need unRegister when component unMount
React.useEffect(() => {
if (groupContext) {
return groupContext.register(id, registerData);
}
}, []);
React.useEffect(() => {
if (groupContext) {
groupContext.register(id, registerData);
}
}, [canPreview, data]);
return id;
}
@@ -0,0 +1,13 @@
type ImageStatus = 'normal' | 'error' | 'loading';
export default function useStatus({ src, isCustomPlaceholder, fallback, }: {
src: string;
isCustomPlaceholder?: boolean;
fallback?: string;
}): readonly [(img?: HTMLImageElement) => void, {
src: string;
onLoad?: undefined;
} | {
onLoad: () => void;
src: string;
}, ImageStatus];
export {};
+50
View File
@@ -0,0 +1,50 @@
import { useEffect, useRef, useState } from 'react';
import { isImageValid } from "../util";
export default function useStatus({
src,
isCustomPlaceholder,
fallback
}) {
const [status, setStatus] = useState(isCustomPlaceholder ? 'loading' : 'normal');
const isLoaded = useRef(false);
const isError = status === 'error';
// https://github.com/react-component/image/pull/187
useEffect(() => {
let isCurrentSrc = true;
isImageValid(src).then(isValid => {
// https://github.com/ant-design/ant-design/issues/44948
// If src changes, the previous setStatus should not be triggered
if (!isValid && isCurrentSrc) {
setStatus('error');
}
});
return () => {
isCurrentSrc = false;
};
}, [src]);
useEffect(() => {
if (isCustomPlaceholder && !isLoaded.current) {
setStatus('loading');
} else if (isError) {
setStatus('normal');
}
}, [src]);
const onLoad = () => {
setStatus('normal');
};
const getImgRef = img => {
isLoaded.current = false;
if (status === 'loading' && img?.complete && (img.naturalWidth || img.naturalHeight)) {
isLoaded.current = true;
onLoad();
}
};
const srcAndOnload = isError && fallback ? {
src: fallback
} : {
onLoad,
src
};
return [getImgRef, srcAndOnload, status];
}
@@ -0,0 +1,8 @@
import type React from 'react';
import type { DispatchZoomChangeFunc, TransformType, UpdateTransformFunc } from './useImageTransform';
export default function useTouchEvent(imgRef: React.MutableRefObject<HTMLImageElement>, movable: boolean, open: boolean, minScale: number, transform: TransformType, updateTransform: UpdateTransformFunc, dispatchZoomChange: DispatchZoomChangeFunc): {
isTouching: boolean;
onTouchStart: (event: React.TouchEvent<HTMLImageElement>) => void;
onTouchMove: (event: React.TouchEvent<HTMLImageElement>) => void;
onTouchEnd: () => void;
};
@@ -0,0 +1,170 @@
import { useEffect, useRef, useState } from 'react';
import getFixScaleEleTransPosition from "../getFixScaleEleTransPosition";
function getDistance(a, b) {
const x = a.x - b.x;
const y = a.y - b.y;
return Math.hypot(x, y);
}
function getCenter(oldPoint1, oldPoint2, newPoint1, newPoint2) {
// Calculate the distance each point has moved
const distance1 = getDistance(oldPoint1, newPoint1);
const distance2 = getDistance(oldPoint2, newPoint2);
// If both distances are 0, return the original points
if (distance1 === 0 && distance2 === 0) {
return [oldPoint1.x, oldPoint1.y];
}
// Calculate the ratio of the distances
const ratio = distance1 / (distance1 + distance2);
// Calculate the new center point based on the ratio
const x = oldPoint1.x + ratio * (oldPoint2.x - oldPoint1.x);
const y = oldPoint1.y + ratio * (oldPoint2.y - oldPoint1.y);
return [x, y];
}
export default function useTouchEvent(imgRef, movable, open, minScale, transform, updateTransform, dispatchZoomChange) {
const {
rotate,
scale,
x,
y
} = transform;
const [isTouching, setIsTouching] = useState(false);
const touchPointInfo = useRef({
point1: {
x: 0,
y: 0
},
point2: {
x: 0,
y: 0
},
eventType: 'none'
});
const updateTouchPointInfo = values => {
touchPointInfo.current = {
...touchPointInfo.current,
...values
};
};
const onTouchStart = event => {
if (!movable) return;
event.stopPropagation();
setIsTouching(true);
const {
touches = []
} = event;
if (touches.length > 1) {
// touch zoom
updateTouchPointInfo({
point1: {
x: touches[0].clientX,
y: touches[0].clientY
},
point2: {
x: touches[1].clientX,
y: touches[1].clientY
},
eventType: 'touchZoom'
});
} else {
// touch move
updateTouchPointInfo({
point1: {
x: touches[0].clientX - x,
y: touches[0].clientY - y
},
eventType: 'move'
});
}
};
const onTouchMove = event => {
const {
touches = []
} = event;
const {
point1,
point2,
eventType
} = touchPointInfo.current;
if (touches.length > 1 && eventType === 'touchZoom') {
// touch zoom
const newPoint1 = {
x: touches[0].clientX,
y: touches[0].clientY
};
const newPoint2 = {
x: touches[1].clientX,
y: touches[1].clientY
};
const [centerX, centerY] = getCenter(point1, point2, newPoint1, newPoint2);
const ratio = getDistance(newPoint1, newPoint2) / getDistance(point1, point2);
dispatchZoomChange(ratio, 'touchZoom', centerX, centerY, true);
updateTouchPointInfo({
point1: newPoint1,
point2: newPoint2,
eventType: 'touchZoom'
});
} else if (eventType === 'move') {
// touch move
updateTransform({
x: touches[0].clientX - point1.x,
y: touches[0].clientY - point1.y
}, 'move');
updateTouchPointInfo({
eventType: 'move'
});
}
};
const onTouchEnd = () => {
if (!open) return;
if (isTouching) {
setIsTouching(false);
}
updateTouchPointInfo({
eventType: 'none'
});
if (minScale > scale) {
/** When the scaling ratio is less than the minimum scaling ratio, reset the scaling ratio */
return updateTransform({
x: 0,
y: 0,
scale: minScale
}, 'touchZoom');
}
const width = imgRef.current.offsetWidth * scale;
const height = imgRef.current.offsetHeight * scale;
// eslint-disable-next-line @typescript-eslint/no-shadow
const {
left,
top
} = imgRef.current.getBoundingClientRect();
const isRotate = rotate % 180 !== 0;
const fixState = getFixScaleEleTransPosition(isRotate ? height : width, isRotate ? width : height, left, top);
if (fixState) {
updateTransform({
...fixState
}, 'dragRebound');
}
};
useEffect(() => {
const preventDefault = e => {
e.preventDefault();
};
if (open && movable) {
window.addEventListener('touchmove', preventDefault, {
passive: false
});
}
return () => {
window.removeEventListener('touchmove', preventDefault);
};
}, [open, movable]);
return {
isTouching,
onTouchStart,
onTouchMove,
onTouchEnd
};
}