The code powering m.abunchtell.com https://m.abunchtell.com
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.
 
 
 
 

542 lines
19 KiB

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