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.

423 lines
13 KiB

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