Skip to content

Commit

Permalink
fix: reset to first when close
Browse files Browse the repository at this point in the history
  • Loading branch information
linxianxi committed Jun 17, 2023
1 parent e0ef69b commit ea44fc6
Show file tree
Hide file tree
Showing 7 changed files with 50 additions and 57 deletions.
6 changes: 3 additions & 3 deletions src/Image.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { getOffset } from 'rc-util/lib/Dom/css';
import useMergedState from 'rc-util/lib/hooks/useMergedState';
import type { GetContainer } from 'rc-util/lib/PortalWrapper';
import * as React from 'react';
import { useContext, useEffect, useRef, useState } from 'react';
import { useContext, useEffect, useMemo, useRef, useState } from 'react';
import { PreviewGroupContext } from './context';
import type { TransformType } from './hooks/useImageTransform';
import useRegisterImage from './hooks/useRegisterImage';
Expand Down Expand Up @@ -179,7 +179,7 @@ const ImageInternal: CompoundedComponent<ImageProps> = props => {
const mergedSrc = isError && fallback ? fallback : src;

// ========================= ImageProps =========================
const imgCommonProps = React.useMemo(
const imgCommonProps = useMemo(
() => {
const obj: ImageElementProps = {};
COMMON_PROPS.forEach((prop: any) => {
Expand All @@ -194,7 +194,7 @@ const ImageInternal: CompoundedComponent<ImageProps> = props => {
);

// ========================== Register ==========================
const registerData: ImageElementProps = React.useMemo(
const registerData: ImageElementProps = useMemo(
() => ({
...imgCommonProps,
src,
Expand Down
12 changes: 6 additions & 6 deletions src/Operations.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ interface OperationsProps
> {
showSwitch: boolean;
showProgress: boolean;
currentIndex: number;
current: number;
transform: TransformType;
count: number;
scale: number;
Expand Down Expand Up @@ -51,7 +51,7 @@ const Operations: React.FC<OperationsProps> = props => {
countRender,
showSwitch,
showProgress,
currentIndex,
current,
transform,
count,
scale,
Expand Down Expand Up @@ -131,7 +131,7 @@ const Operations: React.FC<OperationsProps> = props => {
<ul className={`${prefixCls}-operations`}>
{showProgress && (
<li className={`${prefixCls}-operations-progress`}>
{countRender?.(currentIndex + 1, count) ?? `${currentIndex + 1} / ${count}`}
{countRender?.(current + 1, count) ?? `${current + 1} / ${count}`}
</li>
)}
{toolsNode}
Expand All @@ -144,15 +144,15 @@ const Operations: React.FC<OperationsProps> = props => {
<>
<div
className={classnames(`${prefixCls}-switch-left`, {
[`${prefixCls}-switch-left-disabled`]: currentIndex === 0,
[`${prefixCls}-switch-left-disabled`]: current === 0,
})}
onClick={onSwitchLeft}
>
{left}
</div>
<div
className={classnames(`${prefixCls}-switch-right`, {
[`${prefixCls}-switch-right-disabled`]: currentIndex === count - 1,
[`${prefixCls}-switch-right-disabled`]: current === count - 1,
})}
onClick={onSwitchRight}
>
Expand Down Expand Up @@ -182,7 +182,7 @@ const Operations: React.FC<OperationsProps> = props => {
close: onClose,
},
transform,
...(groupContext ? { current: currentIndex, total: count } : {}),
...(groupContext ? { current, total: count } : {}),
})
: toolbar}
</>
Expand Down
8 changes: 5 additions & 3 deletions src/Preview.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@ import addEventListener from 'rc-util/lib/Dom/addEventListener';
import KeyCode from 'rc-util/lib/KeyCode';
import { warning } from 'rc-util/lib/warning';
import React, { useContext, useEffect, useRef, useState } from 'react';
import getFixScaleEleTransPosition from './getFixScaleEleTransPosition';
import { PreviewGroupContext } from './context';
import getFixScaleEleTransPosition from './getFixScaleEleTransPosition';
import type { TransformAction, TransformType } from './hooks/useImageTransform';
import useImageTransform from './hooks/useImageTransform';
import Operations from './Operations';
Expand Down Expand Up @@ -67,7 +67,7 @@ export interface PreviewProps extends Omit<IDialogPropTypes, 'onClose'> {
onClose?: () => void;
onTransform?: (params: { transform: TransformType; action: TransformAction }) => void;
toolbarRender?: (params: ToolbarRenderType) => React.ReactNode;
onChange?: (currentIndex, prevIndex) => void;
onChange?: (current, prev) => void;
}

const Preview: React.FC<PreviewProps> = props => {
Expand All @@ -93,6 +93,7 @@ const Preview: React.FC<PreviewProps> = props => {
toolbarRender,
onTransform,
onChange,
afterClose,
...restProps
} = props;

Expand Down Expand Up @@ -128,6 +129,7 @@ const Preview: React.FC<PreviewProps> = props => {

const onAfterClose = () => {
resetTransform('close');
afterClose?.();
};

const onZoomIn = () => {
Expand Down Expand Up @@ -363,7 +365,7 @@ const Preview: React.FC<PreviewProps> = props => {
countRender={countRender}
showSwitch={showLeftOrRightSwitches}
showProgress={showOperationsProgress}
currentIndex={current}
current={current}
count={count}
scale={scale}
minScale={minScale}
Expand Down
37 changes: 19 additions & 18 deletions src/PreviewGroup.tsx
Original file line number Diff line number Diff line change
@@ -1,13 +1,11 @@
import useMergedState from 'rc-util/lib/hooks/useMergedState';
import omit from 'rc-util/lib/omit';
import * as React from 'react';
import { useState } from 'react';
import { PreviewGroupContext } from './context';
import type { TransformType } from './hooks/useImageTransform';
import usePreviewItems from './hooks/usePreviewItems';
import type { ImagePreviewType } from './Image';
import type { ImageElementProps } from './interface';
import { InternalItem, OnGroupPreview } from './interface';
import type { ImageElementProps, OnGroupPreview } from './interface';
import type { PreviewProps, ToolbarRenderType } from './Preview';
import Preview from './Preview';

Expand All @@ -28,7 +26,7 @@ export interface PreviewGroupPreview
transform: TransformType;
current: number;
}) => React.ReactNode;
onVisibleChange?: (value: boolean, prevValue: boolean, currentIndex: number) => void;
onVisibleChange?: (value: boolean, prevValue: boolean, current: number) => void;
onChange?: (current: number, prevCurrent: number) => void;
}

Expand Down Expand Up @@ -66,7 +64,7 @@ const Group: React.FC<GroupConsumerProps> = ({
visible: previewVisible,
onVisibleChange,
getContainer,
current,
current: currentIndex,
minScale,
maxScale,
countRender,
Expand All @@ -82,22 +80,17 @@ const Group: React.FC<GroupConsumerProps> = ({

// ========================= Preview ==========================
// >>> Index
const [currentIndex, setCurrentIndex] = useMergedState(0, {
value: current,
const [current, setCurrent] = useMergedState(0, {
value: currentIndex,
});

// >>> Image
const imgCommonProps = omit(mergedItems[currentIndex] || ({} as InternalItem), [
'id',
'canPreview',
]);
const src = imgCommonProps.src;

const { src, ...imgCommonProps } = mergedItems[current]?.imgData || {};
// >>> Visible
const [isShowPreview, setShowPreview] = useMergedState(!!previewVisible, {
value: previewVisible,
onChange: (val, prevVal) => {
onVisibleChange?.(val, prevVal, currentIndex);
onVisibleChange?.(val, prevVal, current);
},
});

Expand All @@ -110,18 +103,18 @@ const Group: React.FC<GroupConsumerProps> = ({

setShowPreview(true);
setMousePosition({ x: mouseX, y: mouseY });
setCurrentIndex(
setCurrent(
// `items` should always open the first one
// We easy replace `-1` to `0` here
index < 0 ? 0 : index,
Math.max(0, index),
);
},
[mergedItems],
);

// ========================== Events ==========================
const onInternalChange: PreviewGroupPreview['onChange'] = (next, prev) => {
setCurrentIndex(next);
setCurrent(next);

onChange?.(next, prev);
};
Expand All @@ -131,6 +124,13 @@ const Group: React.FC<GroupConsumerProps> = ({
setMousePosition(null);
};

// if not controlled current, reset to first image when closed
const afterClose = () => {
if (currentIndex === undefined) {
setCurrent(0);
}
};

// ========================= Context ==========================
const previewGroupContext = React.useMemo(
() => ({ register, onPreview: onPreviewFromImage }),
Expand All @@ -153,13 +153,14 @@ const Group: React.FC<GroupConsumerProps> = ({
minScale={minScale}
maxScale={maxScale}
getContainer={getContainer}
current={currentIndex}
current={current}
count={mergedItems.length}
countRender={countRender}
onTransform={onTransform}
toolbarRender={toolbarRender}
imageRender={imageRender}
onChange={onInternalChange}
afterClose={afterClose}
{...dialogProps}
/>
</PreviewGroupContext.Provider>
Expand Down
27 changes: 11 additions & 16 deletions src/hooks/usePreviewItems.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import * as React from 'react';
import type { InternalItem, PreviewImageElementProps, RegisterImage } from '../interface';
import type { GroupConsumerProps } from '../PreviewGroup';

export type Items = InternalItem[];
export type Items = Omit<InternalItem, 'canPreview'>[];

/**
* Merge props provided `items` or context collected images
Expand Down Expand Up @@ -31,23 +31,18 @@ export default function usePreviewItems(
// items
const mergedItems = React.useMemo<Items>(() => {
if (items) {
return items.map((item, index) => {
const itemObj = typeof item === 'string' ? { src: item } : item;

return {
...itemObj,
// From `items` should always `id` not same as context registered one
id: `items_${index}`,
};
});
return items.map(item =>
typeof item === 'string' ? { imgData: { src: item } } : { imgData: item },
);
}

return Object.keys(images)
.map(id => ({
...images[id],
id,
}))
.filter(info => info.canPreview);
return Object.keys(images).reduce((total: Items, id) => {
const { canPreview, imgData } = images[id];
if (canPreview) {
total.push({ imgData, id });
}
return total;
}, []);
}, [items, images]);

return [mergedItems, registerImage];
Expand Down
12 changes: 3 additions & 9 deletions src/hooks/useRegisterImage.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import * as React from 'react';
import type { ImageElementProps } from '../interface';
import { PreviewGroupContext } from '../context';
import type { ImageElementProps } from '../interface';

let uid = 0;

Expand All @@ -12,7 +12,7 @@ export default function useRegisterImage(canPreview: boolean, imgData: ImageElem
const groupContext = React.useContext(PreviewGroupContext);

const registerData = {
...imgData,
imgData,
canPreview,
};

Expand All @@ -23,13 +23,7 @@ export default function useRegisterImage(canPreview: boolean, imgData: ImageElem
if (groupContext) {
return groupContext.register(id, registerData);
}
}, [canPreview]);

React.useEffect(() => {
if (groupContext) {
return groupContext.register(id, registerData);
}
}, [imgData]);
}, [canPreview, imgData]);

return id;
}
5 changes: 3 additions & 2 deletions src/interface.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,13 @@ export type ImageElementProps = Pick<
| 'alt'
>;

export type PreviewImageElementProps = ImageElementProps & {
export type PreviewImageElementProps = {
imgData: ImageElementProps;
canPreview: boolean;
};

export type InternalItem = PreviewImageElementProps & {
id: string;
id?: string;
};

export type RegisterImage = (id: string, data: PreviewImageElementProps) => VoidFunction;
Expand Down

0 comments on commit ea44fc6

Please sign in to comment.