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.

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