-
-
Notifications
You must be signed in to change notification settings - Fork 118
Expand file tree
/
Copy pathindex.tsx
More file actions
493 lines (440 loc) · 13 KB
/
index.tsx
File metadata and controls
493 lines (440 loc) · 13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
import CSSMotion from '@rc-component/motion';
import Portal, { type PortalProps } from '@rc-component/portal';
import { useEvent } from '@rc-component/util';
import useLayoutEffect from '@rc-component/util/lib/hooks/useLayoutEffect';
import KeyCode from '@rc-component/util/lib/KeyCode';
import { clsx } from 'clsx';
import React, { useContext, useEffect, useRef, useState } from 'react';
import { PreviewGroupContext } from '../context';
import type { TransformAction, TransformType } from '../hooks/useImageTransform';
import useImageTransform from '../hooks/useImageTransform';
import useMouseEvent from '../hooks/useMouseEvent';
import useStatus from '../hooks/useStatus';
import useTouchEvent from '../hooks/useTouchEvent';
import type { ImgInfo } from '../Image';
import { BASE_SCALE_RATIO } from '../previewConfig';
import CloseBtn from './CloseBtn';
import Footer, { type FooterSemanticName } from './Footer';
import PrevNext from './PrevNext';
// Note: if you want to add `action`,
// pls contact @zombieJ or @thinkasany first.
export type PreviewSemanticName = 'root' | 'mask' | 'body' | FooterSemanticName;
export interface OperationIcons {
rotateLeft?: React.ReactNode;
rotateRight?: React.ReactNode;
zoomIn?: React.ReactNode;
zoomOut?: React.ReactNode;
close?: React.ReactNode;
prev?: React.ReactNode;
next?: React.ReactNode;
/** @deprecated Please use `prev` instead */
left?: React.ReactNode;
/** @deprecated Please use `next` instead */
right?: React.ReactNode;
flipX?: React.ReactNode;
flipY?: React.ReactNode;
}
export interface Actions {
onActive: (offset: number) => void;
onFlipY: () => void;
onFlipX: () => void;
onRotateLeft: () => void;
onRotateRight: () => void;
onZoomOut: () => void;
onZoomIn: () => void;
onClose: () => void;
onReset: () => void;
}
export type ToolbarRenderInfoType = {
icons: {
prevIcon?: React.ReactNode;
nextIcon?: React.ReactNode;
flipYIcon: React.ReactNode;
flipXIcon: React.ReactNode;
rotateLeftIcon: React.ReactNode;
rotateRightIcon: React.ReactNode;
zoomOutIcon: React.ReactNode;
zoomInIcon: React.ReactNode;
};
actions: Actions;
transform: TransformType;
current: number;
total: number;
image: ImgInfo;
};
export interface InternalPreviewConfig {
// Semantic
/** Better to use `classNames.root` instead */
rootClassName?: string;
// Image
src?: string;
alt?: string;
// Scale
scaleStep?: number;
minScale?: number;
maxScale?: number;
// Display
motionName?: string;
open?: boolean;
getContainer?: PortalProps['getContainer'];
zIndex?: number;
afterOpenChange?: (open: boolean) => void;
// Operation
movable?: boolean;
icons?: OperationIcons;
closeIcon?: React.ReactNode;
onTransform?: (info: { transform: TransformType; action: TransformAction }) => void;
// Render
countRender?: (current: number, total: number) => React.ReactNode;
imageRender?: (
originalNode: React.ReactElement,
info: { transform: TransformType; current?: number; image: ImgInfo },
) => React.ReactNode;
actionsRender?: (
originalNode: React.ReactElement,
info: ToolbarRenderInfoType,
) => React.ReactNode;
}
export interface PreviewProps extends InternalPreviewConfig {
// Misc
prefixCls: string;
classNames?: Partial<Record<PreviewSemanticName, string>>;
styles?: Partial<Record<PreviewSemanticName, React.CSSProperties>>;
// Origin image Info
imageInfo?: {
width: number | string;
height: number | string;
};
fallback?: string;
// Preview image
imgCommonProps?: React.ImgHTMLAttributes<HTMLImageElement>;
width?: string | number;
height?: string | number;
// Pagination
current?: number;
count?: number;
onChange?: (current: number, prev: number) => void;
// Events
onClose?: () => void;
// Display
mousePosition: null | { x: number; y: number };
}
interface PreviewImageProps extends React.ImgHTMLAttributes<HTMLImageElement> {
fallback?: string;
imgRef: React.MutableRefObject<HTMLImageElement>;
}
const PreviewImage: React.FC<PreviewImageProps> = ({ fallback, src, imgRef, ...props }) => {
const [getImgRef, srcAndOnload] = useStatus({
src,
fallback,
});
return (
<img
ref={ref => {
imgRef.current = ref;
getImgRef(ref);
}}
{...props}
{...srcAndOnload}
/>
);
};
const Preview: React.FC<PreviewProps> = props => {
const {
prefixCls,
rootClassName,
src,
alt,
imageInfo,
fallback,
movable = true,
onClose,
open,
afterOpenChange,
icons = {},
closeIcon,
getContainer,
current = 0,
count = 1,
countRender,
scaleStep = 0.5,
minScale = 1,
maxScale = 50,
motionName = 'fade',
imageRender,
imgCommonProps,
actionsRender,
onTransform,
onChange,
classNames = {},
styles = {},
mousePosition,
zIndex,
} = props;
const imgRef = useRef<HTMLImageElement>();
const groupContext = useContext(PreviewGroupContext);
const showLeftOrRightSwitches = groupContext && count > 1;
const showOperationsProgress = groupContext && count >= 1;
// ======================== Transform =========================
const [enableTransition, setEnableTransition] = useState(true);
const { transform, resetTransform, updateTransform, dispatchZoomChange } = useImageTransform(
imgRef,
minScale,
maxScale,
onTransform,
);
const { isMoving, onMouseDown, onWheel } = useMouseEvent(
imgRef,
movable,
open,
scaleStep,
transform,
updateTransform,
dispatchZoomChange,
);
const { isTouching, onTouchStart, onTouchMove, onTouchEnd } = useTouchEvent(
imgRef,
movable,
open,
minScale,
transform,
updateTransform,
dispatchZoomChange,
);
const { rotate, scale } = transform;
useEffect(() => {
if (!enableTransition) {
setEnableTransition(true);
}
}, [enableTransition]);
useEffect(() => {
if (!open) {
resetTransform('close');
}
}, [open]);
// ========================== Image ===========================
const onDoubleClick = (event: React.MouseEvent<HTMLImageElement, MouseEvent>) => {
if (open) {
if (scale !== 1) {
updateTransform({ x: 0, y: 0, scale: 1 }, 'doubleClick');
} else {
dispatchZoomChange(
BASE_SCALE_RATIO + scaleStep,
'doubleClick',
event.clientX,
event.clientY,
);
}
}
};
const imgNode = (
<PreviewImage
{...imgCommonProps}
width={props.width}
height={props.height}
imgRef={imgRef}
className={`${prefixCls}-img`}
alt={alt}
style={{
transform: `translate3d(${transform.x}px, ${transform.y}px, 0) scale3d(${
transform.flipX ? '-' : ''
}${scale}, ${transform.flipY ? '-' : ''}${scale}, 1) rotate(${rotate}deg)`,
transitionDuration: (!enableTransition || isTouching) && '0s',
}}
fallback={fallback}
src={src}
onWheel={onWheel}
onMouseDown={onMouseDown}
onDoubleClick={onDoubleClick}
onTouchStart={onTouchStart}
onTouchMove={onTouchMove}
onTouchEnd={onTouchEnd}
onTouchCancel={onTouchEnd}
/>
);
const image = {
url: src,
alt,
...imageInfo,
};
// ======================== Operation =========================
// >>>>> Actions
const onZoomIn = () => {
dispatchZoomChange(BASE_SCALE_RATIO + scaleStep, 'zoomIn');
};
const onZoomOut = () => {
dispatchZoomChange(BASE_SCALE_RATIO / (BASE_SCALE_RATIO + scaleStep), 'zoomOut');
};
const onRotateRight = () => {
updateTransform({ rotate: rotate + 90 }, 'rotateRight');
};
const onRotateLeft = () => {
updateTransform({ rotate: rotate - 90 }, 'rotateLeft');
};
const onFlipX = () => {
updateTransform({ flipX: !transform.flipX }, 'flipX');
};
const onFlipY = () => {
updateTransform({ flipY: !transform.flipY }, 'flipY');
};
const onReset = () => {
resetTransform('reset');
};
const onActive = (offset: number) => {
const nextCurrent = current + offset;
if (nextCurrent >= 0 && nextCurrent <= count - 1) {
setEnableTransition(false);
resetTransform(offset < 0 ? 'prev' : 'next');
onChange?.(nextCurrent, current);
}
};
// >>>>> Effect: Keyboard
const onKeyDown = useEvent((event: KeyboardEvent) => {
if (open) {
const { keyCode } = event;
if (keyCode === KeyCode.ESC) {
onClose?.();
}
if (showLeftOrRightSwitches) {
if (keyCode === KeyCode.LEFT) {
onActive(-1);
} else if (keyCode === KeyCode.RIGHT) {
onActive(1);
}
}
}
});
useEffect(() => {
if (open) {
window.addEventListener('keydown', onKeyDown);
return () => {
window.removeEventListener('keydown', onKeyDown);
};
}
}, [open]);
// ======================= Lock Scroll ========================
const [lockScroll, setLockScroll] = useState(false);
React.useEffect(() => {
if (open) {
setLockScroll(true);
}
}, [open]);
const onVisibleChanged = (nextVisible: boolean) => {
if (!nextVisible) {
setLockScroll(false);
}
afterOpenChange?.(nextVisible);
};
// ========================== Portal ==========================
const [portalRender, setPortalRender] = useState(false);
useLayoutEffect(() => {
if (open) {
setPortalRender(true);
}
}, [open]);
// ========================== Render ==========================
const bodyStyle: React.CSSProperties = {
...styles.body,
};
if (mousePosition) {
bodyStyle.transformOrigin = `${mousePosition.x}px ${mousePosition.y}px`;
}
return (
<Portal open={portalRender} getContainer={getContainer} autoLock={lockScroll}>
<div
className={clsx(prefixCls, rootClassName, classNames.root, { [`${prefixCls}-moving`]: isMoving })}
style={{ ...styles.root, ...(zIndex ? { zIndex } : {}) }}>
{/* Mask */}
<CSSMotion
motionName={motionName}
visible={portalRender && open}
motionAppear
motionEnter
motionLeave>
{({ className: motionClassName, style: motionStyle }) => {
return (<div
className={clsx(`${prefixCls}-mask`, classNames.mask, motionClassName)}
style={{ ...styles.mask, ...motionStyle }}
onClick={onClose}
/>);
}}
</CSSMotion>
<CSSMotion
motionName={motionName}
visible={portalRender && open}
motionAppear
motionEnter
motionLeave
onVisibleChanged={onVisibleChanged}
>
{({ className: motionClassName, style: motionStyle }) => {
return (
<div
className={clsx(motionClassName)}
style={{ ...motionStyle }}
>
{/* Body */}
<div className={clsx(`${prefixCls}-body`, classNames.body)} style={bodyStyle}>
{/* Preview Image */}
{imageRender
? imageRender(imgNode, { transform, image, ...(groupContext ? { current } : {}) })
: imgNode}
</div>
{/* Close Button */}
{closeIcon !== false && closeIcon !== null && (
<CloseBtn
prefixCls={prefixCls}
icon={closeIcon === true ? icons.close : closeIcon || icons.close}
onClick={onClose}
/>
)}
{/* Switch prev or next */}
{showLeftOrRightSwitches && (
<PrevNext
prefixCls={prefixCls}
current={current}
count={count}
icons={icons}
onActive={onActive}
/>
)}
{/* Footer */}
<Footer
prefixCls={prefixCls}
showProgress={showOperationsProgress}
current={current}
count={count}
showSwitch={showLeftOrRightSwitches}
// Style
classNames={classNames}
styles={styles}
// Render
image={image}
transform={transform}
icons={icons}
countRender={countRender}
actionsRender={actionsRender}
// Scale
scale={scale}
minScale={minScale}
maxScale={maxScale}
// Actions
onActive={onActive}
onFlipY={onFlipY}
onFlipX={onFlipX}
onRotateLeft={onRotateLeft}
onRotateRight={onRotateRight}
onZoomOut={onZoomOut}
onZoomIn={onZoomIn}
onClose={onClose}
onReset={onReset}
/>
</div>
);
}}
</CSSMotion>
</div>
</Portal>
);
};
export default Preview;