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.

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