previewInner.tsx 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441
  1. import React, { CSSProperties } from "react";
  2. import BaseComponent from "../_base/baseComponent";
  3. import { PreviewProps as PreviewInnerProps, PreviewInnerStates } from "./interface";
  4. import PropTypes from "prop-types";
  5. import { cssClasses } 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. const prefixCls = cssClasses.PREFIX;
  17. let startMouseDown = { x: 0, y: 0 };
  18. let mouseActiveTime: number = null;
  19. let stopTiming = false;
  20. let timer = null;
  21. // let bodyOverflowValue = document.body.style.overflow;
  22. export default class PreviewInner extends BaseComponent<PreviewInnerProps, PreviewInnerStates> {
  23. static contextType = PreviewContext;
  24. static propTypes = {
  25. style: PropTypes.object,
  26. className: PropTypes.string,
  27. visible: PropTypes.bool,
  28. src: PropTypes.oneOfType([PropTypes.string, PropTypes.array]),
  29. currentIndex: PropTypes.number,
  30. defaultIndex: PropTypes.number,
  31. defaultVisible: PropTypes.bool,
  32. maskClosable: PropTypes.bool,
  33. closable: PropTypes.bool,
  34. zoomStep: PropTypes.number,
  35. infinite: PropTypes.bool,
  36. showTooltip: PropTypes.bool,
  37. closeOnEsc: PropTypes.bool,
  38. prevTip: PropTypes.string,
  39. nextTip: PropTypes.string,
  40. zoomInTip: PropTypes.string,
  41. zoomOutTip: PropTypes.string,
  42. downloadTip: PropTypes.string,
  43. adaptiveTip: PropTypes.string,
  44. originTip: PropTypes.string,
  45. lazyLoad: PropTypes.bool,
  46. preLoad: PropTypes.bool,
  47. preLoadGap: PropTypes.number,
  48. disableDownload: PropTypes.bool,
  49. viewerVisibleDelay: PropTypes.number,
  50. zIndex: PropTypes.number,
  51. renderHeader: PropTypes.func,
  52. renderPreviewMenu: PropTypes.func,
  53. getPopupContainer: PropTypes.func,
  54. onVisibleChange: PropTypes.func,
  55. onChange: PropTypes.func,
  56. onClose: PropTypes.func,
  57. onZoomIn: PropTypes.func,
  58. onZoomOut: PropTypes.func,
  59. onPrev: PropTypes.func,
  60. onNext: PropTypes.func,
  61. onDownload: PropTypes.func,
  62. onRatioChange: PropTypes.func,
  63. onRotateLeft: PropTypes.func,
  64. }
  65. static defaultProps = {
  66. showTooltip: false,
  67. zoomStep: 0.1,
  68. infinite: false,
  69. closeOnEsc: true,
  70. lazyLoad: false,
  71. preLoad: true,
  72. preLoadGap: 2,
  73. zIndex: 1000,
  74. maskClosable: true,
  75. viewerVisibleDelay: 10000,
  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. getMouseActiveTime: () => {
  143. return mouseActiveTime;
  144. },
  145. getStopTiming: () => {
  146. return stopTiming;
  147. },
  148. setStopTiming: (value) => {
  149. stopTiming = value;
  150. },
  151. getStartMouseDown: () => {
  152. return startMouseDown;
  153. },
  154. setStartMouseDown: (x: number, y: number) => {
  155. startMouseDown = { x, y };
  156. },
  157. setMouseActiveTime: (time: number) => {
  158. mouseActiveTime = time;
  159. },
  160. getSetDownloadFunc: () => {
  161. return this.context?.setDownloadName ?? this.props.setDownloadName;
  162. }
  163. };
  164. }
  165. timer;
  166. context: PreviewContextProps;
  167. foundation: PreviewInnerFoundation;
  168. constructor(props: PreviewInnerProps) {
  169. super(props);
  170. this.state = {
  171. imgSrc: [],
  172. imgLoadStatus: new Map(),
  173. zoom: 0.1,
  174. currentIndex: 0,
  175. ratio: "adaptation",
  176. rotation: 0,
  177. viewerVisible: true,
  178. visible: false,
  179. preloadAfterVisibleChange: true,
  180. direction: "",
  181. };
  182. this.foundation = new PreviewInnerFoundation(this.adapter);
  183. this.bodyOverflow = '';
  184. this.originBodyWidth = '100%';
  185. this.scrollBarWidth = 0;
  186. }
  187. static getDerivedStateFromProps(props: PreviewInnerProps, state: PreviewInnerStates) {
  188. const willUpdateStates: Partial<PreviewInnerStates> = {};
  189. let src = [];
  190. if (props.visible) {
  191. // if src in props
  192. src = Array.isArray(props.src) ? props.src : [props.src];
  193. }
  194. if (!isEqual(src, state.imgSrc)) {
  195. willUpdateStates.imgSrc = src;
  196. }
  197. if (props.visible !== state.visible) {
  198. willUpdateStates.visible = props.visible;
  199. if (props.visible) {
  200. willUpdateStates.preloadAfterVisibleChange = true;
  201. }
  202. }
  203. if ("currentIndex" in props && props.currentIndex !== state.currentIndex) {
  204. willUpdateStates.currentIndex = props.currentIndex;
  205. // ratio will set to adaptation when change picture,
  206. // attention: If the ratio is controlled, the ratio should not change as the index changes
  207. willUpdateStates.ratio = 'adaptation';
  208. }
  209. return willUpdateStates;
  210. }
  211. componentDidMount() {
  212. this.scrollBarWidth = getScrollbarWidth();
  213. this.originBodyWidth = document.body.style.width;
  214. if (this.props.visible) {
  215. this.foundation.beforeShow();
  216. }
  217. }
  218. componentDidUpdate(prevProps: PreviewInnerProps, prevState: PreviewInnerStates) {
  219. if (prevState.visible !== this.props.visible && this.props.visible) {
  220. mouseActiveTime = new Date().getTime();
  221. timer && clearInterval(timer);
  222. timer = setInterval(this.viewVisibleChange, 1000);
  223. }
  224. // hide => show
  225. if (!prevProps.visible && this.props.visible) {
  226. this.foundation.beforeShow();
  227. }
  228. // show => hide
  229. if (prevProps.visible && !this.props.visible) {
  230. this.foundation.afterHide();
  231. }
  232. }
  233. componentWillUnmount() {
  234. timer && clearInterval(timer);
  235. }
  236. isInGroup() {
  237. return Boolean(this.context && this.context.isGroup);
  238. }
  239. viewVisibleChange = () => {
  240. this.foundation.handleViewVisibleChange();
  241. }
  242. handleSwitchImage = (direction: string) => {
  243. this.foundation.handleSwitchImage(direction);
  244. }
  245. handleDownload = () => {
  246. this.foundation.handleDownload();
  247. }
  248. handlePreviewClose = () => {
  249. this.foundation.handlePreviewClose();
  250. }
  251. handleAdjustRatio = (type: RatioType) => {
  252. this.foundation.handleAdjustRatio(type);
  253. }
  254. handleRotateImage = (direction) => {
  255. this.foundation.handleRotateImage(direction);
  256. }
  257. handleZoomImage = (newZoom: number) => {
  258. this.foundation.handleZoomImage(newZoom);
  259. }
  260. handleMouseUp = (e): void => {
  261. this.foundation.handleMouseUp(e.nativeEvent);
  262. }
  263. handleMouseMove = (e): void => {
  264. this.foundation.handleMouseMove(e);
  265. }
  266. handleMouseEvent = (e, event: string) => {
  267. this.foundation.handleMouseMoveEvent(e, event);
  268. }
  269. handleKeyDown = (e: KeyboardEvent) => {
  270. this.foundation.handleKeyDown(e);
  271. };
  272. onImageError = () => {
  273. this.foundation.preloadSingleImage();
  274. }
  275. onImageLoad = (src) => {
  276. this.foundation.onImageLoad(src);
  277. }
  278. handleMouseDown = (e): void => {
  279. this.foundation.handleMouseDown(e);
  280. }
  281. render() {
  282. const {
  283. getPopupContainer,
  284. zIndex,
  285. visible,
  286. className,
  287. style,
  288. infinite,
  289. zoomStep,
  290. crossOrigin,
  291. prevTip,
  292. nextTip,
  293. zoomInTip,
  294. zoomOutTip,
  295. rotateTip,
  296. downloadTip,
  297. adaptiveTip,
  298. originTip,
  299. showTooltip,
  300. disableDownload,
  301. renderPreviewMenu,
  302. renderHeader,
  303. } = this.props;
  304. const { currentIndex, imgSrc, zoom, ratio, rotation, viewerVisible } = this.state;
  305. let wrapperStyle: {
  306. zIndex?: CSSProperties["zIndex"];
  307. position?: CSSProperties["position"]
  308. } = {
  309. zIndex,
  310. };
  311. if (getPopupContainer) {
  312. wrapperStyle = {
  313. zIndex,
  314. position: "static",
  315. };
  316. }
  317. const previewPrefixCls = `${prefixCls}-preview`;
  318. const previewWrapperCls = cls(previewPrefixCls,
  319. {
  320. [`${prefixCls}-hide`]: !visible,
  321. [`${previewPrefixCls}-popup`]: getPopupContainer,
  322. },
  323. className,
  324. );
  325. const hideViewerCls = !viewerVisible ? `${previewPrefixCls}-hide` : "";
  326. const total = imgSrc.length;
  327. const showPrev = total !== 1 && (infinite || currentIndex !== 0);
  328. const showNext = total !== 1 && (infinite || currentIndex !== total - 1);
  329. return (
  330. <Portal
  331. getPopupContainer={getPopupContainer}
  332. style={wrapperStyle}
  333. >
  334. {visible &&
  335. // eslint-disable-next-line jsx-a11y/mouse-events-have-key-events,jsx-a11y/no-static-element-interactions
  336. <div
  337. className={previewWrapperCls}
  338. style={style}
  339. onMouseDown={this.handleMouseDown}
  340. onMouseUp={this.handleMouseUp}
  341. onMouseMove={this.handleMouseMove}
  342. onMouseOver={(e): void => this.handleMouseEvent(e.nativeEvent, "over")}
  343. onMouseOut={(e): void => this.handleMouseEvent(e.nativeEvent, "out")}
  344. >
  345. <Header className={cls(hideViewerCls)} onClose={this.handlePreviewClose} renderHeader={renderHeader} />
  346. <PreviewImage
  347. src={imgSrc[currentIndex]}
  348. onZoom={this.handleZoomImage}
  349. disableDownload={disableDownload}
  350. setRatio={this.handleAdjustRatio}
  351. zoom={zoom}
  352. ratio={ratio}
  353. zoomStep={zoomStep}
  354. rotation={rotation}
  355. crossOrigin={crossOrigin}
  356. onError={this.onImageError}
  357. onLoad={this.onImageLoad}
  358. />
  359. {showPrev && (
  360. // eslint-disable-next-line jsx-a11y/click-events-have-key-events,jsx-a11y/no-static-element-interactions
  361. <div
  362. className={cls(`${previewPrefixCls}-icon`, `${previewPrefixCls}-prev`, hideViewerCls)}
  363. onClick={(): void => this.handleSwitchImage("prev")}
  364. >
  365. <IconArrowLeft size="large" />
  366. </div>
  367. )}
  368. {showNext && (
  369. // eslint-disable-next-line jsx-a11y/click-events-have-key-events,jsx-a11y/no-static-element-interactions
  370. <div
  371. className={cls(`${previewPrefixCls}-icon`, `${previewPrefixCls}-next`, hideViewerCls)}
  372. onClick={(): void => this.handleSwitchImage("next")}
  373. >
  374. <IconArrowRight size="large" />
  375. </div>
  376. )}
  377. <Footer
  378. className={hideViewerCls}
  379. totalNum={total}
  380. curPage={currentIndex + 1}
  381. disabledPrev={!showPrev}
  382. disabledNext={!showNext}
  383. zoom={zoom * 100}
  384. step={zoomStep * 100}
  385. showTooltip={showTooltip}
  386. ratio={ratio}
  387. prevTip={prevTip}
  388. nextTip={nextTip}
  389. zoomInTip={zoomInTip}
  390. zoomOutTip={zoomOutTip}
  391. rotateTip={rotateTip}
  392. downloadTip={downloadTip}
  393. disableDownload={disableDownload}
  394. adaptiveTip={adaptiveTip}
  395. originTip={originTip}
  396. onPrev={(): void => this.handleSwitchImage("prev")}
  397. onNext={(): void => this.handleSwitchImage("next")}
  398. onZoomIn={this.handleZoomImage}
  399. onZoomOut={this.handleZoomImage}
  400. onDownload={this.handleDownload}
  401. onRotate={this.handleRotateImage}
  402. onAdjustRatio={this.handleAdjustRatio}
  403. renderPreviewMenu={renderPreviewMenu}
  404. />
  405. </div>}
  406. </Portal>
  407. );
  408. }
  409. }