The code powering m.abunchtell.com https://m.abunchtell.com
Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.
 
 
 
 

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