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.

451 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='/statuses/new' component={Compose} content={children} />
  133. <WrappedRoute path='/statuses/:statusId' exact component={Status} content={children} />
  134. <WrappedRoute path='/statuses/:statusId/reblogs' component={Reblogs} content={children} />
  135. <WrappedRoute path='/statuses/:statusId/favourites' component={Favourites} content={children} />
  136. <WrappedRoute path='/accounts/:accountId' exact component={AccountTimeline} content={children} />
  137. <WrappedRoute path='/accounts/:accountId/with_replies' component={AccountTimeline} content={children} componentParams={{ withReplies: true }} />
  138. <WrappedRoute path='/accounts/:accountId/followers' component={Followers} content={children} />
  139. <WrappedRoute path='/accounts/:accountId/following' component={Following} content={children} />
  140. <WrappedRoute path='/accounts/:accountId/media' component={AccountGallery} content={children} />
  141. <WrappedRoute path='/follow_requests' component={FollowRequests} content={children} />
  142. <WrappedRoute path='/blocks' component={Blocks} content={children} />
  143. <WrappedRoute path='/domain_blocks' component={DomainBlocks} content={children} />
  144. <WrappedRoute path='/mutes' component={Mutes} content={children} />
  145. <WrappedRoute path='/lists' component={Lists} content={children} />
  146. <WrappedRoute component={GenericNotFound} content={children} />
  147. </WrappedSwitch>
  148. </ColumnsAreaContainer>
  149. );
  150. }
  151. }
  152. @connect(mapStateToProps)
  153. @injectIntl
  154. @withRouter
  155. export default class UI extends React.PureComponent {
  156. static contextTypes = {
  157. router: PropTypes.object.isRequired,
  158. };
  159. static propTypes = {
  160. dispatch: PropTypes.func.isRequired,
  161. children: PropTypes.node,
  162. isComposing: PropTypes.bool,
  163. hasComposingText: PropTypes.bool,
  164. location: PropTypes.object,
  165. intl: PropTypes.object.isRequired,
  166. dropdownMenuIsOpen: PropTypes.bool,
  167. };
  168. state = {
  169. draggingOver: false,
  170. };
  171. handleBeforeUnload = (e) => {
  172. const { intl, isComposing, hasComposingText } = this.props;
  173. if (isComposing && hasComposingText) {
  174. // Setting returnValue to any string causes confirmation dialog.
  175. // Many browsers no longer display this text to users,
  176. // but we set user-friendly message for other browsers, e.g. Edge.
  177. e.returnValue = intl.formatMessage(messages.beforeUnload);
  178. }
  179. }
  180. handleLayoutChange = () => {
  181. // The cached heights are no longer accurate, invalidate
  182. this.props.dispatch(clearHeight());
  183. }
  184. handleDragEnter = (e) => {
  185. e.preventDefault();
  186. if (!this.dragTargets) {
  187. this.dragTargets = [];
  188. }
  189. if (this.dragTargets.indexOf(e.target) === -1) {
  190. this.dragTargets.push(e.target);
  191. }
  192. if (e.dataTransfer && e.dataTransfer.types.includes('Files')) {
  193. this.setState({ draggingOver: true });
  194. }
  195. }
  196. handleDragOver = (e) => {
  197. e.preventDefault();
  198. e.stopPropagation();
  199. try {
  200. e.dataTransfer.dropEffect = 'copy';
  201. } catch (err) {
  202. }
  203. return false;
  204. }
  205. handleDrop = (e) => {
  206. e.preventDefault();
  207. this.setState({ draggingOver: false });
  208. if (e.dataTransfer && e.dataTransfer.files.length === 1) {
  209. this.props.dispatch(uploadCompose(e.dataTransfer.files));
  210. }
  211. }
  212. handleDragLeave = (e) => {
  213. e.preventDefault();
  214. e.stopPropagation();
  215. this.dragTargets = this.dragTargets.filter(el => el !== e.target && this.node.contains(el));
  216. if (this.dragTargets.length > 0) {
  217. return;
  218. }
  219. this.setState({ draggingOver: false });
  220. }
  221. closeUploadModal = () => {
  222. this.setState({ draggingOver: false });
  223. }
  224. handleServiceWorkerPostMessage = ({ data }) => {
  225. if (data.type === 'navigate') {
  226. this.context.router.history.push(data.path);
  227. } else {
  228. console.warn('Unknown message type:', data.type);
  229. }
  230. }
  231. componentWillMount () {
  232. window.addEventListener('beforeunload', this.handleBeforeUnload, false);
  233. document.addEventListener('dragenter', this.handleDragEnter, false);
  234. document.addEventListener('dragover', this.handleDragOver, false);
  235. document.addEventListener('drop', this.handleDrop, false);
  236. document.addEventListener('dragleave', this.handleDragLeave, false);
  237. document.addEventListener('dragend', this.handleDragEnd, false);
  238. if ('serviceWorker' in navigator) {
  239. navigator.serviceWorker.addEventListener('message', this.handleServiceWorkerPostMessage);
  240. }
  241. this.props.dispatch(expandHomeTimeline());
  242. this.props.dispatch(expandNotifications());
  243. }
  244. componentDidMount () {
  245. this.hotkeys.__mousetrap__.stopCallback = (e, element) => {
  246. return ['TEXTAREA', 'SELECT', 'INPUT'].includes(element.tagName);
  247. };
  248. }
  249. componentWillUnmount () {
  250. window.removeEventListener('beforeunload', this.handleBeforeUnload);
  251. document.removeEventListener('dragenter', this.handleDragEnter);
  252. document.removeEventListener('dragover', this.handleDragOver);
  253. document.removeEventListener('drop', this.handleDrop);
  254. document.removeEventListener('dragleave', this.handleDragLeave);
  255. document.removeEventListener('dragend', this.handleDragEnd);
  256. }
  257. setRef = c => {
  258. this.node = c;
  259. }
  260. handleHotkeyNew = e => {
  261. e.preventDefault();
  262. const element = this.node.querySelector('.compose-form__autosuggest-wrapper textarea');
  263. if (element) {
  264. element.focus();
  265. }
  266. }
  267. handleHotkeySearch = e => {
  268. e.preventDefault();
  269. const element = this.node.querySelector('.search__input');
  270. if (element) {
  271. element.focus();
  272. }
  273. }
  274. handleHotkeyForceNew = e => {
  275. this.handleHotkeyNew(e);
  276. this.props.dispatch(resetCompose());
  277. }
  278. handleHotkeyFocusColumn = e => {
  279. const index = (e.key * 1) + 1; // First child is drawer, skip that
  280. const column = this.node.querySelector(`.column:nth-child(${index})`);
  281. if (column) {
  282. const status = column.querySelector('.focusable');
  283. if (status) {
  284. status.focus();
  285. }
  286. }
  287. }
  288. handleHotkeyBack = () => {
  289. if (window.history && window.history.length === 1) {
  290. this.context.router.history.push('/');
  291. } else {
  292. this.context.router.history.goBack();
  293. }
  294. }
  295. setHotkeysRef = c => {
  296. this.hotkeys = c;
  297. }
  298. handleHotkeyToggleHelp = () => {
  299. if (this.props.location.pathname === '/keyboard-shortcuts') {
  300. this.context.router.history.goBack();
  301. } else {
  302. this.context.router.history.push('/keyboard-shortcuts');
  303. }
  304. }
  305. handleHotkeyGoToHome = () => {
  306. this.context.router.history.push('/timelines/home');
  307. }
  308. handleHotkeyGoToNotifications = () => {
  309. this.context.router.history.push('/notifications');
  310. }
  311. handleHotkeyGoToLocal = () => {
  312. this.context.router.history.push('/timelines/public/local');
  313. }
  314. handleHotkeyGoToFederated = () => {
  315. this.context.router.history.push('/timelines/public');
  316. }
  317. handleHotkeyGoToStart = () => {
  318. this.context.router.history.push('/getting-started');
  319. }
  320. handleHotkeyGoToFavourites = () => {
  321. this.context.router.history.push('/favourites');
  322. }
  323. handleHotkeyGoToPinned = () => {
  324. this.context.router.history.push('/pinned');
  325. }
  326. handleHotkeyGoToProfile = () => {
  327. this.context.router.history.push(`/accounts/${me}`);
  328. }
  329. handleHotkeyGoToBlocked = () => {
  330. this.context.router.history.push('/blocks');
  331. }
  332. handleHotkeyGoToMuted = () => {
  333. this.context.router.history.push('/mutes');
  334. }
  335. render () {
  336. const { draggingOver } = this.state;
  337. const { children, isComposing, location, dropdownMenuIsOpen } = this.props;
  338. const handlers = {
  339. help: this.handleHotkeyToggleHelp,
  340. new: this.handleHotkeyNew,
  341. search: this.handleHotkeySearch,
  342. forceNew: this.handleHotkeyForceNew,
  343. focusColumn: this.handleHotkeyFocusColumn,
  344. back: this.handleHotkeyBack,
  345. goToHome: this.handleHotkeyGoToHome,
  346. goToNotifications: this.handleHotkeyGoToNotifications,
  347. goToLocal: this.handleHotkeyGoToLocal,
  348. goToFederated: this.handleHotkeyGoToFederated,
  349. goToStart: this.handleHotkeyGoToStart,
  350. goToFavourites: this.handleHotkeyGoToFavourites,
  351. goToPinned: this.handleHotkeyGoToPinned,
  352. goToProfile: this.handleHotkeyGoToProfile,
  353. goToBlocked: this.handleHotkeyGoToBlocked,
  354. goToMuted: this.handleHotkeyGoToMuted,
  355. };
  356. return (
  357. <HotKeys keyMap={keyMap} handlers={handlers} ref={this.setHotkeysRef}>
  358. <div className={classNames('ui', { 'is-composing': isComposing })} ref={this.setRef} style={{ pointerEvents: dropdownMenuIsOpen ? 'none' : null }}>
  359. <TabsBar />
  360. <SwitchingColumnsArea location={location} onLayoutChange={this.handleLayoutChange}>
  361. {children}
  362. </SwitchingColumnsArea>
  363. <NotificationsContainer />
  364. <LoadingBarContainer className='loading-bar' />
  365. <ModalContainer />
  366. <UploadArea active={draggingOver} onClose={this.closeUploadModal} />
  367. </div>
  368. </HotKeys>
  369. );
  370. }
  371. }