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.

462 lines
14 KiB

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