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.

461 lines
14 KiB

7 years ago
7 years ago
7 years ago
  1. import React from 'react';
  2. import ImmutablePropTypes from 'react-immutable-proptypes';
  3. import PropTypes from 'prop-types';
  4. import { FormattedMessage, injectIntl } from 'react-intl';
  5. import Permalink from './permalink';
  6. import classnames from 'classnames';
  7. import Icon from 'flavours/glitch/components/icon';
  8. import { autoPlayGif, languages as preloadedLanguages } from 'flavours/glitch/initial_state';
  9. import { decode as decodeIDNA } from 'flavours/glitch/utils/idna';
  10. const textMatchesTarget = (text, origin, host) => {
  11. return (text === origin || text === host
  12. || text.startsWith(origin + '/') || text.startsWith(host + '/')
  13. || 'www.' + text === host || ('www.' + text).startsWith(host + '/'));
  14. };
  15. const isLinkMisleading = (link) => {
  16. let linkTextParts = [];
  17. // Reconstruct visible text, as we do not have much control over how links
  18. // from remote software look, and we can't rely on `innerText` because the
  19. // `invisible` class does not set `display` to `none`.
  20. const walk = (node) => {
  21. switch (node.nodeType) {
  22. case Node.TEXT_NODE:
  23. linkTextParts.push(node.textContent);
  24. break;
  25. case Node.ELEMENT_NODE:
  26. if (node.classList.contains('invisible')) return;
  27. const children = node.childNodes;
  28. for (let i = 0; i < children.length; i++) {
  29. walk(children[i]);
  30. }
  31. break;
  32. }
  33. };
  34. walk(link);
  35. const linkText = linkTextParts.join('');
  36. const targetURL = new URL(link.href);
  37. if (targetURL.protocol === 'magnet:') {
  38. return !linkText.startsWith('magnet:');
  39. }
  40. if (targetURL.protocol === 'xmpp:') {
  41. return !(linkText === targetURL.href || 'xmpp:' + linkText === targetURL.href);
  42. }
  43. // The following may not work with international domain names
  44. if (textMatchesTarget(linkText, targetURL.origin, targetURL.host) || textMatchesTarget(linkText.toLowerCase(), targetURL.origin, targetURL.host)) {
  45. return false;
  46. }
  47. // The link hasn't been recognized, maybe it features an international domain name
  48. const hostname = decodeIDNA(targetURL.hostname).normalize('NFKC');
  49. const host = targetURL.host.replace(targetURL.hostname, hostname);
  50. const origin = targetURL.origin.replace(targetURL.host, host);
  51. const text = linkText.normalize('NFKC');
  52. return !(textMatchesTarget(text, origin, host) || textMatchesTarget(text.toLowerCase(), origin, host));
  53. };
  54. class TranslateButton extends React.PureComponent {
  55. static propTypes = {
  56. translation: ImmutablePropTypes.map,
  57. onClick: PropTypes.func,
  58. };
  59. render () {
  60. const { translation, onClick } = this.props;
  61. if (translation) {
  62. const language = preloadedLanguages.find(lang => lang[0] === translation.get('detected_source_language'));
  63. const languageName = language ? language[2] : translation.get('detected_source_language');
  64. const provider = translation.get('provider');
  65. return (
  66. <div className='translate-button'>
  67. <div className='translate-button__meta'>
  68. <FormattedMessage id='status.translated_from_with' defaultMessage='Translated from {lang} using {provider}' values={{ lang: languageName, provider }} />
  69. </div>
  70. <button className='link-button' onClick={onClick}>
  71. <FormattedMessage id='status.show_original' defaultMessage='Show original' />
  72. </button>
  73. </div>
  74. );
  75. }
  76. return (
  77. <button className='status__content__read-more-button' onClick={onClick}>
  78. <FormattedMessage id='status.translate' defaultMessage='Translate' />
  79. </button>
  80. );
  81. }
  82. }
  83. export default @injectIntl
  84. class StatusContent extends React.PureComponent {
  85. static contextTypes = {
  86. identity: PropTypes.object,
  87. };
  88. static propTypes = {
  89. status: ImmutablePropTypes.map.isRequired,
  90. expanded: PropTypes.bool,
  91. collapsed: PropTypes.bool,
  92. onExpandedToggle: PropTypes.func,
  93. onTranslate: PropTypes.func,
  94. media: PropTypes.node,
  95. extraMedia: PropTypes.node,
  96. mediaIcons: PropTypes.arrayOf(PropTypes.string),
  97. parseClick: PropTypes.func,
  98. disabled: PropTypes.bool,
  99. onUpdate: PropTypes.func,
  100. tagLinks: PropTypes.bool,
  101. rewriteMentions: PropTypes.string,
  102. intl: PropTypes.object,
  103. };
  104. static defaultProps = {
  105. tagLinks: true,
  106. rewriteMentions: 'no',
  107. };
  108. state = {
  109. hidden: true,
  110. };
  111. _updateStatusLinks () {
  112. const node = this.contentsNode;
  113. const { tagLinks, rewriteMentions } = this.props;
  114. if (!node) {
  115. return;
  116. }
  117. const links = node.querySelectorAll('a');
  118. for (var i = 0; i < links.length; ++i) {
  119. let link = links[i];
  120. if (link.classList.contains('status-link')) {
  121. continue;
  122. }
  123. link.classList.add('status-link');
  124. let mention = this.props.status.get('mentions').find(item => link.href === item.get('url'));
  125. if (mention) {
  126. link.addEventListener('click', this.onMentionClick.bind(this, mention), false);
  127. link.setAttribute('title', mention.get('acct'));
  128. if (rewriteMentions !== 'no') {
  129. while (link.firstChild) link.removeChild(link.firstChild);
  130. link.appendChild(document.createTextNode('@'));
  131. const acctSpan = document.createElement('span');
  132. acctSpan.textContent = rewriteMentions === 'acct' ? mention.get('acct') : mention.get('username');
  133. link.appendChild(acctSpan);
  134. }
  135. } else if (link.textContent[0] === '#' || (link.previousSibling && link.previousSibling.textContent && link.previousSibling.textContent[link.previousSibling.textContent.length - 1] === '#')) {
  136. link.addEventListener('click', this.onHashtagClick.bind(this, link.text), false);
  137. } else {
  138. link.addEventListener('click', this.onLinkClick.bind(this), false);
  139. link.setAttribute('title', link.href);
  140. link.classList.add('unhandled-link');
  141. link.setAttribute('target', '_blank');
  142. link.setAttribute('rel', 'noopener nofollow noreferrer');
  143. try {
  144. if (tagLinks && isLinkMisleading(link)) {
  145. // Add a tag besides the link to display its origin
  146. const url = new URL(link.href);
  147. const tag = document.createElement('span');
  148. tag.classList.add('link-origin-tag');
  149. switch (url.protocol) {
  150. case 'xmpp:':
  151. tag.textContent = `[${url.href}]`;
  152. break;
  153. case 'magnet:':
  154. tag.textContent = '(magnet)';
  155. break;
  156. default:
  157. tag.textContent = `[${url.host}]`;
  158. }
  159. link.insertAdjacentText('beforeend', ' ');
  160. link.insertAdjacentElement('beforeend', tag);
  161. }
  162. } catch (e) {
  163. // The URL is invalid, remove the href just to be safe
  164. if (tagLinks && e instanceof TypeError) link.removeAttribute('href');
  165. }
  166. }
  167. }
  168. }
  169. handleMouseEnter = ({ currentTarget }) => {
  170. if (autoPlayGif) {
  171. return;
  172. }
  173. const emojis = currentTarget.querySelectorAll('.custom-emoji');
  174. for (var i = 0; i < emojis.length; i++) {
  175. let emoji = emojis[i];
  176. emoji.src = emoji.getAttribute('data-original');
  177. }
  178. };
  179. handleMouseLeave = ({ currentTarget }) => {
  180. if (autoPlayGif) {
  181. return;
  182. }
  183. const emojis = currentTarget.querySelectorAll('.custom-emoji');
  184. for (var i = 0; i < emojis.length; i++) {
  185. let emoji = emojis[i];
  186. emoji.src = emoji.getAttribute('data-static');
  187. }
  188. };
  189. componentDidMount () {
  190. this._updateStatusLinks();
  191. }
  192. componentDidUpdate () {
  193. this._updateStatusLinks();
  194. if (this.props.onUpdate) this.props.onUpdate();
  195. }
  196. onLinkClick = (e) => {
  197. if (this.props.collapsed) {
  198. if (this.props.parseClick) this.props.parseClick(e);
  199. }
  200. };
  201. onMentionClick = (mention, e) => {
  202. if (this.props.parseClick) {
  203. this.props.parseClick(e, `/@${mention.get('acct')}`);
  204. }
  205. };
  206. onHashtagClick = (hashtag, e) => {
  207. hashtag = hashtag.replace(/^#/, '');
  208. if (this.props.parseClick) {
  209. this.props.parseClick(e, `/tags/${hashtag}`);
  210. }
  211. };
  212. handleMouseDown = (e) => {
  213. this.startXY = [e.clientX, e.clientY];
  214. };
  215. handleMouseUp = (e) => {
  216. const { parseClick, disabled } = this.props;
  217. if (disabled || !this.startXY) {
  218. return;
  219. }
  220. const [ startX, startY ] = this.startXY;
  221. const [ deltaX, deltaY ] = [Math.abs(e.clientX - startX), Math.abs(e.clientY - startY)];
  222. let element = e.target;
  223. while (element !== e.currentTarget) {
  224. if (['button', 'video', 'a', 'label', 'canvas'].includes(element.localName) || element.getAttribute('role') === 'button') {
  225. return;
  226. }
  227. element = element.parentNode;
  228. }
  229. if (deltaX + deltaY < 5 && e.button === 0 && parseClick) {
  230. parseClick(e);
  231. }
  232. this.startXY = null;
  233. };
  234. handleSpoilerClick = (e) => {
  235. e.preventDefault();
  236. if (this.props.onExpandedToggle) {
  237. this.props.onExpandedToggle();
  238. } else {
  239. this.setState({ hidden: !this.state.hidden });
  240. }
  241. };
  242. handleTranslate = () => {
  243. this.props.onTranslate();
  244. };
  245. setContentsRef = (c) => {
  246. this.contentsNode = c;
  247. };
  248. render () {
  249. const {
  250. status,
  251. media,
  252. extraMedia,
  253. mediaIcons,
  254. parseClick,
  255. disabled,
  256. tagLinks,
  257. rewriteMentions,
  258. intl,
  259. } = this.props;
  260. const hidden = this.props.onExpandedToggle ? !this.props.expanded : this.state.hidden;
  261. const renderTranslate = this.props.onTranslate && status.get('translatable');
  262. const content = { __html: status.get('translation') ? status.getIn(['translation', 'content']) : status.get('contentHtml') };
  263. const spoilerContent = { __html: status.get('spoilerHtml') };
  264. const lang = status.get('translation') ? intl.locale : status.get('language');
  265. const classNames = classnames('status__content', {
  266. 'status__content--with-action': parseClick && !disabled,
  267. 'status__content--with-spoiler': status.get('spoiler_text').length > 0,
  268. });
  269. const translateButton = renderTranslate && (
  270. <TranslateButton onClick={this.handleTranslate} translation={status.get('translation')} />
  271. );
  272. if (status.get('spoiler_text').length > 0) {
  273. let mentionsPlaceholder = '';
  274. const mentionLinks = status.get('mentions').map(item => (
  275. <Permalink
  276. to={`/@${item.get('acct')}`}
  277. href={item.get('url')}
  278. key={item.get('id')}
  279. className='mention'
  280. >
  281. @<span>{item.get('username')}</span>
  282. </Permalink>
  283. )).reduce((aggregate, item) => [...aggregate, item, ' '], []);
  284. let toggleText = null;
  285. if (hidden) {
  286. toggleText = [
  287. <FormattedMessage
  288. id='status.show_more'
  289. defaultMessage='Show more'
  290. key='0'
  291. />,
  292. ];
  293. if (mediaIcons) {
  294. mediaIcons.forEach((mediaIcon, idx) => {
  295. toggleText.push(
  296. <Icon
  297. fixedWidth
  298. className='status__content__spoiler-icon'
  299. id={mediaIcon}
  300. aria-hidden='true'
  301. key={`icon-${idx}`}
  302. />,
  303. );
  304. });
  305. }
  306. } else {
  307. toggleText = (
  308. <FormattedMessage
  309. id='status.show_less'
  310. defaultMessage='Show less'
  311. key='0'
  312. />
  313. );
  314. }
  315. if (hidden) {
  316. mentionsPlaceholder = <div>{mentionLinks}</div>;
  317. }
  318. return (
  319. <div className={classNames} tabIndex='0' onMouseDown={this.handleMouseDown} onMouseUp={this.handleMouseUp}>
  320. <p
  321. style={{ marginBottom: hidden && status.get('mentions').isEmpty() ? '0px' : null }}
  322. >
  323. <span dangerouslySetInnerHTML={spoilerContent} className='translate' lang={lang} />
  324. {' '}
  325. <button type='button' className='status__content__spoiler-link' onClick={this.handleSpoilerClick} aria-expanded={!hidden}>
  326. {toggleText}
  327. </button>
  328. </p>
  329. {mentionsPlaceholder}
  330. <div className={`status__content__spoiler ${!hidden ? 'status__content__spoiler--visible' : ''}`}>
  331. <div
  332. ref={this.setContentsRef}
  333. key={`contents-${tagLinks}`}
  334. tabIndex={!hidden ? 0 : null}
  335. dangerouslySetInnerHTML={content}
  336. className='status__content__text translate'
  337. onMouseEnter={this.handleMouseEnter}
  338. onMouseLeave={this.handleMouseLeave}
  339. lang={lang}
  340. />
  341. {!hidden && translateButton}
  342. {media}
  343. </div>
  344. {extraMedia}
  345. </div>
  346. );
  347. } else if (parseClick) {
  348. return (
  349. <div
  350. className={classNames}
  351. onMouseDown={this.handleMouseDown}
  352. onMouseUp={this.handleMouseUp}
  353. tabIndex='0'
  354. >
  355. <div
  356. ref={this.setContentsRef}
  357. key={`contents-${tagLinks}-${rewriteMentions}`}
  358. dangerouslySetInnerHTML={content}
  359. className='status__content__text translate'
  360. tabIndex='0'
  361. onMouseEnter={this.handleMouseEnter}
  362. onMouseLeave={this.handleMouseLeave}
  363. lang={lang}
  364. />
  365. {translateButton}
  366. {media}
  367. {extraMedia}
  368. </div>
  369. );
  370. } else {
  371. return (
  372. <div
  373. className='status__content'
  374. tabIndex='0'
  375. >
  376. <div
  377. ref={this.setContentsRef}
  378. key={`contents-${tagLinks}`}
  379. className='status__content__text translate'
  380. dangerouslySetInnerHTML={content}
  381. tabIndex='0'
  382. onMouseEnter={this.handleMouseEnter}
  383. onMouseLeave={this.handleMouseLeave}
  384. lang={lang}
  385. />
  386. {translateButton}
  387. {media}
  388. {extraMedia}
  389. </div>
  390. );
  391. }
  392. }
  393. }