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.

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