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.

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