index.js 19 KB

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