index.js 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585
  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 initialState, { me, owner, singleUserMode } 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.getWrappedInstance();
  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 {
  153. redirect = <Redirect from='/' to='/explore' exact />;
  154. }
  155. return (
  156. <ColumnsAreaContainer ref={this.setRef} singleColumn={mobile}>
  157. <WrappedSwitch>
  158. {redirect}
  159. <WrappedRoute path='/getting-started' component={GettingStarted} content={children} />
  160. <WrappedRoute path='/keyboard-shortcuts' component={KeyboardShortcuts} content={children} />
  161. <WrappedRoute path='/about' component={About} content={children} />
  162. <WrappedRoute path='/privacy-policy' component={PrivacyPolicy} content={children} />
  163. <WrappedRoute path={['/home', '/timelines/home']} component={HomeTimeline} content={children} />
  164. <WrappedRoute path={['/public', '/timelines/public']} exact component={PublicTimeline} content={children} />
  165. <WrappedRoute path={['/public/local', '/timelines/public/local']} exact component={CommunityTimeline} content={children} />
  166. <WrappedRoute path={['/conversations', '/timelines/direct']} component={DirectTimeline} content={children} />
  167. <WrappedRoute path='/tags/:id' component={HashtagTimeline} content={children} />
  168. <WrappedRoute path='/lists/:id' component={ListTimeline} content={children} />
  169. <WrappedRoute path='/notifications' component={Notifications} content={children} />
  170. <WrappedRoute path='/favourites' component={FavouritedStatuses} content={children} />
  171. <WrappedRoute path='/bookmarks' component={BookmarkedStatuses} content={children} />
  172. <WrappedRoute path='/pinned' component={PinnedStatuses} content={children} />
  173. <WrappedRoute path='/start' component={FollowRecommendations} content={children} />
  174. <WrappedRoute path='/directory' component={Directory} content={children} />
  175. <WrappedRoute path={['/explore', '/search']} component={Explore} content={children} />
  176. <WrappedRoute path={['/publish', '/statuses/new']} component={Compose} content={children} />
  177. <WrappedRoute path={['/@:acct', '/accounts/:id']} exact component={AccountTimeline} content={children} />
  178. <WrappedRoute path='/@:acct/tagged/:tagged?' exact component={AccountTimeline} content={children} />
  179. <WrappedRoute path={['/@:acct/with_replies', '/accounts/:id/with_replies']} component={AccountTimeline} content={children} componentParams={{ withReplies: true }} />
  180. <WrappedRoute path={['/accounts/:id/followers', '/users/:acct/followers', '/@:acct/followers']} component={Followers} content={children} />
  181. <WrappedRoute path={['/accounts/:id/following', '/users/:acct/following', '/@:acct/following']} component={Following} content={children} />
  182. <WrappedRoute path={['/@:acct/media', '/accounts/:id/media']} component={AccountGallery} content={children} />
  183. <WrappedRoute path='/@:acct/:statusId' exact component={Status} content={children} />
  184. <WrappedRoute path='/@:acct/:statusId/reblogs' component={Reblogs} content={children} />
  185. <WrappedRoute path='/@:acct/:statusId/favourites' component={Favourites} content={children} />
  186. {/* Legacy routes, cannot be easily factored with other routes because they share a param name */}
  187. <WrappedRoute path='/timelines/tag/:id' component={HashtagTimeline} content={children} />
  188. <WrappedRoute path='/timelines/list/:id' component={ListTimeline} content={children} />
  189. <WrappedRoute path='/statuses/:statusId' exact component={Status} content={children} />
  190. <WrappedRoute path='/statuses/:statusId/reblogs' component={Reblogs} content={children} />
  191. <WrappedRoute path='/statuses/:statusId/favourites' component={Favourites} content={children} />
  192. <WrappedRoute path='/follow_requests' component={FollowRequests} content={children} />
  193. <WrappedRoute path='/blocks' component={Blocks} content={children} />
  194. <WrappedRoute path='/domain_blocks' component={DomainBlocks} content={children} />
  195. <WrappedRoute path='/mutes' component={Mutes} content={children} />
  196. <WrappedRoute path='/lists' component={Lists} content={children} />
  197. <WrappedRoute component={GenericNotFound} content={children} />
  198. </WrappedSwitch>
  199. </ColumnsAreaContainer>
  200. );
  201. }
  202. }
  203. export default @connect(mapStateToProps)
  204. @injectIntl
  205. @withRouter
  206. class UI extends React.PureComponent {
  207. static contextTypes = {
  208. router: PropTypes.object.isRequired,
  209. identity: PropTypes.object.isRequired,
  210. };
  211. static propTypes = {
  212. dispatch: PropTypes.func.isRequired,
  213. children: PropTypes.node,
  214. isComposing: PropTypes.bool,
  215. hasComposingText: PropTypes.bool,
  216. hasMediaAttachments: PropTypes.bool,
  217. canUploadMore: PropTypes.bool,
  218. location: PropTypes.object,
  219. intl: PropTypes.object.isRequired,
  220. dropdownMenuIsOpen: PropTypes.bool,
  221. layout: PropTypes.string.isRequired,
  222. firstLaunch: PropTypes.bool,
  223. username: PropTypes.string,
  224. };
  225. state = {
  226. draggingOver: false,
  227. };
  228. handleBeforeUnload = e => {
  229. const { intl, dispatch, isComposing, hasComposingText, hasMediaAttachments } = this.props;
  230. dispatch(synchronouslySubmitMarkers());
  231. if (isComposing && (hasComposingText || hasMediaAttachments)) {
  232. e.preventDefault();
  233. // Setting returnValue to any string causes confirmation dialog.
  234. // Many browsers no longer display this text to users,
  235. // but we set user-friendly message for other browsers, e.g. Edge.
  236. e.returnValue = intl.formatMessage(messages.beforeUnload);
  237. }
  238. }
  239. handleWindowFocus = () => {
  240. this.props.dispatch(focusApp());
  241. this.props.dispatch(submitMarkers({ immediate: true }));
  242. }
  243. handleWindowBlur = () => {
  244. this.props.dispatch(unfocusApp());
  245. }
  246. handleDragEnter = (e) => {
  247. e.preventDefault();
  248. if (!this.dragTargets) {
  249. this.dragTargets = [];
  250. }
  251. if (this.dragTargets.indexOf(e.target) === -1) {
  252. this.dragTargets.push(e.target);
  253. }
  254. if (e.dataTransfer && Array.from(e.dataTransfer.types).includes('Files') && this.props.canUploadMore) {
  255. this.setState({ draggingOver: true });
  256. }
  257. }
  258. handleDragOver = (e) => {
  259. if (this.dataTransferIsText(e.dataTransfer)) return false;
  260. e.preventDefault();
  261. e.stopPropagation();
  262. try {
  263. e.dataTransfer.dropEffect = 'copy';
  264. } catch (err) {
  265. }
  266. return false;
  267. }
  268. handleDrop = (e) => {
  269. if (this.dataTransferIsText(e.dataTransfer)) return;
  270. e.preventDefault();
  271. this.setState({ draggingOver: false });
  272. this.dragTargets = [];
  273. if (e.dataTransfer && e.dataTransfer.files.length >= 1 && this.props.canUploadMore) {
  274. this.props.dispatch(uploadCompose(e.dataTransfer.files));
  275. }
  276. }
  277. handleDragLeave = (e) => {
  278. e.preventDefault();
  279. e.stopPropagation();
  280. this.dragTargets = this.dragTargets.filter(el => el !== e.target && this.node.contains(el));
  281. if (this.dragTargets.length > 0) {
  282. return;
  283. }
  284. this.setState({ draggingOver: false });
  285. }
  286. dataTransferIsText = (dataTransfer) => {
  287. return (dataTransfer && Array.from(dataTransfer.types).filter((type) => type === 'text/plain').length === 1);
  288. }
  289. closeUploadModal = () => {
  290. this.setState({ draggingOver: false });
  291. }
  292. handleServiceWorkerPostMessage = ({ data }) => {
  293. if (data.type === 'navigate') {
  294. this.context.router.history.push(data.path);
  295. } else {
  296. console.warn('Unknown message type:', data.type);
  297. }
  298. }
  299. handleLayoutChange = debounce(() => {
  300. this.props.dispatch(clearHeight()); // The cached heights are no longer accurate, invalidate
  301. }, 500, {
  302. trailing: true,
  303. });
  304. handleResize = () => {
  305. const layout = layoutFromWindow();
  306. if (layout !== this.props.layout) {
  307. this.handleLayoutChange.cancel();
  308. this.props.dispatch(changeLayout(layout));
  309. } else {
  310. this.handleLayoutChange();
  311. }
  312. }
  313. componentDidMount () {
  314. const { signedIn } = this.context.identity;
  315. window.addEventListener('focus', this.handleWindowFocus, false);
  316. window.addEventListener('blur', this.handleWindowBlur, false);
  317. window.addEventListener('beforeunload', this.handleBeforeUnload, false);
  318. window.addEventListener('resize', this.handleResize, { passive: true });
  319. document.addEventListener('dragenter', this.handleDragEnter, false);
  320. document.addEventListener('dragover', this.handleDragOver, false);
  321. document.addEventListener('drop', this.handleDrop, false);
  322. document.addEventListener('dragleave', this.handleDragLeave, false);
  323. document.addEventListener('dragend', this.handleDragEnd, false);
  324. if ('serviceWorker' in navigator) {
  325. navigator.serviceWorker.addEventListener('message', this.handleServiceWorkerPostMessage);
  326. }
  327. // On first launch, redirect to the follow recommendations page
  328. if (signedIn && this.props.firstLaunch) {
  329. this.context.router.history.replace('/start');
  330. this.props.dispatch(closeOnboarding());
  331. }
  332. if (signedIn) {
  333. this.props.dispatch(fetchMarkers());
  334. this.props.dispatch(expandHomeTimeline());
  335. this.props.dispatch(expandNotifications());
  336. setTimeout(() => this.props.dispatch(fetchServer()), 3000);
  337. }
  338. this.hotkeys.__mousetrap__.stopCallback = (e, element) => {
  339. return ['TEXTAREA', 'SELECT', 'INPUT'].includes(element.tagName);
  340. };
  341. }
  342. componentWillUnmount () {
  343. window.removeEventListener('focus', this.handleWindowFocus);
  344. window.removeEventListener('blur', this.handleWindowBlur);
  345. window.removeEventListener('beforeunload', this.handleBeforeUnload);
  346. window.removeEventListener('resize', this.handleResize);
  347. document.removeEventListener('dragenter', this.handleDragEnter);
  348. document.removeEventListener('dragover', this.handleDragOver);
  349. document.removeEventListener('drop', this.handleDrop);
  350. document.removeEventListener('dragleave', this.handleDragLeave);
  351. document.removeEventListener('dragend', this.handleDragEnd);
  352. }
  353. setRef = c => {
  354. this.node = c;
  355. }
  356. handleHotkeyNew = e => {
  357. e.preventDefault();
  358. const element = this.node.querySelector('.compose-form__autosuggest-wrapper textarea');
  359. if (element) {
  360. element.focus();
  361. }
  362. }
  363. handleHotkeySearch = e => {
  364. e.preventDefault();
  365. const element = this.node.querySelector('.search__input');
  366. if (element) {
  367. element.focus();
  368. }
  369. }
  370. handleHotkeyForceNew = e => {
  371. this.handleHotkeyNew(e);
  372. this.props.dispatch(resetCompose());
  373. }
  374. handleHotkeyToggleComposeSpoilers = e => {
  375. e.preventDefault();
  376. this.props.dispatch(changeComposeSpoilerness());
  377. }
  378. handleHotkeyFocusColumn = e => {
  379. const index = (e.key * 1) + 1; // First child is drawer, skip that
  380. const column = this.node.querySelector(`.column:nth-child(${index})`);
  381. if (!column) return;
  382. const container = column.querySelector('.scrollable');
  383. if (container) {
  384. const status = container.querySelector('.focusable');
  385. if (status) {
  386. if (container.scrollTop > status.offsetTop) {
  387. status.scrollIntoView(true);
  388. }
  389. status.focus();
  390. }
  391. }
  392. }
  393. handleHotkeyBack = () => {
  394. if (window.history && window.history.length === 1) {
  395. this.context.router.history.push('/');
  396. } else {
  397. this.context.router.history.goBack();
  398. }
  399. }
  400. setHotkeysRef = c => {
  401. this.hotkeys = c;
  402. }
  403. handleHotkeyToggleHelp = () => {
  404. if (this.props.location.pathname === '/keyboard-shortcuts') {
  405. this.context.router.history.goBack();
  406. } else {
  407. this.context.router.history.push('/keyboard-shortcuts');
  408. }
  409. }
  410. handleHotkeyGoToHome = () => {
  411. this.context.router.history.push('/home');
  412. }
  413. handleHotkeyGoToNotifications = () => {
  414. this.context.router.history.push('/notifications');
  415. }
  416. handleHotkeyGoToLocal = () => {
  417. this.context.router.history.push('/public/local');
  418. }
  419. handleHotkeyGoToFederated = () => {
  420. this.context.router.history.push('/public');
  421. }
  422. handleHotkeyGoToDirect = () => {
  423. this.context.router.history.push('/conversations');
  424. }
  425. handleHotkeyGoToStart = () => {
  426. this.context.router.history.push('/getting-started');
  427. }
  428. handleHotkeyGoToFavourites = () => {
  429. this.context.router.history.push('/favourites');
  430. }
  431. handleHotkeyGoToPinned = () => {
  432. this.context.router.history.push('/pinned');
  433. }
  434. handleHotkeyGoToProfile = () => {
  435. this.context.router.history.push(`/@${this.props.username}`);
  436. }
  437. handleHotkeyGoToBlocked = () => {
  438. this.context.router.history.push('/blocks');
  439. }
  440. handleHotkeyGoToMuted = () => {
  441. this.context.router.history.push('/mutes');
  442. }
  443. handleHotkeyGoToRequests = () => {
  444. this.context.router.history.push('/follow_requests');
  445. }
  446. render () {
  447. const { draggingOver } = this.state;
  448. const { children, isComposing, location, dropdownMenuIsOpen, layout } = this.props;
  449. const handlers = {
  450. help: this.handleHotkeyToggleHelp,
  451. new: this.handleHotkeyNew,
  452. search: this.handleHotkeySearch,
  453. forceNew: this.handleHotkeyForceNew,
  454. toggleComposeSpoilers: this.handleHotkeyToggleComposeSpoilers,
  455. focusColumn: this.handleHotkeyFocusColumn,
  456. back: this.handleHotkeyBack,
  457. goToHome: this.handleHotkeyGoToHome,
  458. goToNotifications: this.handleHotkeyGoToNotifications,
  459. goToLocal: this.handleHotkeyGoToLocal,
  460. goToFederated: this.handleHotkeyGoToFederated,
  461. goToDirect: this.handleHotkeyGoToDirect,
  462. goToStart: this.handleHotkeyGoToStart,
  463. goToFavourites: this.handleHotkeyGoToFavourites,
  464. goToPinned: this.handleHotkeyGoToPinned,
  465. goToProfile: this.handleHotkeyGoToProfile,
  466. goToBlocked: this.handleHotkeyGoToBlocked,
  467. goToMuted: this.handleHotkeyGoToMuted,
  468. goToRequests: this.handleHotkeyGoToRequests,
  469. };
  470. return (
  471. <HotKeys keyMap={keyMap} handlers={handlers} ref={this.setHotkeysRef} attach={window} focused>
  472. <div className={classNames('ui', { 'is-composing': isComposing })} ref={this.setRef} style={{ pointerEvents: dropdownMenuIsOpen ? 'none' : null }}>
  473. <Header />
  474. <SwitchingColumnsArea location={location} mobile={layout === 'mobile' || layout === 'single-column'}>
  475. {children}
  476. </SwitchingColumnsArea>
  477. {layout !== 'mobile' && <PictureInPicture />}
  478. <NotificationsContainer />
  479. <LoadingBarContainer className='loading-bar' />
  480. <ModalContainer />
  481. <UploadArea active={draggingOver} onClose={this.closeUploadModal} />
  482. </div>
  483. </HotKeys>
  484. );
  485. }
  486. }