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.

478 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']) !== '',
  60. dropdownMenuIsOpen: state.getIn(['dropdown_menu', 'openId']) !== null,
  61. });
  62. const keyMap = {
  63. help: '?',
  64. new: 'n',
  65. search: 's',
  66. forceNew: 'option+n',
  67. focusColumn: ['1', '2', '3', '4', '5', '6', '7', '8', '9'],
  68. reply: 'r',
  69. favourite: 'f',
  70. boost: 'b',
  71. mention: 'm',
  72. open: ['enter', 'o'],
  73. openProfile: 'p',
  74. moveDown: ['down', 'j'],
  75. moveUp: ['up', 'k'],
  76. back: 'backspace',
  77. goToHome: 'g h',
  78. goToNotifications: 'g n',
  79. goToLocal: 'g l',
  80. goToFederated: 'g t',
  81. goToDirect: 'g d',
  82. goToStart: 'g s',
  83. goToFavourites: 'g f',
  84. goToPinned: 'g p',
  85. goToProfile: 'g u',
  86. goToBlocked: 'g b',
  87. goToMuted: 'g m',
  88. goToRequests: 'g r',
  89. toggleHidden: 'x',
  90. };
  91. class SwitchingColumnsArea extends React.PureComponent {
  92. static propTypes = {
  93. children: PropTypes.node,
  94. location: PropTypes.object,
  95. onLayoutChange: PropTypes.func.isRequired,
  96. };
  97. state = {
  98. mobile: isMobile(window.innerWidth),
  99. };
  100. componentWillMount () {
  101. window.addEventListener('resize', this.handleResize, { passive: true });
  102. }
  103. componentDidUpdate (prevProps) {
  104. if (![this.props.location.pathname, '/'].includes(prevProps.location.pathname)) {
  105. this.node.handleChildrenContentChange();
  106. }
  107. }
  108. componentWillUnmount () {
  109. window.removeEventListener('resize', this.handleResize);
  110. }
  111. shouldUpdateScroll (_, { location }) {
  112. return location.state !== previewState;
  113. }
  114. handleResize = debounce(() => {
  115. // The cached heights are no longer accurate, invalidate
  116. this.props.onLayoutChange();
  117. this.setState({ mobile: isMobile(window.innerWidth) });
  118. }, 500, {
  119. trailing: true,
  120. });
  121. setRef = c => {
  122. this.node = c.getWrappedInstance().getWrappedInstance();
  123. }
  124. render () {
  125. const { children } = this.props;
  126. const { mobile } = this.state;
  127. const redirect = mobile ? <Redirect from='/' to='/timelines/home' exact /> : <Redirect from='/' to='/getting-started' exact />;
  128. return (
  129. <ColumnsAreaContainer ref={this.setRef} singleColumn={mobile}>
  130. <WrappedSwitch>
  131. {redirect}
  132. <WrappedRoute path='/getting-started' component={GettingStarted} content={children} />
  133. <WrappedRoute path='/keyboard-shortcuts' component={KeyboardShortcuts} content={children} />
  134. <WrappedRoute path='/timelines/home' component={HomeTimeline} content={children} componentParams={{ shouldUpdateScroll: this.shouldUpdateScroll }} />
  135. <WrappedRoute path='/timelines/public' exact component={PublicTimeline} content={children} componentParams={{ shouldUpdateScroll: this.shouldUpdateScroll }} />
  136. <WrappedRoute path='/timelines/public/media' component={PublicTimeline} content={children} componentParams={{ shouldUpdateScroll: this.shouldUpdateScroll, onlyMedia: true }} />
  137. <WrappedRoute path='/timelines/public/local' exact component={CommunityTimeline} content={children} componentParams={{ shouldUpdateScroll: this.shouldUpdateScroll }} />
  138. <WrappedRoute path='/timelines/public/local/media' component={CommunityTimeline} content={children} componentParams={{ shouldUpdateScroll: this.shouldUpdateScroll, onlyMedia: true }} />
  139. <WrappedRoute path='/timelines/direct' component={DirectTimeline} content={children} componentParams={{ shouldUpdateScroll: this.shouldUpdateScroll }} />
  140. <WrappedRoute path='/timelines/tag/:id' component={HashtagTimeline} content={children} componentParams={{ shouldUpdateScroll: this.shouldUpdateScroll }} />
  141. <WrappedRoute path='/timelines/list/:id' component={ListTimeline} content={children} componentParams={{ shouldUpdateScroll: this.shouldUpdateScroll }} />
  142. <WrappedRoute path='/notifications' component={Notifications} content={children} componentParams={{ shouldUpdateScroll: this.shouldUpdateScroll }} />
  143. <WrappedRoute path='/favourites' component={FavouritedStatuses} content={children} componentParams={{ shouldUpdateScroll: this.shouldUpdateScroll }} />
  144. <WrappedRoute path='/pinned' component={PinnedStatuses} content={children} componentParams={{ shouldUpdateScroll: this.shouldUpdateScroll }} />
  145. <WrappedRoute path='/search' component={Compose} content={children} componentParams={{ isSearchPage: true }} />
  146. <WrappedRoute path='/statuses/new' component={Compose} content={children} />
  147. <WrappedRoute path='/statuses/:statusId' exact component={Status} content={children} componentParams={{ shouldUpdateScroll: this.shouldUpdateScroll }} />
  148. <WrappedRoute path='/statuses/:statusId/reblogs' component={Reblogs} content={children} componentParams={{ shouldUpdateScroll: this.shouldUpdateScroll }} />
  149. <WrappedRoute path='/statuses/:statusId/favourites' component={Favourites} content={children} componentParams={{ shouldUpdateScroll: this.shouldUpdateScroll }} />
  150. <WrappedRoute path='/accounts/:accountId' exact component={AccountTimeline} content={children} componentParams={{ shouldUpdateScroll: this.shouldUpdateScroll }} />
  151. <WrappedRoute path='/accounts/:accountId/with_replies' component={AccountTimeline} content={children} componentParams={{ shouldUpdateScroll: this.shouldUpdateScroll, withReplies: true }} />
  152. <WrappedRoute path='/accounts/:accountId/followers' component={Followers} content={children} componentParams={{ shouldUpdateScroll: this.shouldUpdateScroll }} />
  153. <WrappedRoute path='/accounts/:accountId/following' component={Following} content={children} componentParams={{ shouldUpdateScroll: this.shouldUpdateScroll }} />
  154. <WrappedRoute path='/accounts/:accountId/media' component={AccountGallery} content={children} componentParams={{ shouldUpdateScroll: this.shouldUpdateScroll }} />
  155. <WrappedRoute path='/follow_requests' component={FollowRequests} content={children} componentParams={{ shouldUpdateScroll: this.shouldUpdateScroll }} />
  156. <WrappedRoute path='/blocks' component={Blocks} content={children} componentParams={{ shouldUpdateScroll: this.shouldUpdateScroll }} />
  157. <WrappedRoute path='/domain_blocks' component={DomainBlocks} content={children} componentParams={{ shouldUpdateScroll: this.shouldUpdateScroll }} />
  158. <WrappedRoute path='/mutes' component={Mutes} content={children} componentParams={{ shouldUpdateScroll: this.shouldUpdateScroll }} />
  159. <WrappedRoute path='/lists' component={Lists} content={children} componentParams={{ shouldUpdateScroll: this.shouldUpdateScroll }} />
  160. <WrappedRoute component={GenericNotFound} content={children} />
  161. </WrappedSwitch>
  162. </ColumnsAreaContainer>
  163. );
  164. }
  165. }
  166. @connect(mapStateToProps)
  167. @injectIntl
  168. @withRouter
  169. export default class UI extends React.PureComponent {
  170. static contextTypes = {
  171. router: PropTypes.object.isRequired,
  172. };
  173. static propTypes = {
  174. dispatch: PropTypes.func.isRequired,
  175. children: PropTypes.node,
  176. isComposing: PropTypes.bool,
  177. hasComposingText: 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 } = this.props;
  187. if (isComposing && hasComposingText) {
  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. if (e.dataTransfer && e.dataTransfer.files.length === 1) {
  223. this.props.dispatch(uploadCompose(e.dataTransfer.files));
  224. }
  225. }
  226. handleDragLeave = (e) => {
  227. e.preventDefault();
  228. e.stopPropagation();
  229. this.dragTargets = this.dragTargets.filter(el => el !== e.target && this.node.contains(el));
  230. if (this.dragTargets.length > 0) {
  231. return;
  232. }
  233. this.setState({ draggingOver: false });
  234. }
  235. closeUploadModal = () => {
  236. this.setState({ draggingOver: false });
  237. }
  238. handleServiceWorkerPostMessage = ({ data }) => {
  239. if (data.type === 'navigate') {
  240. this.context.router.history.push(data.path);
  241. } else {
  242. console.warn('Unknown message type:', data.type);
  243. }
  244. }
  245. componentWillMount () {
  246. window.addEventListener('beforeunload', this.handleBeforeUnload, false);
  247. document.addEventListener('dragenter', this.handleDragEnter, false);
  248. document.addEventListener('dragover', this.handleDragOver, false);
  249. document.addEventListener('drop', this.handleDrop, false);
  250. document.addEventListener('dragleave', this.handleDragLeave, false);
  251. document.addEventListener('dragend', this.handleDragEnd, false);
  252. if ('serviceWorker' in navigator) {
  253. navigator.serviceWorker.addEventListener('message', this.handleServiceWorkerPostMessage);
  254. }
  255. this.props.dispatch(expandHomeTimeline());
  256. this.props.dispatch(expandNotifications());
  257. setTimeout(() => this.props.dispatch(fetchFilters()), 500);
  258. }
  259. componentDidMount () {
  260. this.hotkeys.__mousetrap__.stopCallback = (e, element) => {
  261. return ['TEXTAREA', 'SELECT', 'INPUT'].includes(element.tagName);
  262. };
  263. }
  264. componentWillUnmount () {
  265. window.removeEventListener('beforeunload', this.handleBeforeUnload);
  266. document.removeEventListener('dragenter', this.handleDragEnter);
  267. document.removeEventListener('dragover', this.handleDragOver);
  268. document.removeEventListener('drop', this.handleDrop);
  269. document.removeEventListener('dragleave', this.handleDragLeave);
  270. document.removeEventListener('dragend', this.handleDragEnd);
  271. }
  272. setRef = c => {
  273. this.node = c;
  274. }
  275. handleHotkeyNew = e => {
  276. e.preventDefault();
  277. const element = this.node.querySelector('.compose-form__autosuggest-wrapper textarea');
  278. if (element) {
  279. element.focus();
  280. }
  281. }
  282. handleHotkeySearch = e => {
  283. e.preventDefault();
  284. const element = this.node.querySelector('.search__input');
  285. if (element) {
  286. element.focus();
  287. }
  288. }
  289. handleHotkeyForceNew = e => {
  290. this.handleHotkeyNew(e);
  291. this.props.dispatch(resetCompose());
  292. }
  293. handleHotkeyFocusColumn = e => {
  294. const index = (e.key * 1) + 1; // First child is drawer, skip that
  295. const column = this.node.querySelector(`.column:nth-child(${index})`);
  296. if (column) {
  297. const status = column.querySelector('.focusable');
  298. if (status) {
  299. status.focus();
  300. }
  301. }
  302. }
  303. handleHotkeyBack = () => {
  304. if (window.history && window.history.length === 1) {
  305. this.context.router.history.push('/');
  306. } else {
  307. this.context.router.history.goBack();
  308. }
  309. }
  310. setHotkeysRef = c => {
  311. this.hotkeys = c;
  312. }
  313. handleHotkeyToggleHelp = () => {
  314. if (this.props.location.pathname === '/keyboard-shortcuts') {
  315. this.context.router.history.goBack();
  316. } else {
  317. this.context.router.history.push('/keyboard-shortcuts');
  318. }
  319. }
  320. handleHotkeyGoToHome = () => {
  321. this.context.router.history.push('/timelines/home');
  322. }
  323. handleHotkeyGoToNotifications = () => {
  324. this.context.router.history.push('/notifications');
  325. }
  326. handleHotkeyGoToLocal = () => {
  327. this.context.router.history.push('/timelines/public/local');
  328. }
  329. handleHotkeyGoToFederated = () => {
  330. this.context.router.history.push('/timelines/public');
  331. }
  332. handleHotkeyGoToDirect = () => {
  333. this.context.router.history.push('/timelines/direct');
  334. }
  335. handleHotkeyGoToStart = () => {
  336. this.context.router.history.push('/getting-started');
  337. }
  338. handleHotkeyGoToFavourites = () => {
  339. this.context.router.history.push('/favourites');
  340. }
  341. handleHotkeyGoToPinned = () => {
  342. this.context.router.history.push('/pinned');
  343. }
  344. handleHotkeyGoToProfile = () => {
  345. this.context.router.history.push(`/accounts/${me}`);
  346. }
  347. handleHotkeyGoToBlocked = () => {
  348. this.context.router.history.push('/blocks');
  349. }
  350. handleHotkeyGoToMuted = () => {
  351. this.context.router.history.push('/mutes');
  352. }
  353. handleHotkeyGoToRequests = () => {
  354. this.context.router.history.push('/follow_requests');
  355. }
  356. render () {
  357. const { draggingOver } = this.state;
  358. const { children, isComposing, location, dropdownMenuIsOpen } = this.props;
  359. const handlers = {
  360. help: this.handleHotkeyToggleHelp,
  361. new: this.handleHotkeyNew,
  362. search: this.handleHotkeySearch,
  363. forceNew: this.handleHotkeyForceNew,
  364. focusColumn: this.handleHotkeyFocusColumn,
  365. back: this.handleHotkeyBack,
  366. goToHome: this.handleHotkeyGoToHome,
  367. goToNotifications: this.handleHotkeyGoToNotifications,
  368. goToLocal: this.handleHotkeyGoToLocal,
  369. goToFederated: this.handleHotkeyGoToFederated,
  370. goToDirect: this.handleHotkeyGoToDirect,
  371. goToStart: this.handleHotkeyGoToStart,
  372. goToFavourites: this.handleHotkeyGoToFavourites,
  373. goToPinned: this.handleHotkeyGoToPinned,
  374. goToProfile: this.handleHotkeyGoToProfile,
  375. goToBlocked: this.handleHotkeyGoToBlocked,
  376. goToMuted: this.handleHotkeyGoToMuted,
  377. goToRequests: this.handleHotkeyGoToRequests,
  378. };
  379. return (
  380. <HotKeys keyMap={keyMap} handlers={handlers} ref={this.setHotkeysRef}>
  381. <div className={classNames('ui', { 'is-composing': isComposing })} ref={this.setRef} style={{ pointerEvents: dropdownMenuIsOpen ? 'none' : null }}>
  382. <TabsBar />
  383. <SwitchingColumnsArea location={location} onLayoutChange={this.handleLayoutChange}>
  384. {children}
  385. </SwitchingColumnsArea>
  386. <NotificationsContainer />
  387. <LoadingBarContainer className='loading-bar' />
  388. <ModalContainer />
  389. <UploadArea active={draggingOver} onClose={this.closeUploadModal} />
  390. </div>
  391. </HotKeys>
  392. );
  393. }
  394. }