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.

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