previewInner.tsx 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473
  1. import React, { CSSProperties } from "react";
  2. import BaseComponent from "../_base/baseComponent";
  3. import { PreviewInnerProps, PreviewInnerStates } from "./interface";
  4. import PropTypes from "prop-types";
  5. import { cssClasses, numbers } from "@douyinfe/semi-foundation/image/constants";
  6. import cls from "classnames";
  7. import { isEqual, isFunction } from "lodash";
  8. import Portal from "../_portal";
  9. import { IconArrowLeft, IconArrowRight } from "@douyinfe/semi-icons";
  10. import Header from "./previewHeader";
  11. import Footer from "./previewFooter";
  12. import PreviewImage from "./previewImage";
  13. import PreviewInnerFoundation, { PreviewInnerAdapter, RatioType } from "@douyinfe/semi-foundation/image/previewInnerFoundation";
  14. import { PreviewContext, PreviewContextProps } from "./previewContext";
  15. import { getScrollbarWidth } from "../_utils";
  16. import ReactDOM from "react-dom";
  17. const prefixCls = cssClasses.PREFIX;
  18. export default class PreviewInner extends BaseComponent<PreviewInnerProps, PreviewInnerStates> {
  19. static contextType = PreviewContext;
  20. static propTypes = {
  21. style: PropTypes.object,
  22. className: PropTypes.string,
  23. visible: PropTypes.bool,
  24. src: PropTypes.oneOfType([PropTypes.string, PropTypes.array]),
  25. currentIndex: PropTypes.number,
  26. defaultCurrentIndex: PropTypes.number,
  27. defaultVisible: PropTypes.bool,
  28. maskClosable: PropTypes.bool,
  29. closable: PropTypes.bool,
  30. zoomStep: PropTypes.number,
  31. infinite: PropTypes.bool,
  32. showTooltip: PropTypes.bool,
  33. closeOnEsc: PropTypes.bool,
  34. prevTip: PropTypes.string,
  35. nextTip: PropTypes.string,
  36. zoomInTip: PropTypes.string,
  37. zoomOutTip: PropTypes.string,
  38. downloadTip: PropTypes.string,
  39. adaptiveTip: PropTypes.string,
  40. originTip: PropTypes.string,
  41. lazyLoad: PropTypes.bool,
  42. preLoad: PropTypes.bool,
  43. preLoadGap: PropTypes.number,
  44. disableDownload: PropTypes.bool,
  45. viewerVisibleDelay: PropTypes.number,
  46. zIndex: PropTypes.number,
  47. maxZoom: PropTypes.number,
  48. minZoom: PropTypes.number,
  49. renderHeader: PropTypes.func,
  50. renderPreviewMenu: PropTypes.func,
  51. getPopupContainer: PropTypes.func,
  52. onVisibleChange: PropTypes.func,
  53. onChange: PropTypes.func,
  54. onClose: PropTypes.func,
  55. onZoomIn: PropTypes.func,
  56. onZoomOut: PropTypes.func,
  57. onPrev: PropTypes.func,
  58. onNext: PropTypes.func,
  59. onDownload: PropTypes.func,
  60. onRatioChange: PropTypes.func,
  61. onRotateLeft: PropTypes.func,
  62. }
  63. static defaultProps = {
  64. showTooltip: false,
  65. zoomStep: 0.1,
  66. infinite: false,
  67. closeOnEsc: true,
  68. lazyLoad: false,
  69. preLoad: true,
  70. preLoadGap: 2,
  71. zIndex: numbers.DEFAULT_Z_INDEX,
  72. maskClosable: true,
  73. viewerVisibleDelay: 10000,
  74. maxZoom: 5,
  75. minZoom: 0.1
  76. };
  77. private bodyOverflow: string;
  78. private scrollBarWidth: number;
  79. private originBodyWidth: string;
  80. get adapter(): PreviewInnerAdapter<PreviewInnerProps, PreviewInnerStates> {
  81. return {
  82. ...super.adapter,
  83. getIsInGroup: () => this.isInGroup(),
  84. disabledBodyScroll: () => {
  85. const { getPopupContainer } = this.props;
  86. this.bodyOverflow = document.body.style.overflow || '';
  87. if (!getPopupContainer && this.bodyOverflow !== 'hidden') {
  88. document.body.style.overflow = 'hidden';
  89. document.body.style.width = `calc(${this.originBodyWidth || '100%'} - ${this.scrollBarWidth}px)`;
  90. }
  91. },
  92. enabledBodyScroll: () => {
  93. const { getPopupContainer } = this.props;
  94. if (!getPopupContainer && this.bodyOverflow !== 'hidden') {
  95. document.body.style.overflow = this.bodyOverflow;
  96. document.body.style.width = this.originBodyWidth;
  97. }
  98. },
  99. notifyChange: (index: number, direction: string) => {
  100. const { onChange, onPrev, onNext } = this.props;
  101. isFunction(onChange) && onChange(index);
  102. if (direction === "prev") {
  103. onPrev && onPrev(index);
  104. } else {
  105. onNext && onNext(index);
  106. }
  107. },
  108. notifyZoom: (zoom: number, increase: boolean) => {
  109. const { onZoomIn, onZoomOut } = this.props;
  110. if (increase) {
  111. isFunction(onZoomIn) && onZoomIn(zoom);
  112. } else {
  113. isFunction(onZoomOut) && onZoomOut(zoom);
  114. }
  115. },
  116. notifyClose: () => {
  117. const { onClose } = this.props;
  118. isFunction(onClose) && onClose();
  119. },
  120. notifyVisibleChange: (visible: boolean) => {
  121. const { onVisibleChange } = this.props;
  122. isFunction(onVisibleChange) && onVisibleChange(visible);
  123. },
  124. notifyRatioChange: (type: RatioType) => {
  125. const { onRatioChange } = this.props;
  126. isFunction(onRatioChange) && onRatioChange(type);
  127. },
  128. notifyRotateChange: (angle: number) => {
  129. const { onRotateLeft } = this.props;
  130. isFunction(onRotateLeft) && onRotateLeft(angle);
  131. },
  132. notifyDownload: (src: string, index: number) => {
  133. const { onDownload } = this.props;
  134. isFunction(onDownload) && onDownload(src, index);
  135. },
  136. registerKeyDownListener: () => {
  137. window && window.addEventListener("keydown", this.handleKeyDown);
  138. },
  139. unregisterKeyDownListener: () => {
  140. window && window.removeEventListener("keydown", this.handleKeyDown);
  141. },
  142. getSetDownloadFunc: () => {
  143. return this.context?.setDownloadName ?? this.props.setDownloadName;
  144. },
  145. isValidTarget: (e) => {
  146. const headerDom = this.headerRef && this.headerRef.current;
  147. const footerDom = this.footerRef && this.footerRef.current;
  148. const leftIconDom = this.leftIconRef && this.leftIconRef.current;
  149. const rightIconDom = this.rightIconRef && this.rightIconRef.current;
  150. const target = e.target as any;
  151. if (
  152. headerDom && headerDom.contains(target) ||
  153. footerDom && footerDom.contains(target) ||
  154. leftIconDom && leftIconDom.contains(target) ||
  155. rightIconDom && rightIconDom.contains(target)
  156. ) {
  157. // Move in the operation area, return false
  158. return false;
  159. }
  160. // Move in the preview area except the operation area, return true
  161. return true;
  162. }
  163. };
  164. }
  165. context: PreviewContextProps;
  166. foundation: PreviewInnerFoundation;
  167. imageWrapRef: React.RefObject<HTMLDivElement>;
  168. headerRef: React.RefObject<HTMLElement>;
  169. footerRef: React.RefObject<HTMLElement>;
  170. leftIconRef: React.RefObject<HTMLDivElement>;
  171. rightIconRef: React.RefObject<HTMLDivElement>;
  172. constructor(props: PreviewInnerProps) {
  173. super(props);
  174. this.state = {
  175. imgSrc: [],
  176. imgLoadStatus: new Map(),
  177. zoom: 0.1,
  178. currentIndex: 0,
  179. ratio: "adaptation",
  180. rotation: 0,
  181. viewerVisible: true,
  182. visible: false,
  183. preloadAfterVisibleChange: true,
  184. direction: "",
  185. };
  186. this.foundation = new PreviewInnerFoundation(this.adapter);
  187. this.bodyOverflow = '';
  188. this.originBodyWidth = '100%';
  189. this.scrollBarWidth = 0;
  190. this.imageWrapRef = null;
  191. this.headerRef = React.createRef<HTMLElement>();
  192. this.footerRef= React.createRef<HTMLElement>();
  193. this.leftIconRef= React.createRef<HTMLDivElement>();
  194. this.rightIconRef= React.createRef<HTMLDivElement>();
  195. }
  196. static getDerivedStateFromProps(props: PreviewInnerProps, state: PreviewInnerStates) {
  197. const willUpdateStates: Partial<PreviewInnerStates> = {};
  198. let src = [];
  199. if (props.visible) {
  200. // if src in props
  201. src = Array.isArray(props.src) ? props.src : [props.src];
  202. }
  203. if (!isEqual(src, state.imgSrc)) {
  204. willUpdateStates.imgSrc = src;
  205. }
  206. if (props.visible !== state.visible) {
  207. willUpdateStates.visible = props.visible;
  208. if (props.visible) {
  209. willUpdateStates.preloadAfterVisibleChange = true;
  210. willUpdateStates.viewerVisible = true;
  211. willUpdateStates.rotation = 0;
  212. willUpdateStates.ratio = 'adaptation';
  213. }
  214. }
  215. if ("currentIndex" in props && props.currentIndex !== state.currentIndex) {
  216. willUpdateStates.currentIndex = props.currentIndex;
  217. // ratio will set to adaptation when change picture,
  218. // attention: If the ratio is controlled, the ratio should not change as the index changes
  219. willUpdateStates.ratio = 'adaptation';
  220. }
  221. return willUpdateStates;
  222. }
  223. componentDidMount() {
  224. this.scrollBarWidth = getScrollbarWidth();
  225. this.originBodyWidth = document.body.style.width;
  226. if (this.props.visible) {
  227. this.foundation.beforeShow();
  228. }
  229. }
  230. componentDidUpdate(prevProps: PreviewInnerProps, prevState: PreviewInnerStates) {
  231. if (prevProps.src !== this.props.src) {
  232. this.foundation.updateTimer();
  233. }
  234. // hide => show
  235. if (!prevProps.visible && this.props.visible) {
  236. this.foundation.beforeShow();
  237. }
  238. // show => hide
  239. if (prevProps.visible && !this.props.visible) {
  240. this.foundation.afterHide();
  241. }
  242. }
  243. componentWillUnmount() {
  244. this.foundation.clearTimer();
  245. }
  246. isInGroup() {
  247. return Boolean(this.context && this.context.isGroup);
  248. }
  249. viewVisibleChange = () => {
  250. this.foundation.handleViewVisibleChange();
  251. }
  252. handleSwitchImage = (direction: string) => {
  253. this.foundation.handleSwitchImage(direction);
  254. }
  255. handleDownload = () => {
  256. this.foundation.handleDownload();
  257. }
  258. handlePreviewClose = (e: React.MouseEvent<HTMLElement>) => {
  259. this.foundation.handlePreviewClose(e);
  260. }
  261. handleAdjustRatio = (type: RatioType) => {
  262. this.foundation.handleAdjustRatio(type);
  263. }
  264. handleRotateImage = (direction) => {
  265. this.foundation.handleRotateImage(direction);
  266. }
  267. handleZoomImage = (newZoom: number, notify: boolean = true) => {
  268. this.foundation.handleZoomImage(newZoom, notify);
  269. }
  270. handleMouseUp = (e): void => {
  271. this.foundation.handleMouseUp(e.nativeEvent);
  272. }
  273. handleMouseMove = (e): void => {
  274. this.foundation.handleMouseMove(e);
  275. }
  276. handleKeyDown = (e: KeyboardEvent) => {
  277. this.foundation.handleKeyDown(e);
  278. };
  279. onImageError = () => {
  280. this.foundation.preloadSingleImage();
  281. }
  282. onImageLoad = (src) => {
  283. this.foundation.onImageLoad(src);
  284. }
  285. handleMouseDown = (e): void => {
  286. this.foundation.handleMouseDown(e);
  287. }
  288. handleWheel = (e) => {
  289. this.foundation.handleWheel(e);
  290. }
  291. // 为什么通过 addEventListener 注册 wheel 事件而不是使用 onWheel 事件?
  292. // 因为 Passive Event Listeners(https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#improving_scrolling_performance_with_passive_listeners)
  293. // Passive Event Listeners 是一种优化技术,用于提高滚动性能。在默认情况下,浏览器会假设事件的监听器不会调用
  294. // preventDefault() 方法来阻止事件的默认行为,从而允许进行一些优化操作,例如滚动平滑。
  295. // 对于 Image 而言,如果使用触控板,双指朝不同方向分开放大图片,则需要 preventDefault 防止页面整体放大。
  296. // Why register wheel event through addEventListener instead of using onWheel event?
  297. // Because of Passive Event Listeners(an optimization technique used to improve scrolling performance. By default,
  298. // the browser will assume that event listeners will not call preventDefault() method to prevent the default behavior of the event,
  299. // allowing some optimization operations such as scroll smoothing.)
  300. // For Image, if we use the trackpad and spread your fingers in different directions to enlarge the image, we need to preventDefault
  301. // to prevent the page from being enlarged as a whole.
  302. registryImageWrapRef = (ref): void => {
  303. if (this.imageWrapRef) {
  304. (this.imageWrapRef as any).removeEventListener("wheel", this.handleWheel);
  305. }
  306. if (ref) {
  307. ref.addEventListener("wheel", this.handleWheel, { passive: false });
  308. }
  309. this.imageWrapRef = ref;
  310. };
  311. render() {
  312. const {
  313. getPopupContainer,
  314. closable,
  315. zIndex,
  316. visible,
  317. className,
  318. style,
  319. infinite,
  320. zoomStep,
  321. crossOrigin,
  322. prevTip,
  323. nextTip,
  324. zoomInTip,
  325. zoomOutTip,
  326. rotateTip,
  327. downloadTip,
  328. adaptiveTip,
  329. originTip,
  330. showTooltip,
  331. disableDownload,
  332. renderPreviewMenu,
  333. renderHeader,
  334. } = this.props;
  335. const { currentIndex, imgSrc, zoom, ratio, rotation, viewerVisible } = this.state;
  336. let wrapperStyle: {
  337. zIndex?: CSSProperties["zIndex"];
  338. position?: CSSProperties["position"]
  339. } = {
  340. zIndex,
  341. };
  342. if (getPopupContainer) {
  343. wrapperStyle = {
  344. zIndex,
  345. position: "static",
  346. };
  347. }
  348. const previewPrefixCls = `${prefixCls}-preview`;
  349. const previewWrapperCls = cls(previewPrefixCls,
  350. {
  351. [`${prefixCls}-hide`]: !visible,
  352. [`${previewPrefixCls}-popup`]: getPopupContainer,
  353. },
  354. className,
  355. );
  356. const hideViewerCls = !viewerVisible ? `${previewPrefixCls}-hide` : "";
  357. const total = imgSrc.length;
  358. const showPrev = total !== 1 && (infinite || currentIndex !== 0);
  359. const showNext = total !== 1 && (infinite || currentIndex !== total - 1);
  360. return (
  361. visible && <Portal
  362. getPopupContainer={getPopupContainer}
  363. style={wrapperStyle}
  364. >
  365. {/* eslint-disable-next-line jsx-a11y/no-static-element-interactions */}
  366. <div
  367. className={previewWrapperCls}
  368. style={style}
  369. onMouseDown={this.handleMouseDown}
  370. onMouseUp={this.handleMouseUp}
  371. ref={this.registryImageWrapRef}
  372. onMouseMove={this.handleMouseMove}
  373. >
  374. <Header ref={this.headerRef} className={cls(hideViewerCls)} onClose={this.handlePreviewClose} renderHeader={renderHeader} closable={closable}/>
  375. <PreviewImage
  376. src={imgSrc[currentIndex]}
  377. onZoom={this.handleZoomImage}
  378. disableDownload={disableDownload}
  379. setRatio={this.handleAdjustRatio}
  380. zoom={zoom}
  381. ratio={ratio}
  382. rotation={rotation}
  383. crossOrigin={crossOrigin}
  384. onError={this.onImageError}
  385. onLoad={this.onImageLoad}
  386. />
  387. {showPrev && (
  388. // eslint-disable-next-line jsx-a11y/click-events-have-key-events,jsx-a11y/no-static-element-interactions
  389. <div
  390. ref={this.leftIconRef}
  391. className={cls(`${previewPrefixCls}-icon`, `${previewPrefixCls}-prev`, hideViewerCls)}
  392. onClick={(): void => this.handleSwitchImage("prev")}
  393. >
  394. <IconArrowLeft size="large" />
  395. </div>
  396. )}
  397. {showNext && (
  398. // eslint-disable-next-line jsx-a11y/click-events-have-key-events,jsx-a11y/no-static-element-interactions
  399. <div
  400. ref={this.rightIconRef}
  401. className={cls(`${previewPrefixCls}-icon`, `${previewPrefixCls}-next`, hideViewerCls)}
  402. onClick={(): void => this.handleSwitchImage("next")}
  403. >
  404. <IconArrowRight size="large" />
  405. </div>
  406. )}
  407. <Footer
  408. forwardRef={this.footerRef}
  409. className={hideViewerCls}
  410. totalNum={total}
  411. curPage={currentIndex + 1}
  412. disabledPrev={!showPrev}
  413. disabledNext={!showNext}
  414. zoom={zoom * 100}
  415. step={zoomStep * 100}
  416. showTooltip={showTooltip}
  417. ratio={ratio}
  418. prevTip={prevTip}
  419. nextTip={nextTip}
  420. zIndex={zIndex}
  421. zoomInTip={zoomInTip}
  422. zoomOutTip={zoomOutTip}
  423. rotateTip={rotateTip}
  424. downloadTip={downloadTip}
  425. disableDownload={disableDownload}
  426. adaptiveTip={adaptiveTip}
  427. originTip={originTip}
  428. onPrev={(): void => this.handleSwitchImage("prev")}
  429. onNext={(): void => this.handleSwitchImage("next")}
  430. onZoomIn={this.handleZoomImage}
  431. onZoomOut={this.handleZoomImage}
  432. onDownload={this.handleDownload}
  433. onRotate={this.handleRotateImage}
  434. onAdjustRatio={this.handleAdjustRatio}
  435. renderPreviewMenu={renderPreviewMenu}
  436. />
  437. </div>
  438. </Portal>
  439. );
  440. }
  441. }