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.

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