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