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.

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