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.

417 lines
12 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, // 'full-width' 'full-height'
  99. rate: null, // full screen scale rate
  100. clientWidth: null,
  101. clientHeight: null,
  102. offsetWidth: null,
  103. offsetHeight: null,
  104. clientHeightFixed: null,
  105. scrollTop: null,
  106. scrollLeft: null,
  107. },
  108. zoomState: 'expand', // 'expand' 'compress'
  109. navigationHidden: false,
  110. dragPosition: { top: 0, left: 0, x: 0, y: 0 },
  111. dragged: false,
  112. lockScroll: { x: 0, y: 0 },
  113. }
  114. removers = [];
  115. container = null;
  116. image = null;
  117. lastTouchEndTime = 0;
  118. lastDistance = 0;
  119. componentDidMount () {
  120. let handler = this.handleTouchStart;
  121. this.container.addEventListener('touchstart', handler);
  122. this.removers.push(() => this.container.removeEventListener('touchstart', handler));
  123. handler = this.handleTouchMove;
  124. // on Chrome 56+, touch event listeners will default to passive
  125. // https://www.chromestatus.com/features/5093566007214080
  126. this.container.addEventListener('touchmove', handler, { passive: false });
  127. this.removers.push(() => this.container.removeEventListener('touchend', handler));
  128. handler = this.mouseDownHandler;
  129. this.container.addEventListener('mousedown', handler);
  130. this.removers.push(() => this.container.removeEventListener('mousedown', handler));
  131. handler = this.mouseWheelHandler;
  132. this.container.addEventListener('wheel', handler);
  133. this.removers.push(() => this.container.removeEventListener('wheel', handler));
  134. // Old Chrome
  135. this.container.addEventListener('mousewheel', handler);
  136. this.removers.push(() => this.container.removeEventListener('mousewheel', handler));
  137. // Old Firefox
  138. this.container.addEventListener('DOMMouseScroll', handler);
  139. this.removers.push(() => this.container.removeEventListener('DOMMouseScroll', handler));
  140. this.initZoomMatrix();
  141. }
  142. componentWillUnmount () {
  143. this.removeEventListeners();
  144. }
  145. componentDidUpdate () {
  146. if (this.props.zoomButtonHidden) {
  147. this.setState({ scale: MIN_SCALE }, () => {
  148. this.container.scrollLeft = 0;
  149. this.container.scrollTop = 0;
  150. });
  151. }
  152. this.setState({ zoomState: this.state.scale >= this.state.zoomMatrix.rate ? 'compress' : 'expand' });
  153. if (this.state.scale === 1) {
  154. this.container.style.removeProperty('cursor');
  155. }
  156. }
  157. removeEventListeners () {
  158. this.removers.forEach(listeners => listeners());
  159. this.removers = [];
  160. }
  161. mouseWheelHandler = e => {
  162. e.preventDefault();
  163. const event = normalizeWheel(e);
  164. if (this.state.zoomMatrix.type === 'full-width') {
  165. // full width, scroll vertical
  166. this.container.scrollTop = Math.max(this.container.scrollTop + event.pixelY, this.state.lockScroll.y);
  167. } else {
  168. // full height, scroll horizontal
  169. this.container.scrollLeft = Math.max(this.container.scrollLeft + event.pixelY, this.state.lockScroll.x);
  170. }
  171. // lock horizontal scroll
  172. this.container.scrollLeft = Math.max(this.container.scrollLeft + event.pixelX, this.state.lockScroll.x);
  173. }
  174. mouseDownHandler = e => {
  175. this.container.style.cursor = 'grabbing';
  176. this.container.style.userSelect = 'none';
  177. this.setState({ dragPosition: {
  178. left: this.container.scrollLeft,
  179. top: this.container.scrollTop,
  180. // Get the current mouse position
  181. x: e.clientX,
  182. y: e.clientY,
  183. } });
  184. this.image.addEventListener('mousemove', this.mouseMoveHandler);
  185. this.image.addEventListener('mouseup', this.mouseUpHandler);
  186. }
  187. mouseMoveHandler = e => {
  188. const dx = e.clientX - this.state.dragPosition.x;
  189. const dy = e.clientY - this.state.dragPosition.y;
  190. this.container.scrollLeft = Math.max(this.state.dragPosition.left - dx, this.state.lockScroll.x);
  191. this.container.scrollTop = Math.max(this.state.dragPosition.top - dy, this.state.lockScroll.y);
  192. this.setState({ dragged: true });
  193. }
  194. mouseUpHandler = () => {
  195. this.container.style.cursor = 'grab';
  196. this.container.style.removeProperty('user-select');
  197. this.image.removeEventListener('mousemove', this.mouseMoveHandler);
  198. this.image.removeEventListener('mouseup', this.mouseUpHandler);
  199. }
  200. handleTouchStart = e => {
  201. if (e.touches.length !== 2) return;
  202. this.lastDistance = getDistance(...e.touches);
  203. }
  204. handleTouchMove = e => {
  205. const { scrollTop, scrollHeight, clientHeight } = this.container;
  206. if (e.touches.length === 1 && scrollTop !== scrollHeight - clientHeight) {
  207. // prevent propagating event to MediaModal
  208. e.stopPropagation();
  209. return;
  210. }
  211. if (e.touches.length !== 2) return;
  212. e.preventDefault();
  213. e.stopPropagation();
  214. const distance = getDistance(...e.touches);
  215. const midpoint = getMidpoint(...e.touches);
  216. const _MAX_SCALE = Math.max(MAX_SCALE, this.state.zoomMatrix.rate);
  217. const scale = clamp(MIN_SCALE, _MAX_SCALE, this.state.scale * distance / this.lastDistance);
  218. this.zoom(scale, midpoint);
  219. this.lastMidpoint = midpoint;
  220. this.lastDistance = distance;
  221. }
  222. zoom(nextScale, midpoint) {
  223. const { scale } = this.state;
  224. const { scrollLeft, scrollTop } = this.container;
  225. // math memo:
  226. // x = (scrollLeft + midpoint.x) / scrollWidth
  227. // x' = (nextScrollLeft + midpoint.x) / nextScrollWidth
  228. // scrollWidth = clientWidth * scale
  229. // scrollWidth' = clientWidth * nextScale
  230. // Solve x = x' for nextScrollLeft
  231. const nextScrollLeft = (scrollLeft + midpoint.x) * nextScale / scale - midpoint.x;
  232. const nextScrollTop = (scrollTop + midpoint.y) * nextScale / scale - midpoint.y;
  233. this.setState({ scale: nextScale }, () => {
  234. this.container.scrollLeft = nextScrollLeft;
  235. this.container.scrollTop = nextScrollTop;
  236. });
  237. }
  238. handleClick = e => {
  239. // don't propagate event to MediaModal
  240. e.stopPropagation();
  241. const dragged = this.state.dragged;
  242. this.setState({ dragged: false });
  243. if (dragged) return;
  244. const handler = this.props.onClick;
  245. if (handler) handler();
  246. this.setState({ navigationHidden: !this.state.navigationHidden });
  247. }
  248. handleMouseDown = e => {
  249. e.preventDefault();
  250. }
  251. initZoomMatrix = () => {
  252. const { width, height } = this.props;
  253. const { clientWidth, clientHeight } = this.container;
  254. const { offsetWidth, offsetHeight } = this.image;
  255. const clientHeightFixed = clientHeight - NAV_BAR_HEIGHT;
  256. const type = width/height < clientWidth / clientHeightFixed ? 'full-width' : 'full-height';
  257. const rate = type === 'full-width' ? clientWidth / offsetWidth : clientHeightFixed / offsetHeight;
  258. const scrollTop = type === 'full-width' ? (clientHeight - offsetHeight) / 2 - NAV_BAR_HEIGHT : (clientHeightFixed - offsetHeight) / 2;
  259. const scrollLeft = (clientWidth - offsetWidth) / 2;
  260. this.setState({
  261. zoomMatrix: {
  262. type: type,
  263. rate: rate,
  264. clientWidth: clientWidth,
  265. clientHeight: clientHeight,
  266. offsetWidth: offsetWidth,
  267. offsetHeight: offsetHeight,
  268. clientHeightFixed: clientHeightFixed,
  269. scrollTop: scrollTop,
  270. scrollLeft: scrollLeft,
  271. },
  272. });
  273. }
  274. handleZoomClick = e => {
  275. e.preventDefault();
  276. e.stopPropagation();
  277. const { scale, zoomMatrix } = this.state;
  278. if ( scale >= zoomMatrix.rate ) {
  279. this.setState({
  280. scale: MIN_SCALE,
  281. lockScroll: {
  282. x: 0,
  283. y: 0,
  284. },
  285. }, () => {
  286. this.container.scrollLeft = 0;
  287. this.container.scrollTop = 0;
  288. });
  289. } else {
  290. this.setState({
  291. scale: zoomMatrix.rate,
  292. lockScroll: {
  293. x: zoomMatrix.scrollLeft,
  294. y: zoomMatrix.scrollTop,
  295. },
  296. }, () => {
  297. this.container.scrollLeft = zoomMatrix.scrollLeft;
  298. this.container.scrollTop = zoomMatrix.scrollTop;
  299. });
  300. }
  301. this.container.style.cursor = 'grab';
  302. this.container.style.removeProperty('user-select');
  303. }
  304. setContainerRef = c => {
  305. this.container = c;
  306. }
  307. setImageRef = c => {
  308. this.image = c;
  309. }
  310. render () {
  311. const { alt, src, width, height, intl } = this.props;
  312. const { scale } = this.state;
  313. const overflow = scale === 1 ? 'hidden' : 'scroll';
  314. const zoomButtonSshouldHide = !this.state.navigationHidden && !this.props.zoomButtonHidden ? '' : 'media-modal__zoom-button--hidden';
  315. const zoomButtonTitle = this.state.zoomState === 'compress' ? intl.formatMessage(messages.compress) : intl.formatMessage(messages.expand);
  316. return (
  317. <React.Fragment>
  318. <IconButton
  319. className={`media-modal__zoom-button ${zoomButtonSshouldHide}`}
  320. title={zoomButtonTitle}
  321. icon={this.state.zoomState}
  322. onClick={this.handleZoomClick}
  323. size={40}
  324. style={{
  325. fontSize: '30px', /* Fontawesome's fa-compress fa-expand is larger than fa-close */
  326. }}
  327. />
  328. <div
  329. className='zoomable-image'
  330. ref={this.setContainerRef}
  331. style={{ overflow }}
  332. >
  333. <img
  334. role='presentation'
  335. ref={this.setImageRef}
  336. alt={alt}
  337. title={alt}
  338. src={src}
  339. width={width}
  340. height={height}
  341. style={{
  342. transform: `scale(${scale})`,
  343. transformOrigin: '0 0',
  344. }}
  345. draggable={false}
  346. onClick={this.handleClick}
  347. onMouseDown={this.handleMouseDown}
  348. />
  349. </div>
  350. </React.Fragment>
  351. );
  352. }
  353. }