Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: refactor PreviewGroup #48

Merged
merged 12 commits into from
Dec 16, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Binary file added examples/images/1.jpeg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added examples/images/2.jpeg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added examples/images/3.jpeg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added examples/images/disabled.jpeg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
52 changes: 9 additions & 43 deletions examples/previewgroup.tsx
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
/* eslint-disable global-require */
import * as React from 'react';
import Image from '../src';
import '../assets/index.less';
Expand All @@ -6,51 +7,16 @@ export default function PreviewGroup() {
return (
<div>
<Image.PreviewGroup>
<Image wrapperStyle={{ marginRight: 24, width: 200 }} src={require('./images/1.jpeg')} />
<Image
src="https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png"
width={200}
style={{
marginRight: 24,
}}
wrapperStyle={{ marginRight: 24, width: 200 }}
preview={false}
src={require('./images/disabled.jpeg')}
/>
<Image
src="https://gw.alipayobjects.com/mdn/rms_08e378/afts/img/A*P0S-QIRUbsUAAAAAAAAAAABkARQnAQ"
width={200}
style={{
marginRight: 24,
}}
/>
<Image
src="https://gw.alipayobjects.com/mdn/rms_08e378/afts/img/A*ngiJQaLQELEAAAAAAAAAAABkARQnAQ"
width={200}
style={{
marginRight: 24,
}}
/>
<Image
src="error1"
fallback="https://gw.alipayobjects.com/mdn/rms_08e378/afts/img/A*NZuwQp_vcIQAAAAAAAAAAABkARQnAQ"
width={200}
style={{
marginRight: 24,
}}
/>
<Image.PreviewGroup>
<Image
src="https://gw.alipayobjects.com/mdn/rms_08e378/afts/img/A*P0S-QIRUbsUAAAAAAAAAAABkARQnAQ"
width={200}
style={{
marginRight: 24,
}}
/>
<Image
src="https://gw.alipayobjects.com/mdn/rms_08e378/afts/img/A*ngiJQaLQELEAAAAAAAAAAABkARQnAQ"
width={200}
style={{
marginRight: 24,
}}
/>
</Image.PreviewGroup>
<Image wrapperStyle={{ marginRight: 24, width: 200 }} src={require('./images/2.jpeg')} />
<Image wrapperStyle={{ marginRight: 24, width: 200 }} src={require('./images/3.jpeg')} />
<Image wrapperStyle={{ marginRight: 24, width: 200 }} src='error' alt="error" />
<Image wrapperStyle={{ marginRight: 24, width: 200 }} src={require('./images/1.jpeg')} />
</Image.PreviewGroup>
</div>
);
Expand Down
61 changes: 30 additions & 31 deletions src/Image.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import * as React from 'react';
import { useState, useEffect } from 'react';
import { useState } from 'react';
import cn from 'classnames';
import { getOffset } from 'rc-util/lib/Dom/css';
import useMergedState from 'rc-util/lib/hooks/useMergedState';
Expand All @@ -14,6 +14,8 @@ export interface ImagePreviewType {
mask?: React.ReactNode;
}

let uuid = 0;

export interface ImageProps
extends Omit<React.ImgHTMLAttributes<HTMLImageElement>, 'placeholder' | 'onClick'> {
// Original
Expand Down Expand Up @@ -82,33 +84,31 @@ const ImageInternal: CompoundedComponent<ImageProps> = ({
const isError = status === 'error';
const {
isPreviewGroup,
previewUrls,
setPreviewUrls,
setCurrent,
setShowPreview: setGroupShowPreview,
setMousePosition: setGroupMousePosition,
registerImage,
} = React.useContext(context);

const groupIndexRef = React.useRef(0);
const [currentId] = React.useState<number>(() => {
uuid += 1;
return uuid;
});
const canPreview = preview && !isError;

const onLoad = () => {
setStatus('normal');
};

const onError = () => {
setStatus('error');
if (isPreviewGroup) {
previewUrls.splice(groupIndexRef.current);
setPreviewUrls(previewUrls);
}
};

const onPreview: React.MouseEventHandler<HTMLDivElement> = e => {
if (!isControlled) {
const { left, top } = getOffset(e.target);

if (isPreviewGroup) {
setCurrent(src);
setCurrent(currentId);
setGroupMousePosition({
x: left,
y: top,
Expand All @@ -130,7 +130,7 @@ const ImageInternal: CompoundedComponent<ImageProps> = ({
if (onClick) onClick(e);
};

const onPreviewClose = (e: React.SyntheticEvent<HTMLDivElement>) => {
const onPreviewClose = (e: React.SyntheticEvent<Element>) => {
e.stopPropagation();
setShowPreview(false);
if (!isControlled) {
Expand All @@ -145,22 +145,19 @@ const ImageInternal: CompoundedComponent<ImageProps> = ({
}
};

useEffect(() => {
if (isPreviewGroup && previewUrls.indexOf(src) < 0) {
groupIndexRef.current = previewUrls.length;
previewUrls.push(src);
setPreviewUrls(previewUrls);
React.useEffect(() => {
if (!isPreviewGroup) {
return () => {};
}
}, [previewUrls]);

useEffect(() => {
if (isCustomPlaceholder) {
setStatus('loading');
const unRegister = registerImage(currentId, src);

if (!canPreview) {
unRegister();
}
return () => {
setPreviewUrls(previewUrls.filter(url => url !== src));
};
}, [src]);

return unRegister;
}, [src, canPreview]);

const wrapperClass = cn(prefixCls, wrapperClassName, {
[`${prefixCls}-error`]: isError,
Expand Down Expand Up @@ -189,8 +186,6 @@ const ImageInternal: CompoundedComponent<ImageProps> = ({
},
};

const canPreview = preview && !isError;

return (
<>
<div
Expand All @@ -203,11 +198,15 @@ const ImageInternal: CompoundedComponent<ImageProps> = ({
...wrapperStyle,
}}
>
{isError && fallback ? (
<img {...imgCommonProps} src={fallback} />
) : (
<img {...imgCommonProps} onLoad={onLoad} onError={onError} src={src} ref={getImgRef} />
)}
<img
{...imgCommonProps}
ref={getImgRef}
{...(isError && fallback
? {
src: fallback,
}
: { onLoad, onError, src })}
/>

{status === 'loading' && (
<div aria-hidden="true" className={`${prefixCls}-placeholder`}>
Expand Down
42 changes: 18 additions & 24 deletions src/Preview.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,14 +12,13 @@ import addEventListener from 'rc-util/lib/Dom/addEventListener';
import { getOffset } from 'rc-util/lib/Dom/css';
import { warning } from 'rc-util/lib/warning';
import useFrameSetState from './hooks/useFrameSetState';
import usePreviewIndex from './hooks/usePreviewIndex';
import getFixScaleEleTransPosition from './getFixScaleEleTransPosition';
import { context } from './PreviewGroup';

const { useState } = React;

interface PreviewProps extends Omit<IDialogPropTypes, 'onClose'> {
onClose?: (e: React.SyntheticEvent<HTMLDivElement | HTMLLIElement>) => void;
onClose?: (e: React.SyntheticEvent<Element>) => void;
src?: string;
alt?: string;
}
Expand Down Expand Up @@ -50,12 +49,12 @@ const Preview: React.FC<PreviewProps> = props => {
deltaY: 0,
});
const [isMoving, setMoving] = React.useState(false);

const { previewUrls } = React.useContext(context);

const urls = previewUrls && previewUrls.length ? previewUrls : [src];

const [index, setIndex] = usePreviewIndex(src, urls);
const { previewUrls, current, isPreviewGroup, setCurrent } = React.useContext(context);
const previewGroupCount = previewUrls.size;
const previewUrlsKeys = Array.from(previewUrls.keys());
const currentPreviewIndex = previewUrlsKeys.indexOf(current);
const combinationSrc = isPreviewGroup ? previewUrls.get(current) : src;
const showLeftOrRightSwitches = isPreviewGroup && previewGroupCount > 1;

const onAfterClose = () => {
setScale(1);
Expand Down Expand Up @@ -87,19 +86,17 @@ const Preview: React.FC<PreviewProps> = props => {
event.preventDefault();
// Without this mask close will abnormal
event.stopPropagation();
if (index > 0) {
onAfterClose();
setIndex(index - 1);
if (currentPreviewIndex > 0) {
setCurrent(previewUrlsKeys[currentPreviewIndex - 1]);
}
};

const onSwitchRight: React.MouseEventHandler<HTMLDivElement> = event => {
event.preventDefault();
// Without this mask close will abnormal
event.stopPropagation();
if (index < urls.length - 1) {
onAfterClose();
setIndex(index + 1);
if (currentPreviewIndex < previewGroupCount - 1) {
setCurrent(previewUrlsKeys[currentPreviewIndex + 1]);
}
};

Expand Down Expand Up @@ -206,9 +203,6 @@ const Preview: React.FC<PreviewProps> = props => {
if (onTopMouseUpListener) onTopMouseUpListener.remove();
/* istanbul ignore next */
if (onTopMouseMoveListener) onTopMouseMoveListener.remove();
if (!visible) {
setIndex(urls.indexOf(src));
}
};
}, [visible, isMoving]);

Expand Down Expand Up @@ -248,33 +242,33 @@ const Preview: React.FC<PreviewProps> = props => {
onMouseDown={onMouseDown}
ref={imgRef}
className={`${prefixCls}-img`}
src={urls[index]}
src={combinationSrc}
alt={alt}
style={{
transform: `scale3d(${scale}, ${scale}, 1) rotate(${rotate}deg)`,
}}
/>
</div>
{urls.length > 1 ? (
{showLeftOrRightSwitches && (
<div
className={classnames(`${prefixCls}-switch-left`, {
[`${prefixCls}-switch-left-disabled`]: index <= 0,
[`${prefixCls}-switch-left-disabled`]: currentPreviewIndex === 0,
})}
onClick={onSwitchLeft}
>
<LeftOutlined />
</div>
) : null}
{urls.length > 1 ? (
)}
{showLeftOrRightSwitches && (
<div
className={classnames(`${prefixCls}-switch-right`, {
[`${prefixCls}-switch-right-disabled`]: index >= urls.length - 1,
[`${prefixCls}-switch-right-disabled`]: currentPreviewIndex === previewGroupCount - 1,
})}
onClick={onSwitchRight}
>
<RightOutlined />
</div>
) : null}
)}
</Dialog>
);
};
Expand Down
41 changes: 32 additions & 9 deletions src/PreviewGroup.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,19 +8,24 @@ export interface GroupConsumerProps {

export interface GroupConsumerValue extends GroupConsumerProps {
isPreviewGroup?: boolean;
previewUrls: string[];
setPreviewUrls: React.Dispatch<React.SetStateAction<string[]>>;
setCurrent: React.Dispatch<React.SetStateAction<string>>;
previewUrls: Map<number, string>;
setPreviewUrls: React.Dispatch<React.SetStateAction<Map<number, string>>>;
current: number;
setCurrent: React.Dispatch<React.SetStateAction<number>>;
setShowPreview: React.Dispatch<React.SetStateAction<boolean>>;
setMousePosition: React.Dispatch<React.SetStateAction<null | { x: number; y: number }>>;
registerImage: (id: number, url: string) => () => void;
}

/* istanbul ignore next */
export const context = React.createContext<GroupConsumerValue>({
previewUrls: [],
previewUrls: new Map(),
setPreviewUrls: () => null,
shaodahong marked this conversation as resolved.
Show resolved Hide resolved
current: null,
setCurrent: () => null,
setShowPreview: () => null,
setMousePosition: () => null,
registerImage: null,
});

const { Provider } = context;
Expand All @@ -29,34 +34,52 @@ const Group: React.FC<GroupConsumerProps> = ({
previewPrefixCls = 'rc-image-preview',
children,
}) => {
const [previewUrls, setPreviewUrls] = useState([]);
const [current, setCurrent] = useState();
const [previewUrls, setPreviewUrls] = useState<Map<number, string>>(new Map());
const [current, setCurrent] = useState<number>();
const [isShowPreview, setShowPreview] = useState(false);
const [mousePosition, setMousePosition] = useState<null | { x: number; y: number }>(null);
const onPreviewClose = (e: React.SyntheticEvent<HTMLDivElement>) => {

const registerImage = (id: number, url: string) => {
setPreviewUrls(oldPreviewUrls => {
return new Map(oldPreviewUrls).set(id, url);
});

return () => {
setPreviewUrls(oldPreviewUrls => {
const clonePreviewUrls = new Map(oldPreviewUrls);
const deleteResult = clonePreviewUrls.delete(id);
return deleteResult ? clonePreviewUrls : oldPreviewUrls;
});
};
};

const onPreviewClose = (e: React.SyntheticEvent<Element>) => {
e.stopPropagation();
setShowPreview(false);
setMousePosition(null);
};

return (
<Provider
value={{
isPreviewGroup: true,
previewUrls,
setPreviewUrls,
current,
setCurrent,
setShowPreview,
setMousePosition,
registerImage,
}}
>
{children}
<Preview
ria-hidden={!isShowPreview}
aria-hidden={!isShowPreview}
visible={isShowPreview}
prefixCls={previewPrefixCls}
onClose={onPreviewClose}
mousePosition={mousePosition}
src={current}
src={previewUrls.get(current)}
/>
</Provider>
);
Expand Down
Loading