previewInner.tsx 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483
  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. notifyDownloadError: (src: string) => {
  137. const { onDownloadError } = this.props;
  138. isFunction(onDownloadError) && onDownloadError(src);
  139. },
  140. registerKeyDownListener: () => {
  141. window && window.addEventListener("keydown", this.handleKeyDown);
  142. },
  143. unregisterKeyDownListener: () => {
  144. window && window.removeEventListener("keydown", this.handleKeyDown);
  145. },
  146. getSetDownloadFunc: () => {
  147. return this.context?.setDownloadName ?? this.props.setDownloadName;
  148. },
  149. isValidTarget: (e) => {
  150. const headerDom = this.headerRef && this.headerRef.current;
  151. const footerDom = this.footerRef && this.footerRef.current;
  152. const leftIconDom = this.leftIconRef && this.leftIconRef.current;
  153. const rightIconDom = this.rightIconRef && this.rightIconRef.current;
  154. const target = e.target as any;
  155. if (
  156. headerDom && headerDom.contains(target) ||
  157. footerDom && footerDom.contains(target) ||
  158. leftIconDom && leftIconDom.contains(target) ||
  159. rightIconDom && rightIconDom.contains(target)
  160. ) {
  161. // Move in the operation area, return false
  162. return false;
  163. }
  164. // Move in the preview area except the operation area, return true
  165. return true;
  166. },
  167. changeImageZoom: (...args) => {
  168. this.imageRef?.current && this.imageRef.current.foundation.changeZoom(...args)
  169. }
  170. };
  171. }
  172. context: PreviewContextProps;
  173. foundation: PreviewInnerFoundation;
  174. imageWrapRef: React.RefObject<HTMLDivElement>;
  175. headerRef: React.RefObject<HTMLElement>;
  176. imageRef: React.RefObject<PreviewImage>;
  177. footerRef: React.RefObject<HTMLElement>;
  178. leftIconRef: React.RefObject<HTMLDivElement>;
  179. rightIconRef: React.RefObject<HTMLDivElement>;
  180. constructor(props: PreviewInnerProps) {
  181. super(props);
  182. this.state = {
  183. imgSrc: [],
  184. imgLoadStatus: new Map(),
  185. zoom: 0.1,
  186. currentIndex: 0,
  187. ratio: "adaptation",
  188. rotation: 0,
  189. viewerVisible: true,
  190. visible: false,
  191. preloadAfterVisibleChange: true,
  192. direction: "",
  193. };
  194. this.foundation = new PreviewInnerFoundation(this.adapter);
  195. this.bodyOverflow = '';
  196. this.originBodyWidth = '100%';
  197. this.scrollBarWidth = 0;
  198. this.imageWrapRef = null;
  199. this.imageRef = React.createRef<PreviewImage>();
  200. this.headerRef = React.createRef<HTMLElement>();
  201. this.footerRef= React.createRef<HTMLElement>();
  202. this.leftIconRef= React.createRef<HTMLDivElement>();
  203. this.rightIconRef= React.createRef<HTMLDivElement>();
  204. }
  205. static getDerivedStateFromProps(props: PreviewInnerProps, state: PreviewInnerStates) {
  206. const willUpdateStates: Partial<PreviewInnerStates> = {};
  207. let src = [];
  208. if (props.visible) {
  209. // if src in props
  210. src = Array.isArray(props.src) ? props.src : [props.src];
  211. }
  212. if (!isEqual(src, state.imgSrc)) {
  213. willUpdateStates.imgSrc = src;
  214. }
  215. if (props.visible !== state.visible) {
  216. willUpdateStates.visible = props.visible;
  217. if (props.visible) {
  218. willUpdateStates.preloadAfterVisibleChange = true;
  219. willUpdateStates.viewerVisible = true;
  220. willUpdateStates.rotation = 0;
  221. willUpdateStates.ratio = 'adaptation';
  222. }
  223. }
  224. if ("currentIndex" in props && props.currentIndex !== state.currentIndex) {
  225. willUpdateStates.currentIndex = props.currentIndex;
  226. // ratio will set to adaptation when change picture,
  227. // attention: If the ratio is controlled, the ratio should not change as the index changes
  228. willUpdateStates.ratio = 'adaptation';
  229. }
  230. return willUpdateStates;
  231. }
  232. componentDidMount() {
  233. this.scrollBarWidth = getScrollbarWidth();
  234. this.originBodyWidth = document.body.style.width;
  235. if (this.props.visible) {
  236. this.foundation.beforeShow();
  237. }
  238. }
  239. componentDidUpdate(prevProps: PreviewInnerProps, prevState: PreviewInnerStates) {
  240. if (prevProps.src !== this.props.src) {
  241. this.foundation.updateTimer();
  242. }
  243. // hide => show
  244. if (!prevProps.visible && this.props.visible) {
  245. this.foundation.beforeShow();
  246. }
  247. // show => hide
  248. if (prevProps.visible && !this.props.visible) {
  249. this.foundation.afterHide();
  250. }
  251. }
  252. componentWillUnmount() {
  253. this.foundation.clearTimer();
  254. }
  255. isInGroup() {
  256. return Boolean(this.context && this.context.isGroup);
  257. }
  258. viewVisibleChange = () => {
  259. this.foundation.handleViewVisibleChange();
  260. }
  261. handleSwitchImage = (direction: string) => {
  262. this.foundation.handleSwitchImage(direction);
  263. }
  264. handleDownload = () => {
  265. this.foundation.handleDownload();
  266. }
  267. handlePreviewClose = (e: React.MouseEvent<HTMLElement>) => {
  268. this.foundation.handlePreviewClose(e);
  269. }
  270. handleAdjustRatio = (type: RatioType) => {
  271. this.foundation.handleAdjustRatio(type);
  272. }
  273. handleRotateImage = (direction) => {
  274. this.foundation.handleRotateImage(direction);
  275. }
  276. handleZoomImage = (newZoom: number, notify: boolean = true) => {
  277. this.foundation.handleZoomImage(newZoom, notify);
  278. }
  279. handleMouseUp = (e): void => {
  280. this.foundation.handleMouseUp(e.nativeEvent);
  281. }
  282. handleMouseMove = (e): void => {
  283. this.foundation.handleMouseMove(e);
  284. }
  285. handleKeyDown = (e: KeyboardEvent) => {
  286. this.foundation.handleKeyDown(e);
  287. };
  288. onImageError = () => {
  289. this.foundation.preloadSingleImage();
  290. }
  291. onImageLoad = (src) => {
  292. this.foundation.onImageLoad(src);
  293. }
  294. handleMouseDown = (e): void => {
  295. this.foundation.handleMouseDown(e);
  296. }
  297. handleWheel = (e) => {
  298. this.foundation.handleWheel(e);
  299. }
  300. // 为什么通过 addEventListener 注册 wheel 事件而不是使用 onWheel 事件?
  301. // 因为 Passive Event Listeners(https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#improving_scrolling_performance_with_passive_listeners)
  302. // Passive Event Listeners 是一种优化技术,用于提高滚动性能。在默认情况下,浏览器会假设事件的监听器不会调用
  303. // preventDefault() 方法来阻止事件的默认行为,从而允许进行一些优化操作,例如滚动平滑。
  304. // 对于 Image 而言,如果使用触控板,双指朝不同方向分开放大图片,则需要 preventDefault 防止页面整体放大。
  305. // Why register wheel event through addEventListener instead of using onWheel event?
  306. // Because of Passive Event Listeners(an optimization technique used to improve scrolling performance. By default,
  307. // the browser will assume that event listeners will not call preventDefault() method to prevent the default behavior of the event,
  308. // allowing some optimization operations such as scroll smoothing.)
  309. // For Image, if we use the trackpad and spread your fingers in different directions to enlarge the image, we need to preventDefault
  310. // to prevent the page from being enlarged as a whole.
  311. registryImageWrapRef = (ref): void => {
  312. if (this.imageWrapRef) {
  313. (this.imageWrapRef as any).removeEventListener("wheel", this.handleWheel);
  314. }
  315. if (ref) {
  316. ref.addEventListener("wheel", this.handleWheel, { passive: false });
  317. }
  318. this.imageWrapRef = ref;
  319. };
  320. render() {
  321. const {
  322. getPopupContainer,
  323. closable,
  324. zIndex,
  325. visible,
  326. className,
  327. style,
  328. infinite,
  329. zoomStep,
  330. crossOrigin,
  331. prevTip,
  332. nextTip,
  333. zoomInTip,
  334. zoomOutTip,
  335. rotateTip,
  336. downloadTip,
  337. adaptiveTip,
  338. originTip,
  339. showTooltip,
  340. disableDownload,
  341. renderPreviewMenu,
  342. renderHeader,
  343. } = this.props;
  344. const { currentIndex, imgSrc, zoom, ratio, rotation, viewerVisible } = this.state;
  345. let wrapperStyle: {
  346. zIndex?: CSSProperties["zIndex"];
  347. position?: CSSProperties["position"]
  348. } = {
  349. zIndex,
  350. };
  351. if (getPopupContainer) {
  352. wrapperStyle = {
  353. zIndex,
  354. position: "static",
  355. };
  356. }
  357. const previewPrefixCls = `${prefixCls}-preview`;
  358. const previewWrapperCls = cls(previewPrefixCls,
  359. {
  360. [`${prefixCls}-hide`]: !visible,
  361. [`${previewPrefixCls}-popup`]: getPopupContainer,
  362. },
  363. className,
  364. );
  365. const hideViewerCls = !viewerVisible ? `${previewPrefixCls}-hide` : "";
  366. const total = imgSrc.length;
  367. const showPrev = total !== 1 && (infinite || currentIndex !== 0);
  368. const showNext = total !== 1 && (infinite || currentIndex !== total - 1);
  369. return (
  370. visible && <Portal
  371. getPopupContainer={getPopupContainer}
  372. style={wrapperStyle}
  373. >
  374. {/* eslint-disable-next-line jsx-a11y/no-static-element-interactions */}
  375. <div
  376. className={previewWrapperCls}
  377. style={style}
  378. onMouseDown={this.handleMouseDown}
  379. onMouseUp={this.handleMouseUp}
  380. ref={this.registryImageWrapRef}
  381. onMouseMove={this.handleMouseMove}
  382. >
  383. <Header ref={this.headerRef} className={cls(hideViewerCls)} onClose={this.handlePreviewClose} renderHeader={renderHeader} closable={closable}/>
  384. <PreviewImage
  385. ref={this.imageRef}
  386. src={imgSrc[currentIndex]}
  387. onZoom={this.handleZoomImage}
  388. disableDownload={disableDownload}
  389. setRatio={this.handleAdjustRatio}
  390. zoom={zoom}
  391. ratio={ratio}
  392. rotation={rotation}
  393. crossOrigin={crossOrigin}
  394. onError={this.onImageError}
  395. onLoad={this.onImageLoad}
  396. />
  397. {showPrev && (
  398. // eslint-disable-next-line jsx-a11y/click-events-have-key-events,jsx-a11y/no-static-element-interactions
  399. <div
  400. ref={this.leftIconRef}
  401. className={cls(`${previewPrefixCls}-icon`, `${previewPrefixCls}-prev`, hideViewerCls)}
  402. onClick={(): void => this.handleSwitchImage("prev")}
  403. >
  404. <IconArrowLeft size="large" />
  405. </div>
  406. )}
  407. {showNext && (
  408. // eslint-disable-next-line jsx-a11y/click-events-have-key-events,jsx-a11y/no-static-element-interactions
  409. <div
  410. ref={this.rightIconRef}
  411. className={cls(`${previewPrefixCls}-icon`, `${previewPrefixCls}-next`, hideViewerCls)}
  412. onClick={(): void => this.handleSwitchImage("next")}
  413. >
  414. <IconArrowRight size="large" />
  415. </div>
  416. )}
  417. <Footer
  418. forwardRef={this.footerRef}
  419. className={hideViewerCls}
  420. totalNum={total}
  421. curPage={currentIndex + 1}
  422. disabledPrev={!showPrev}
  423. disabledNext={!showNext}
  424. zoom={zoom * 100}
  425. step={zoomStep * 100}
  426. showTooltip={showTooltip}
  427. ratio={ratio}
  428. prevTip={prevTip}
  429. nextTip={nextTip}
  430. zIndex={zIndex}
  431. zoomInTip={zoomInTip}
  432. zoomOutTip={zoomOutTip}
  433. rotateTip={rotateTip}
  434. downloadTip={downloadTip}
  435. disableDownload={disableDownload}
  436. adaptiveTip={adaptiveTip}
  437. originTip={originTip}
  438. onPrev={(): void => this.handleSwitchImage("prev")}
  439. onNext={(): void => this.handleSwitchImage("next")}
  440. onZoomIn={this.handleZoomImage}
  441. onZoomOut={this.handleZoomImage}
  442. onDownload={this.handleDownload}
  443. onRotate={this.handleRotateImage}
  444. onAdjustRatio={this.handleAdjustRatio}
  445. renderPreviewMenu={renderPreviewMenu}
  446. />
  447. </div>
  448. </Portal>
  449. );
  450. }
  451. }