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.

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