You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

450 lines
13 KiB

  1. import React from 'react';
  2. import PropTypes from 'prop-types';
  3. import IconButton from 'mastodon/components/icon_button';
  4. import { defineMessages, injectIntl } from 'react-intl';
  5. const messages = defineMessages({
  6. compress: { id: 'lightbox.compress', defaultMessage: 'Compress image view box' },
  7. expand: { id: 'lightbox.expand', defaultMessage: 'Expand image view box' },
  8. });
  9. const MIN_SCALE = 1;
  10. const MAX_SCALE = 4;
  11. const NAV_BAR_HEIGHT = 66;
  12. const getMidpoint = (p1, p2) => ({
  13. x: (p1.clientX + p2.clientX) / 2,
  14. y: (p1.clientY + p2.clientY) / 2,
  15. });
  16. const getDistance = (p1, p2) =>
  17. Math.sqrt(Math.pow(p1.clientX - p2.clientX, 2) + Math.pow(p1.clientY - p2.clientY, 2));
  18. const clamp = (min, max, value) => Math.min(max, Math.max(min, value));
  19. // Normalizing mousewheel speed across browsers
  20. // copy from: https://github.com/facebookarchive/fixed-data-table/blob/master/src/vendor_upstream/dom/normalizeWheel.js
  21. const normalizeWheel = event => {
  22. // Reasonable defaults
  23. const PIXEL_STEP = 10;
  24. const LINE_HEIGHT = 40;
  25. const PAGE_HEIGHT = 800;
  26. let sX = 0,
  27. sY = 0, // spinX, spinY
  28. pX = 0,
  29. pY = 0; // pixelX, pixelY
  30. // Legacy
  31. if ('detail' in event) {
  32. sY = event.detail;
  33. }
  34. if ('wheelDelta' in event) {
  35. sY = -event.wheelDelta / 120;
  36. }
  37. if ('wheelDeltaY' in event) {
  38. sY = -event.wheelDeltaY / 120;
  39. }
  40. if ('wheelDeltaX' in event) {
  41. sX = -event.wheelDeltaX / 120;
  42. }
  43. // side scrolling on FF with DOMMouseScroll
  44. if ('axis' in event && event.axis === event.HORIZONTAL_AXIS) {
  45. sX = sY;
  46. sY = 0;
  47. }
  48. pX = sX * PIXEL_STEP;
  49. pY = sY * PIXEL_STEP;
  50. if ('deltaY' in event) {
  51. pY = event.deltaY;
  52. }
  53. if ('deltaX' in event) {
  54. pX = event.deltaX;
  55. }
  56. if ((pX || pY) && event.deltaMode) {
  57. if (event.deltaMode === 1) { // delta in LINE units
  58. pX *= LINE_HEIGHT;
  59. pY *= LINE_HEIGHT;
  60. } else { // delta in PAGE units
  61. pX *= PAGE_HEIGHT;
  62. pY *= PAGE_HEIGHT;
  63. }
  64. }
  65. // Fall-back if spin cannot be determined
  66. if (pX && !sX) {
  67. sX = (pX < 1) ? -1 : 1;
  68. }
  69. if (pY && !sY) {
  70. sY = (pY < 1) ? -1 : 1;
  71. }
  72. return {
  73. spinX: sX,
  74. spinY: sY,
  75. pixelX: pX,
  76. pixelY: pY,
  77. };
  78. };
  79. export default @injectIntl
  80. class ZoomableImage extends React.PureComponent {
  81. static propTypes = {
  82. alt: PropTypes.string,
  83. src: PropTypes.string.isRequired,
  84. width: PropTypes.number,
  85. height: PropTypes.number,
  86. onClick: PropTypes.func,
  87. zoomButtonHidden: PropTypes.bool,
  88. intl: PropTypes.object.isRequired,
  89. }
  90. static defaultProps = {
  91. alt: '',
  92. width: null,
  93. height: null,
  94. };
  95. state = {
  96. scale: MIN_SCALE,
  97. zoomMatrix: {
  98. type: null, // 'width' 'height'
  99. fullScreen: null, // bool
  100. rate: null, // full screen scale rate
  101. clientWidth: null,
  102. clientHeight: null,
  103. offsetWidth: null,
  104. offsetHeight: null,
  105. clientHeightFixed: null,
  106. scrollTop: null,
  107. scrollLeft: null,
  108. translateX: null,
  109. translateY: null,
  110. },
  111. zoomState: 'expand', // 'expand' 'compress'
  112. navigationHidden: false,
  113. dragPosition: { top: 0, left: 0, x: 0, y: 0 },
  114. dragged: false,
  115. lockScroll: { x: 0, y: 0 },
  116. lockTranslate: { x: 0, y: 0 },
  117. }
  118. removers = [];
  119. container = null;
  120. image = null;
  121. lastTouchEndTime = 0;
  122. lastDistance = 0;
  123. componentDidMount () {
  124. let handler = this.handleTouchStart;
  125. this.container.addEventListener('touchstart', handler);
  126. this.removers.push(() => this.container.removeEventListener('touchstart', handler));
  127. handler = this.handleTouchMove;
  128. // on Chrome 56+, touch event listeners will default to passive
  129. // https://www.chromestatus.com/features/5093566007214080
  130. this.container.addEventListener('touchmove', handler, { passive: false });
  131. this.removers.push(() => this.container.removeEventListener('touchend', handler));
  132. handler = this.mouseDownHandler;
  133. this.container.addEventListener('mousedown', handler);
  134. this.removers.push(() => this.container.removeEventListener('mousedown', handler));
  135. handler = this.mouseWheelHandler;
  136. this.container.addEventListener('wheel', handler);
  137. this.removers.push(() => this.container.removeEventListener('wheel', handler));
  138. // Old Chrome
  139. this.container.addEventListener('mousewheel', handler);
  140. this.removers.push(() => this.container.removeEventListener('mousewheel', handler));
  141. // Old Firefox
  142. this.container.addEventListener('DOMMouseScroll', handler);
  143. this.removers.push(() => this.container.removeEventListener('DOMMouseScroll', handler));
  144. this.initZoomMatrix();
  145. }
  146. componentWillUnmount () {
  147. this.removeEventListeners();
  148. }
  149. componentDidUpdate () {
  150. this.setState({ zoomState: this.state.scale >= this.state.zoomMatrix.rate ? 'compress' : 'expand' });
  151. if (this.state.scale === MIN_SCALE) {
  152. this.container.style.removeProperty('cursor');
  153. }
  154. }
  155. UNSAFE_componentWillReceiveProps () {
  156. // reset when slide to next image
  157. if (this.props.zoomButtonHidden) {
  158. this.setState({
  159. scale: MIN_SCALE,
  160. lockTranslate: { x: 0, y: 0 },
  161. }, () => {
  162. this.container.scrollLeft = 0;
  163. this.container.scrollTop = 0;
  164. });
  165. }
  166. }
  167. removeEventListeners () {
  168. this.removers.forEach(listeners => listeners());
  169. this.removers = [];
  170. }
  171. mouseWheelHandler = e => {
  172. e.preventDefault();
  173. const event = normalizeWheel(e);
  174. if (this.state.zoomMatrix.type === 'width') {
  175. // full width, scroll vertical
  176. this.container.scrollTop = Math.max(this.container.scrollTop + event.pixelY, this.state.lockScroll.y);
  177. } else {
  178. // full height, scroll horizontal
  179. this.container.scrollLeft = Math.max(this.container.scrollLeft + event.pixelY, this.state.lockScroll.x);
  180. }
  181. // lock horizontal scroll
  182. this.container.scrollLeft = Math.max(this.container.scrollLeft + event.pixelX, this.state.lockScroll.x);
  183. }
  184. mouseDownHandler = e => {
  185. this.container.style.cursor = 'grabbing';
  186. this.container.style.userSelect = 'none';
  187. this.setState({ dragPosition: {
  188. left: this.container.scrollLeft,
  189. top: this.container.scrollTop,
  190. // Get the current mouse position
  191. x: e.clientX,
  192. y: e.clientY,
  193. } });
  194. this.image.addEventListener('mousemove', this.mouseMoveHandler);
  195. this.image.addEventListener('mouseup', this.mouseUpHandler);
  196. }
  197. mouseMoveHandler = e => {
  198. const dx = e.clientX - this.state.dragPosition.x;
  199. const dy = e.clientY - this.state.dragPosition.y;
  200. this.container.scrollLeft = Math.max(this.state.dragPosition.left - dx, this.state.lockScroll.x);
  201. this.container.scrollTop = Math.max(this.state.dragPosition.top - dy, this.state.lockScroll.y);
  202. this.setState({ dragged: true });
  203. }
  204. mouseUpHandler = () => {
  205. this.container.style.cursor = 'grab';
  206. this.container.style.removeProperty('user-select');
  207. this.image.removeEventListener('mousemove', this.mouseMoveHandler);
  208. this.image.removeEventListener('mouseup', this.mouseUpHandler);
  209. }
  210. handleTouchStart = e => {
  211. if (e.touches.length !== 2) return;
  212. this.lastDistance = getDistance(...e.touches);
  213. }
  214. handleTouchMove = e => {
  215. const { scrollTop, scrollHeight, clientHeight } = this.container;
  216. if (e.touches.length === 1 && scrollTop !== scrollHeight - clientHeight) {
  217. // prevent propagating event to MediaModal
  218. e.stopPropagation();
  219. return;
  220. }
  221. if (e.touches.length !== 2) return;
  222. e.preventDefault();
  223. e.stopPropagation();
  224. const distance = getDistance(...e.touches);
  225. const midpoint = getMidpoint(...e.touches);
  226. const _MAX_SCALE = Math.max(MAX_SCALE, this.state.zoomMatrix.rate);
  227. const scale = clamp(MIN_SCALE, _MAX_SCALE, this.state.scale * distance / this.lastDistance);
  228. this.zoom(scale, midpoint);
  229. this.lastMidpoint = midpoint;
  230. this.lastDistance = distance;
  231. }
  232. zoom(nextScale, midpoint) {
  233. const { scale, zoomMatrix } = this.state;
  234. const { scrollLeft, scrollTop } = this.container;
  235. // math memo:
  236. // x = (scrollLeft + midpoint.x) / scrollWidth
  237. // x' = (nextScrollLeft + midpoint.x) / nextScrollWidth
  238. // scrollWidth = clientWidth * scale
  239. // scrollWidth' = clientWidth * nextScale
  240. // Solve x = x' for nextScrollLeft
  241. const nextScrollLeft = (scrollLeft + midpoint.x) * nextScale / scale - midpoint.x;
  242. const nextScrollTop = (scrollTop + midpoint.y) * nextScale / scale - midpoint.y;
  243. this.setState({ scale: nextScale }, () => {
  244. this.container.scrollLeft = nextScrollLeft;
  245. this.container.scrollTop = nextScrollTop;
  246. // reset the translateX/Y constantly
  247. if (nextScale < zoomMatrix.rate) {
  248. this.setState({
  249. lockTranslate: {
  250. x: zoomMatrix.fullScreen ? 0 : zoomMatrix.translateX * ((nextScale - MIN_SCALE) / (zoomMatrix.rate - MIN_SCALE)),
  251. y: zoomMatrix.fullScreen ? 0 : zoomMatrix.translateY * ((nextScale - MIN_SCALE) / (zoomMatrix.rate - MIN_SCALE)),
  252. },
  253. });
  254. }
  255. });
  256. }
  257. handleClick = e => {
  258. // don't propagate event to MediaModal
  259. e.stopPropagation();
  260. const dragged = this.state.dragged;
  261. this.setState({ dragged: false });
  262. if (dragged) return;
  263. const handler = this.props.onClick;
  264. if (handler) handler();
  265. this.setState({ navigationHidden: !this.state.navigationHidden });
  266. }
  267. handleMouseDown = e => {
  268. e.preventDefault();
  269. }
  270. initZoomMatrix = () => {
  271. const { width, height } = this.props;
  272. const { clientWidth, clientHeight } = this.container;
  273. const { offsetWidth, offsetHeight } = this.image;
  274. const clientHeightFixed = clientHeight - NAV_BAR_HEIGHT;
  275. const type = width / height < clientWidth / clientHeightFixed ? 'width' : 'height';
  276. const fullScreen = type === 'width' ? width > clientWidth : height > clientHeightFixed;
  277. const rate = type === 'width' ? Math.min(clientWidth, width) / offsetWidth : Math.min(clientHeightFixed, height) / offsetHeight;
  278. const scrollTop = type === 'width' ? (clientHeight - offsetHeight) / 2 - NAV_BAR_HEIGHT : (clientHeightFixed - offsetHeight) / 2;
  279. const scrollLeft = (clientWidth - offsetWidth) / 2;
  280. const translateX = type === 'width' ? (width - offsetWidth) / (2 * rate) : 0;
  281. const translateY = type === 'height' ? (height - offsetHeight) / (2 * rate) : 0;
  282. this.setState({
  283. zoomMatrix: {
  284. type: type,
  285. fullScreen: fullScreen,
  286. rate: rate,
  287. clientWidth: clientWidth,
  288. clientHeight: clientHeight,
  289. offsetWidth: offsetWidth,
  290. offsetHeight: offsetHeight,
  291. clientHeightFixed: clientHeightFixed,
  292. scrollTop: scrollTop,
  293. scrollLeft: scrollLeft,
  294. translateX: translateX,
  295. translateY: translateY,
  296. },
  297. });
  298. }
  299. handleZoomClick = e => {
  300. e.preventDefault();
  301. e.stopPropagation();
  302. const { scale, zoomMatrix } = this.state;
  303. if ( scale >= zoomMatrix.rate ) {
  304. this.setState({
  305. scale: MIN_SCALE,
  306. lockScroll: {
  307. x: 0,
  308. y: 0,
  309. },
  310. lockTranslate: {
  311. x: 0,
  312. y: 0,
  313. },
  314. }, () => {
  315. this.container.scrollLeft = 0;
  316. this.container.scrollTop = 0;
  317. });
  318. } else {
  319. this.setState({
  320. scale: zoomMatrix.rate,
  321. lockScroll: {
  322. x: zoomMatrix.scrollLeft,
  323. y: zoomMatrix.scrollTop,
  324. },
  325. lockTranslate: {
  326. x: zoomMatrix.fullScreen ? 0 : zoomMatrix.translateX,
  327. y: zoomMatrix.fullScreen ? 0 : zoomMatrix.translateY,
  328. },
  329. }, () => {
  330. this.container.scrollLeft = zoomMatrix.scrollLeft;
  331. this.container.scrollTop = zoomMatrix.scrollTop;
  332. });
  333. }
  334. this.container.style.cursor = 'grab';
  335. this.container.style.removeProperty('user-select');
  336. }
  337. setContainerRef = c => {
  338. this.container = c;
  339. }
  340. setImageRef = c => {
  341. this.image = c;
  342. }
  343. render () {
  344. const { alt, src, width, height, intl } = this.props;
  345. const { scale, lockTranslate } = this.state;
  346. const overflow = scale === MIN_SCALE ? 'hidden' : 'scroll';
  347. const zoomButtonShouldHide = this.state.navigationHidden || this.props.zoomButtonHidden || this.state.zoomMatrix.rate <= MIN_SCALE ? 'media-modal__zoom-button--hidden' : '';
  348. const zoomButtonTitle = this.state.zoomState === 'compress' ? intl.formatMessage(messages.compress) : intl.formatMessage(messages.expand);
  349. return (
  350. <React.Fragment>
  351. <IconButton
  352. className={`media-modal__zoom-button ${zoomButtonShouldHide}`}
  353. title={zoomButtonTitle}
  354. icon={this.state.zoomState}
  355. onClick={this.handleZoomClick}
  356. size={40}
  357. style={{
  358. fontSize: '30px', /* Fontawesome's fa-compress fa-expand is larger than fa-close */
  359. }}
  360. />
  361. <div
  362. className='zoomable-image'
  363. ref={this.setContainerRef}
  364. style={{ overflow }}
  365. >
  366. <img
  367. role='presentation'
  368. ref={this.setImageRef}
  369. alt={alt}
  370. title={alt}
  371. src={src}
  372. width={width}
  373. height={height}
  374. style={{
  375. transform: `scale(${scale}) translate(-${lockTranslate.x}px, -${lockTranslate.y}px)`,
  376. transformOrigin: '0 0',
  377. }}
  378. draggable={false}
  379. onClick={this.handleClick}
  380. onMouseDown={this.handleMouseDown}
  381. />
  382. </div>
  383. </React.Fragment>
  384. );
  385. }
  386. }