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.

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