闭社主体 forked from https://github.com/tootsuite/mastodon
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.

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