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.

486 lines
17 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().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/media' component={PublicTimeline} content={children} componentParams={{ shouldUpdateScroll: this.shouldUpdateScroll, onlyMedia: true }} />
  138. <WrappedRoute path='/timelines/public/local' exact component={CommunityTimeline} content={children} componentParams={{ shouldUpdateScroll: this.shouldUpdateScroll }} />
  139. <WrappedRoute path='/timelines/public/local/media' component={CommunityTimeline} content={children} componentParams={{ shouldUpdateScroll: this.shouldUpdateScroll, onlyMedia: true }} />
  140. <WrappedRoute path='/timelines/direct' component={DirectTimeline} content={children} componentParams={{ shouldUpdateScroll: this.shouldUpdateScroll }} />
  141. <WrappedRoute path='/timelines/tag/:id' component={HashtagTimeline} content={children} componentParams={{ shouldUpdateScroll: this.shouldUpdateScroll }} />
  142. <WrappedRoute path='/timelines/list/:id' component={ListTimeline} content={children} componentParams={{ shouldUpdateScroll: this.shouldUpdateScroll }} />
  143. <WrappedRoute path='/notifications' component={Notifications} content={children} componentParams={{ shouldUpdateScroll: this.shouldUpdateScroll }} />
  144. <WrappedRoute path='/favourites' component={FavouritedStatuses} content={children} componentParams={{ shouldUpdateScroll: this.shouldUpdateScroll }} />
  145. <WrappedRoute path='/pinned' component={PinnedStatuses} content={children} componentParams={{ shouldUpdateScroll: this.shouldUpdateScroll }} />
  146. <WrappedRoute path='/search' component={Compose} content={children} componentParams={{ isSearchPage: true }} />
  147. <WrappedRoute path='/statuses/new' component={Compose} content={children} />
  148. <WrappedRoute path='/statuses/:statusId' exact component={Status} content={children} componentParams={{ shouldUpdateScroll: this.shouldUpdateScroll }} />
  149. <WrappedRoute path='/statuses/:statusId/reblogs' component={Reblogs} content={children} componentParams={{ shouldUpdateScroll: this.shouldUpdateScroll }} />
  150. <WrappedRoute path='/statuses/:statusId/favourites' component={Favourites} content={children} componentParams={{ shouldUpdateScroll: this.shouldUpdateScroll }} />
  151. <WrappedRoute path='/accounts/:accountId' exact component={AccountTimeline} content={children} componentParams={{ shouldUpdateScroll: this.shouldUpdateScroll }} />
  152. <WrappedRoute path='/accounts/:accountId/with_replies' component={AccountTimeline} content={children} componentParams={{ shouldUpdateScroll: this.shouldUpdateScroll, withReplies: true }} />
  153. <WrappedRoute path='/accounts/:accountId/followers' component={Followers} content={children} componentParams={{ shouldUpdateScroll: this.shouldUpdateScroll }} />
  154. <WrappedRoute path='/accounts/:accountId/following' component={Following} content={children} componentParams={{ shouldUpdateScroll: this.shouldUpdateScroll }} />
  155. <WrappedRoute path='/accounts/:accountId/media' component={AccountGallery} content={children} componentParams={{ shouldUpdateScroll: this.shouldUpdateScroll }} />
  156. <WrappedRoute path='/follow_requests' component={FollowRequests} content={children} componentParams={{ shouldUpdateScroll: this.shouldUpdateScroll }} />
  157. <WrappedRoute path='/blocks' component={Blocks} content={children} componentParams={{ shouldUpdateScroll: this.shouldUpdateScroll }} />
  158. <WrappedRoute path='/domain_blocks' component={DomainBlocks} content={children} componentParams={{ shouldUpdateScroll: this.shouldUpdateScroll }} />
  159. <WrappedRoute path='/mutes' component={Mutes} content={children} componentParams={{ shouldUpdateScroll: this.shouldUpdateScroll }} />
  160. <WrappedRoute path='/lists' component={Lists} content={children} componentParams={{ shouldUpdateScroll: this.shouldUpdateScroll }} />
  161. <WrappedRoute component={GenericNotFound} content={children} />
  162. </WrappedSwitch>
  163. </ColumnsAreaContainer>
  164. );
  165. }
  166. }
  167. export default @connect(mapStateToProps)
  168. @injectIntl
  169. @withRouter
  170. class UI extends React.PureComponent {
  171. static contextTypes = {
  172. router: PropTypes.object.isRequired,
  173. };
  174. static propTypes = {
  175. dispatch: PropTypes.func.isRequired,
  176. children: PropTypes.node,
  177. isComposing: PropTypes.bool,
  178. hasComposingText: PropTypes.bool,
  179. hasMediaAttachments: PropTypes.bool,
  180. location: PropTypes.object,
  181. intl: PropTypes.object.isRequired,
  182. dropdownMenuIsOpen: PropTypes.bool,
  183. };
  184. state = {
  185. draggingOver: false,
  186. };
  187. handleBeforeUnload = (e) => {
  188. const { intl, isComposing, hasComposingText, hasMediaAttachments } = this.props;
  189. if (isComposing && (hasComposingText || hasMediaAttachments)) {
  190. // Setting returnValue to any string causes confirmation dialog.
  191. // Many browsers no longer display this text to users,
  192. // but we set user-friendly message for other browsers, e.g. Edge.
  193. e.returnValue = intl.formatMessage(messages.beforeUnload);
  194. }
  195. }
  196. handleLayoutChange = () => {
  197. // The cached heights are no longer accurate, invalidate
  198. this.props.dispatch(clearHeight());
  199. }
  200. handleDragEnter = (e) => {
  201. e.preventDefault();
  202. if (!this.dragTargets) {
  203. this.dragTargets = [];
  204. }
  205. if (this.dragTargets.indexOf(e.target) === -1) {
  206. this.dragTargets.push(e.target);
  207. }
  208. if (e.dataTransfer && Array.from(e.dataTransfer.types).includes('Files')) {
  209. this.setState({ draggingOver: true });
  210. }
  211. }
  212. handleDragOver = (e) => {
  213. e.preventDefault();
  214. e.stopPropagation();
  215. try {
  216. e.dataTransfer.dropEffect = 'copy';
  217. } catch (err) {
  218. }
  219. return false;
  220. }
  221. handleDrop = (e) => {
  222. e.preventDefault();
  223. this.setState({ draggingOver: false });
  224. if (e.dataTransfer && e.dataTransfer.files.length === 1) {
  225. this.props.dispatch(uploadCompose(e.dataTransfer.files));
  226. }
  227. }
  228. handleDragLeave = (e) => {
  229. e.preventDefault();
  230. e.stopPropagation();
  231. this.dragTargets = this.dragTargets.filter(el => el !== e.target && this.node.contains(el));
  232. if (this.dragTargets.length > 0) {
  233. return;
  234. }
  235. this.setState({ draggingOver: false });
  236. }
  237. closeUploadModal = () => {
  238. this.setState({ draggingOver: false });
  239. }
  240. handleServiceWorkerPostMessage = ({ data }) => {
  241. if (data.type === 'navigate') {
  242. this.context.router.history.push(data.path);
  243. } else {
  244. console.warn('Unknown message type:', data.type);
  245. }
  246. }
  247. componentWillMount () {
  248. window.addEventListener('beforeunload', this.handleBeforeUnload, false);
  249. document.addEventListener('dragenter', this.handleDragEnter, false);
  250. document.addEventListener('dragover', this.handleDragOver, false);
  251. document.addEventListener('drop', this.handleDrop, false);
  252. document.addEventListener('dragleave', this.handleDragLeave, false);
  253. document.addEventListener('dragend', this.handleDragEnd, false);
  254. if ('serviceWorker' in navigator) {
  255. navigator.serviceWorker.addEventListener('message', this.handleServiceWorkerPostMessage);
  256. }
  257. if (typeof window.Notification !== 'undefined' && Notification.permission === 'default') {
  258. window.setTimeout(() => Notification.requestPermission(), 120 * 1000);
  259. }
  260. this.props.dispatch(expandHomeTimeline());
  261. this.props.dispatch(expandNotifications());
  262. setTimeout(() => this.props.dispatch(fetchFilters()), 500);
  263. }
  264. componentDidMount () {
  265. this.hotkeys.__mousetrap__.stopCallback = (e, element) => {
  266. return ['TEXTAREA', 'SELECT', 'INPUT'].includes(element.tagName);
  267. };
  268. }
  269. componentWillUnmount () {
  270. window.removeEventListener('beforeunload', this.handleBeforeUnload);
  271. document.removeEventListener('dragenter', this.handleDragEnter);
  272. document.removeEventListener('dragover', this.handleDragOver);
  273. document.removeEventListener('drop', this.handleDrop);
  274. document.removeEventListener('dragleave', this.handleDragLeave);
  275. document.removeEventListener('dragend', this.handleDragEnd);
  276. }
  277. setRef = c => {
  278. this.node = c;
  279. }
  280. handleHotkeyNew = e => {
  281. e.preventDefault();
  282. const element = this.node.querySelector('.compose-form__autosuggest-wrapper textarea');
  283. if (element) {
  284. element.focus();
  285. }
  286. }
  287. handleHotkeySearch = e => {
  288. e.preventDefault();
  289. const element = this.node.querySelector('.search__input');
  290. if (element) {
  291. element.focus();
  292. }
  293. }
  294. handleHotkeyForceNew = e => {
  295. this.handleHotkeyNew(e);
  296. this.props.dispatch(resetCompose());
  297. }
  298. handleHotkeyFocusColumn = e => {
  299. const index = (e.key * 1) + 1; // First child is drawer, skip that
  300. const column = this.node.querySelector(`.column:nth-child(${index})`);
  301. if (column) {
  302. const status = column.querySelector('.focusable');
  303. if (status) {
  304. status.focus();
  305. }
  306. }
  307. }
  308. handleHotkeyBack = () => {
  309. if (window.history && window.history.length === 1) {
  310. this.context.router.history.push('/');
  311. } else {
  312. this.context.router.history.goBack();
  313. }
  314. }
  315. setHotkeysRef = c => {
  316. this.hotkeys = c;
  317. }
  318. handleHotkeyToggleHelp = () => {
  319. if (this.props.location.pathname === '/keyboard-shortcuts') {
  320. this.context.router.history.goBack();
  321. } else {
  322. this.context.router.history.push('/keyboard-shortcuts');
  323. }
  324. }
  325. handleHotkeyGoToHome = () => {
  326. this.context.router.history.push('/timelines/home');
  327. }
  328. handleHotkeyGoToNotifications = () => {
  329. this.context.router.history.push('/notifications');
  330. }
  331. handleHotkeyGoToLocal = () => {
  332. this.context.router.history.push('/timelines/public/local');
  333. }
  334. handleHotkeyGoToFederated = () => {
  335. this.context.router.history.push('/timelines/public');
  336. }
  337. handleHotkeyGoToDirect = () => {
  338. this.context.router.history.push('/timelines/direct');
  339. }
  340. handleHotkeyGoToStart = () => {
  341. this.context.router.history.push('/getting-started');
  342. }
  343. handleHotkeyGoToFavourites = () => {
  344. this.context.router.history.push('/favourites');
  345. }
  346. handleHotkeyGoToPinned = () => {
  347. this.context.router.history.push('/pinned');
  348. }
  349. handleHotkeyGoToProfile = () => {
  350. this.context.router.history.push(`/accounts/${me}`);
  351. }
  352. handleHotkeyGoToBlocked = () => {
  353. this.context.router.history.push('/blocks');
  354. }
  355. handleHotkeyGoToMuted = () => {
  356. this.context.router.history.push('/mutes');
  357. }
  358. handleHotkeyGoToRequests = () => {
  359. this.context.router.history.push('/follow_requests');
  360. }
  361. render () {
  362. const { draggingOver } = this.state;
  363. const { children, isComposing, location, dropdownMenuIsOpen } = this.props;
  364. const handlers = {
  365. help: this.handleHotkeyToggleHelp,
  366. new: this.handleHotkeyNew,
  367. search: this.handleHotkeySearch,
  368. forceNew: this.handleHotkeyForceNew,
  369. focusColumn: this.handleHotkeyFocusColumn,
  370. back: this.handleHotkeyBack,
  371. goToHome: this.handleHotkeyGoToHome,
  372. goToNotifications: this.handleHotkeyGoToNotifications,
  373. goToLocal: this.handleHotkeyGoToLocal,
  374. goToFederated: this.handleHotkeyGoToFederated,
  375. goToDirect: this.handleHotkeyGoToDirect,
  376. goToStart: this.handleHotkeyGoToStart,
  377. goToFavourites: this.handleHotkeyGoToFavourites,
  378. goToPinned: this.handleHotkeyGoToPinned,
  379. goToProfile: this.handleHotkeyGoToProfile,
  380. goToBlocked: this.handleHotkeyGoToBlocked,
  381. goToMuted: this.handleHotkeyGoToMuted,
  382. goToRequests: this.handleHotkeyGoToRequests,
  383. };
  384. return (
  385. <HotKeys keyMap={keyMap} handlers={handlers} ref={this.setHotkeysRef} attach={window} focused>
  386. <div className={classNames('ui', { 'is-composing': isComposing })} ref={this.setRef} style={{ pointerEvents: dropdownMenuIsOpen ? 'none' : null }}>
  387. <TabsBar />
  388. <SwitchingColumnsArea location={location} onLayoutChange={this.handleLayoutChange}>
  389. {children}
  390. </SwitchingColumnsArea>
  391. <NotificationsContainer />
  392. <LoadingBarContainer className='loading-bar' />
  393. <ModalContainer />
  394. <UploadArea active={draggingOver} onClose={this.closeUploadModal} />
  395. </div>
  396. </HotKeys>
  397. );
  398. }
  399. }