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.

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