index.js 19 KB

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