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.

545 lines
19 KiB

  1. import classNames from 'classnames';
  2. import React from 'react';
  3. import { HotKeys } from 'react-hotkeys';
  4. import { defineMessages, injectIntl } from 'react-intl';
  5. import { connect } from 'react-redux';
  6. import { Redirect, withRouter } from 'react-router-dom';
  7. import PropTypes from 'prop-types';
  8. import NotificationsContainer from './containers/notifications_container';
  9. import LoadingBarContainer from './containers/loading_bar_container';
  10. import ModalContainer from './containers/modal_container';
  11. import { isMobile } from '../../is_mobile';
  12. import { debounce } from 'lodash';
  13. import { uploadCompose, resetCompose } from '../../actions/compose';
  14. import { expandHomeTimeline } from '../../actions/timelines';
  15. import { expandNotifications } from '../../actions/notifications';
  16. import { fetchFilters } from '../../actions/filters';
  17. import { clearHeight } from '../../actions/height_cache';
  18. import { focusApp, unfocusApp } from 'mastodon/actions/app';
  19. import { submitMarkers } from 'mastodon/actions/markers';
  20. import { WrappedSwitch, WrappedRoute } from './util/react_router_helpers';
  21. import UploadArea from './components/upload_area';
  22. import ColumnsAreaContainer from './containers/columns_area_container';
  23. import DocumentTitle from './components/document_title';
  24. import {
  25. Compose,
  26. Status,
  27. GettingStarted,
  28. KeyboardShortcuts,
  29. PublicTimeline,
  30. CommunityTimeline,
  31. AccountTimeline,
  32. AccountGallery,
  33. HomeTimeline,
  34. Followers,
  35. Following,
  36. Reblogs,
  37. Favourites,
  38. DirectTimeline,
  39. HashtagTimeline,
  40. Notifications,
  41. FollowRequests,
  42. GenericNotFound,
  43. FavouritedStatuses,
  44. ListTimeline,
  45. Blocks,
  46. DomainBlocks,
  47. Mutes,
  48. PinnedStatuses,
  49. Lists,
  50. Search,
  51. Directory,
  52. } from './util/async-components';
  53. import { me, forceSingleColumn } from '../../initial_state';
  54. import { previewState as previewMediaState } from './components/media_modal';
  55. import { previewState as previewVideoState } from './components/video_modal';
  56. // Dummy import, to make sure that <Status /> ends up in the application bundle.
  57. // Without this it ends up in ~8 very commonly used bundles.
  58. import '../../components/status';
  59. const messages = defineMessages({
  60. beforeUnload: { id: 'ui.beforeunload', defaultMessage: 'Your draft will be lost if you leave Mastodon.' },
  61. });
  62. const mapStateToProps = state => ({
  63. isComposing: state.getIn(['compose', 'is_composing']),
  64. hasComposingText: state.getIn(['compose', 'text']).trim().length !== 0,
  65. hasMediaAttachments: state.getIn(['compose', 'media_attachments']).size > 0,
  66. canUploadMore: !state.getIn(['compose', 'media_attachments']).some(x => ['audio', 'video'].includes(x.get('type'))) && state.getIn(['compose', 'media_attachments']).size < 4,
  67. dropdownMenuIsOpen: state.getIn(['dropdown_menu', 'openId']) !== null,
  68. });
  69. const keyMap = {
  70. help: '?',
  71. new: 'n',
  72. search: 's',
  73. forceNew: 'option+n',
  74. focusColumn: ['1', '2', '3', '4', '5', '6', '7', '8', '9'],
  75. reply: 'r',
  76. favourite: 'f',
  77. boost: 'b',
  78. mention: 'm',
  79. open: ['enter', 'o'],
  80. openProfile: 'p',
  81. moveDown: ['down', 'j'],
  82. moveUp: ['up', 'k'],
  83. back: 'backspace',
  84. goToHome: 'g h',
  85. goToNotifications: 'g n',
  86. goToLocal: 'g l',
  87. goToFederated: 'g t',
  88. goToDirect: 'g d',
  89. goToStart: 'g s',
  90. goToFavourites: 'g f',
  91. goToPinned: 'g p',
  92. goToProfile: 'g u',
  93. goToBlocked: 'g b',
  94. goToMuted: 'g m',
  95. goToRequests: 'g r',
  96. toggleHidden: 'x',
  97. toggleSensitive: 'h',
  98. };
  99. class SwitchingColumnsArea extends React.PureComponent {
  100. static propTypes = {
  101. children: PropTypes.node,
  102. location: PropTypes.object,
  103. onLayoutChange: PropTypes.func.isRequired,
  104. };
  105. state = {
  106. mobile: isMobile(window.innerWidth),
  107. };
  108. componentWillMount () {
  109. window.addEventListener('resize', this.handleResize, { passive: true });
  110. if (this.state.mobile || forceSingleColumn) {
  111. document.body.classList.toggle('layout-single-column', true);
  112. document.body.classList.toggle('layout-multiple-columns', false);
  113. } else {
  114. document.body.classList.toggle('layout-single-column', false);
  115. document.body.classList.toggle('layout-multiple-columns', true);
  116. }
  117. }
  118. componentDidUpdate (prevProps, prevState) {
  119. if (![this.props.location.pathname, '/'].includes(prevProps.location.pathname)) {
  120. this.node.handleChildrenContentChange();
  121. }
  122. if (prevState.mobile !== this.state.mobile && !forceSingleColumn) {
  123. document.body.classList.toggle('layout-single-column', this.state.mobile);
  124. document.body.classList.toggle('layout-multiple-columns', !this.state.mobile);
  125. }
  126. }
  127. componentWillUnmount () {
  128. window.removeEventListener('resize', this.handleResize);
  129. }
  130. shouldUpdateScroll (_, { location }) {
  131. return location.state !== previewMediaState && location.state !== previewVideoState;
  132. }
  133. handleLayoutChange = debounce(() => {
  134. // The cached heights are no longer accurate, invalidate
  135. this.props.onLayoutChange();
  136. }, 500, {
  137. trailing: true,
  138. })
  139. handleResize = () => {
  140. const mobile = isMobile(window.innerWidth);
  141. if (mobile !== this.state.mobile) {
  142. this.handleLayoutChange.cancel();
  143. this.props.onLayoutChange();
  144. this.setState({ mobile });
  145. } else {
  146. this.handleLayoutChange();
  147. }
  148. }
  149. setRef = c => {
  150. this.node = c.getWrappedInstance();
  151. }
  152. render () {
  153. const { children } = this.props;
  154. const { mobile } = this.state;
  155. const singleColumn = forceSingleColumn || mobile;
  156. const redirect = singleColumn ? <Redirect from='/' to='/timelines/home' exact /> : <Redirect from='/' to='/getting-started' exact />;
  157. return (
  158. <ColumnsAreaContainer ref={this.setRef} singleColumn={singleColumn}>
  159. <WrappedSwitch>
  160. {redirect}
  161. <WrappedRoute path='/getting-started' component={GettingStarted} content={children} />
  162. <WrappedRoute path='/keyboard-shortcuts' component={KeyboardShortcuts} content={children} />
  163. <WrappedRoute path='/timelines/home' component={HomeTimeline} content={children} componentParams={{ shouldUpdateScroll: this.shouldUpdateScroll }} />
  164. <WrappedRoute path='/timelines/public' exact component={PublicTimeline} content={children} componentParams={{ shouldUpdateScroll: this.shouldUpdateScroll }} />
  165. <WrappedRoute path='/timelines/public/local' exact component={CommunityTimeline} content={children} componentParams={{ shouldUpdateScroll: this.shouldUpdateScroll }} />
  166. <WrappedRoute path='/timelines/direct' component={DirectTimeline} content={children} componentParams={{ shouldUpdateScroll: this.shouldUpdateScroll }} />
  167. <WrappedRoute path='/timelines/tag/:id' component={HashtagTimeline} content={children} componentParams={{ shouldUpdateScroll: this.shouldUpdateScroll }} />
  168. <WrappedRoute path='/timelines/list/:id' component={ListTimeline} content={children} componentParams={{ shouldUpdateScroll: this.shouldUpdateScroll }} />
  169. <WrappedRoute path='/notifications' component={Notifications} content={children} componentParams={{ shouldUpdateScroll: this.shouldUpdateScroll }} />
  170. <WrappedRoute path='/favourites' component={FavouritedStatuses} content={children} componentParams={{ shouldUpdateScroll: this.shouldUpdateScroll }} />
  171. <WrappedRoute path='/pinned' component={PinnedStatuses} content={children} componentParams={{ shouldUpdateScroll: this.shouldUpdateScroll }} />
  172. <WrappedRoute path='/search' component={Search} content={children} />
  173. <WrappedRoute path='/directory' component={Directory} content={children} componentParams={{ shouldUpdateScroll: this.shouldUpdateScroll }} />
  174. <WrappedRoute path='/statuses/new' component={Compose} content={children} />
  175. <WrappedRoute path='/statuses/:statusId' exact component={Status} content={children} componentParams={{ shouldUpdateScroll: this.shouldUpdateScroll }} />
  176. <WrappedRoute path='/statuses/:statusId/reblogs' component={Reblogs} content={children} componentParams={{ shouldUpdateScroll: this.shouldUpdateScroll }} />
  177. <WrappedRoute path='/statuses/:statusId/favourites' component={Favourites} content={children} componentParams={{ shouldUpdateScroll: this.shouldUpdateScroll }} />
  178. <WrappedRoute path='/accounts/:accountId' exact component={AccountTimeline} content={children} componentParams={{ shouldUpdateScroll: this.shouldUpdateScroll }} />
  179. <WrappedRoute path='/accounts/:accountId/with_replies' component={AccountTimeline} content={children} componentParams={{ shouldUpdateScroll: this.shouldUpdateScroll, withReplies: true }} />
  180. <WrappedRoute path='/accounts/:accountId/followers' component={Followers} content={children} componentParams={{ shouldUpdateScroll: this.shouldUpdateScroll }} />
  181. <WrappedRoute path='/accounts/:accountId/following' component={Following} content={children} componentParams={{ shouldUpdateScroll: this.shouldUpdateScroll }} />
  182. <WrappedRoute path='/accounts/:accountId/media' component={AccountGallery} content={children} componentParams={{ shouldUpdateScroll: this.shouldUpdateScroll }} />
  183. <WrappedRoute path='/follow_requests' component={FollowRequests} content={children} componentParams={{ shouldUpdateScroll: this.shouldUpdateScroll }} />
  184. <WrappedRoute path='/blocks' component={Blocks} content={children} componentParams={{ shouldUpdateScroll: this.shouldUpdateScroll }} />
  185. <WrappedRoute path='/domain_blocks' component={DomainBlocks} content={children} componentParams={{ shouldUpdateScroll: this.shouldUpdateScroll }} />
  186. <WrappedRoute path='/mutes' component={Mutes} content={children} componentParams={{ shouldUpdateScroll: this.shouldUpdateScroll }} />
  187. <WrappedRoute path='/lists' component={Lists} content={children} componentParams={{ shouldUpdateScroll: this.shouldUpdateScroll }} />
  188. <WrappedRoute component={GenericNotFound} content={children} />
  189. </WrappedSwitch>
  190. </ColumnsAreaContainer>
  191. );
  192. }
  193. }
  194. export default @connect(mapStateToProps)
  195. @injectIntl
  196. @withRouter
  197. class UI extends React.PureComponent {
  198. static contextTypes = {
  199. router: PropTypes.object.isRequired,
  200. };
  201. static propTypes = {
  202. dispatch: PropTypes.func.isRequired,
  203. children: PropTypes.node,
  204. isComposing: PropTypes.bool,
  205. hasComposingText: PropTypes.bool,
  206. hasMediaAttachments: PropTypes.bool,
  207. canUploadMore: PropTypes.bool,
  208. location: PropTypes.object,
  209. intl: PropTypes.object.isRequired,
  210. dropdownMenuIsOpen: PropTypes.bool,
  211. };
  212. state = {
  213. draggingOver: false,
  214. };
  215. handleBeforeUnload = e => {
  216. const { intl, dispatch, isComposing, hasComposingText, hasMediaAttachments } = this.props;
  217. dispatch(submitMarkers());
  218. if (isComposing && (hasComposingText || hasMediaAttachments)) {
  219. // Setting returnValue to any string causes confirmation dialog.
  220. // Many browsers no longer display this text to users,
  221. // but we set user-friendly message for other browsers, e.g. Edge.
  222. e.returnValue = intl.formatMessage(messages.beforeUnload);
  223. }
  224. }
  225. handleWindowFocus = () => {
  226. this.props.dispatch(focusApp());
  227. }
  228. handleWindowBlur = () => {
  229. this.props.dispatch(unfocusApp());
  230. }
  231. handleLayoutChange = () => {
  232. // The cached heights are no longer accurate, invalidate
  233. this.props.dispatch(clearHeight());
  234. }
  235. handleDragEnter = (e) => {
  236. e.preventDefault();
  237. if (!this.dragTargets) {
  238. this.dragTargets = [];
  239. }
  240. if (this.dragTargets.indexOf(e.target) === -1) {
  241. this.dragTargets.push(e.target);
  242. }
  243. if (e.dataTransfer && Array.from(e.dataTransfer.types).includes('Files') && this.props.canUploadMore) {
  244. this.setState({ draggingOver: true });
  245. }
  246. }
  247. handleDragOver = (e) => {
  248. if (this.dataTransferIsText(e.dataTransfer)) return false;
  249. e.preventDefault();
  250. e.stopPropagation();
  251. try {
  252. e.dataTransfer.dropEffect = 'copy';
  253. } catch (err) {
  254. }
  255. return false;
  256. }
  257. handleDrop = (e) => {
  258. if (this.dataTransferIsText(e.dataTransfer)) return;
  259. e.preventDefault();
  260. this.setState({ draggingOver: false });
  261. this.dragTargets = [];
  262. if (e.dataTransfer && e.dataTransfer.files.length >= 1 && this.props.canUploadMore) {
  263. this.props.dispatch(uploadCompose(e.dataTransfer.files));
  264. }
  265. }
  266. handleDragLeave = (e) => {
  267. e.preventDefault();
  268. e.stopPropagation();
  269. this.dragTargets = this.dragTargets.filter(el => el !== e.target && this.node.contains(el));
  270. if (this.dragTargets.length > 0) {
  271. return;
  272. }
  273. this.setState({ draggingOver: false });
  274. }
  275. dataTransferIsText = (dataTransfer) => {
  276. return (dataTransfer && Array.from(dataTransfer.types).filter((type) => type === 'text/plain').length === 1);
  277. }
  278. closeUploadModal = () => {
  279. this.setState({ draggingOver: false });
  280. }
  281. handleServiceWorkerPostMessage = ({ data }) => {
  282. if (data.type === 'navigate') {
  283. this.context.router.history.push(data.path);
  284. } else {
  285. console.warn('Unknown message type:', data.type);
  286. }
  287. }
  288. componentWillMount () {
  289. window.addEventListener('focus', this.handleWindowFocus, false);
  290. window.addEventListener('blur', this.handleWindowBlur, false);
  291. window.addEventListener('beforeunload', this.handleBeforeUnload, false);
  292. document.addEventListener('dragenter', this.handleDragEnter, false);
  293. document.addEventListener('dragover', this.handleDragOver, false);
  294. document.addEventListener('drop', this.handleDrop, false);
  295. document.addEventListener('dragleave', this.handleDragLeave, false);
  296. document.addEventListener('dragend', this.handleDragEnd, false);
  297. if ('serviceWorker' in navigator) {
  298. navigator.serviceWorker.addEventListener('message', this.handleServiceWorkerPostMessage);
  299. }
  300. if (typeof window.Notification !== 'undefined' && Notification.permission === 'default') {
  301. window.setTimeout(() => Notification.requestPermission(), 120 * 1000);
  302. }
  303. this.props.dispatch(expandHomeTimeline());
  304. this.props.dispatch(expandNotifications());
  305. setTimeout(() => this.props.dispatch(fetchFilters()), 500);
  306. }
  307. componentDidMount () {
  308. this.hotkeys.__mousetrap__.stopCallback = (e, element) => {
  309. return ['TEXTAREA', 'SELECT', 'INPUT'].includes(element.tagName);
  310. };
  311. }
  312. componentWillUnmount () {
  313. window.removeEventListener('focus', this.handleWindowFocus);
  314. window.removeEventListener('blur', this.handleWindowBlur);
  315. window.removeEventListener('beforeunload', this.handleBeforeUnload);
  316. document.removeEventListener('dragenter', this.handleDragEnter);
  317. document.removeEventListener('dragover', this.handleDragOver);
  318. document.removeEventListener('drop', this.handleDrop);
  319. document.removeEventListener('dragleave', this.handleDragLeave);
  320. document.removeEventListener('dragend', this.handleDragEnd);
  321. }
  322. setRef = c => {
  323. this.node = c;
  324. }
  325. handleHotkeyNew = e => {
  326. e.preventDefault();
  327. const element = this.node.querySelector('.compose-form__autosuggest-wrapper textarea');
  328. if (element) {
  329. element.focus();
  330. }
  331. }
  332. handleHotkeySearch = e => {
  333. e.preventDefault();
  334. const element = this.node.querySelector('.search__input');
  335. if (element) {
  336. element.focus();
  337. }
  338. }
  339. handleHotkeyForceNew = e => {
  340. this.handleHotkeyNew(e);
  341. this.props.dispatch(resetCompose());
  342. }
  343. handleHotkeyFocusColumn = e => {
  344. const index = (e.key * 1) + 1; // First child is drawer, skip that
  345. const column = this.node.querySelector(`.column:nth-child(${index})`);
  346. if (!column) return;
  347. const container = column.querySelector('.scrollable');
  348. if (container) {
  349. const status = container.querySelector('.focusable');
  350. if (status) {
  351. if (container.scrollTop > status.offsetTop) {
  352. status.scrollIntoView(true);
  353. }
  354. status.focus();
  355. }
  356. }
  357. }
  358. handleHotkeyBack = () => {
  359. if (window.history && window.history.length === 1) {
  360. this.context.router.history.push('/');
  361. } else {
  362. this.context.router.history.goBack();
  363. }
  364. }
  365. setHotkeysRef = c => {
  366. this.hotkeys = c;
  367. }
  368. handleHotkeyToggleHelp = () => {
  369. if (this.props.location.pathname === '/keyboard-shortcuts') {
  370. this.context.router.history.goBack();
  371. } else {
  372. this.context.router.history.push('/keyboard-shortcuts');
  373. }
  374. }
  375. handleHotkeyGoToHome = () => {
  376. this.context.router.history.push('/timelines/home');
  377. }
  378. handleHotkeyGoToNotifications = () => {
  379. this.context.router.history.push('/notifications');
  380. }
  381. handleHotkeyGoToLocal = () => {
  382. this.context.router.history.push('/timelines/public/local');
  383. }
  384. handleHotkeyGoToFederated = () => {
  385. this.context.router.history.push('/timelines/public');
  386. }
  387. handleHotkeyGoToDirect = () => {
  388. this.context.router.history.push('/timelines/direct');
  389. }
  390. handleHotkeyGoToStart = () => {
  391. this.context.router.history.push('/getting-started');
  392. }
  393. handleHotkeyGoToFavourites = () => {
  394. this.context.router.history.push('/favourites');
  395. }
  396. handleHotkeyGoToPinned = () => {
  397. this.context.router.history.push('/pinned');
  398. }
  399. handleHotkeyGoToProfile = () => {
  400. this.context.router.history.push(`/accounts/${me}`);
  401. }
  402. handleHotkeyGoToBlocked = () => {
  403. this.context.router.history.push('/blocks');
  404. }
  405. handleHotkeyGoToMuted = () => {
  406. this.context.router.history.push('/mutes');
  407. }
  408. handleHotkeyGoToRequests = () => {
  409. this.context.router.history.push('/follow_requests');
  410. }
  411. render () {
  412. const { draggingOver } = this.state;
  413. const { children, isComposing, location, dropdownMenuIsOpen } = this.props;
  414. const handlers = {
  415. help: this.handleHotkeyToggleHelp,
  416. new: this.handleHotkeyNew,
  417. search: this.handleHotkeySearch,
  418. forceNew: this.handleHotkeyForceNew,
  419. focusColumn: this.handleHotkeyFocusColumn,
  420. back: this.handleHotkeyBack,
  421. goToHome: this.handleHotkeyGoToHome,
  422. goToNotifications: this.handleHotkeyGoToNotifications,
  423. goToLocal: this.handleHotkeyGoToLocal,
  424. goToFederated: this.handleHotkeyGoToFederated,
  425. goToDirect: this.handleHotkeyGoToDirect,
  426. goToStart: this.handleHotkeyGoToStart,
  427. goToFavourites: this.handleHotkeyGoToFavourites,
  428. goToPinned: this.handleHotkeyGoToPinned,
  429. goToProfile: this.handleHotkeyGoToProfile,
  430. goToBlocked: this.handleHotkeyGoToBlocked,
  431. goToMuted: this.handleHotkeyGoToMuted,
  432. goToRequests: this.handleHotkeyGoToRequests,
  433. };
  434. return (
  435. <HotKeys keyMap={keyMap} handlers={handlers} ref={this.setHotkeysRef} attach={window} focused>
  436. <div className={classNames('ui', { 'is-composing': isComposing })} ref={this.setRef} style={{ pointerEvents: dropdownMenuIsOpen ? 'none' : null }}>
  437. <SwitchingColumnsArea location={location} onLayoutChange={this.handleLayoutChange}>
  438. {children}
  439. </SwitchingColumnsArea>
  440. <NotificationsContainer />
  441. <LoadingBarContainer className='loading-bar' />
  442. <ModalContainer />
  443. <UploadArea active={draggingOver} onClose={this.closeUploadModal} />
  444. <DocumentTitle />
  445. </div>
  446. </HotKeys>
  447. );
  448. }
  449. }