Files
mastodon-sakyey/app/javascript/mastodon/components/status_content.jsx

303 lines
9.3 KiB
React
Raw Normal View History

import PropTypes from 'prop-types';
import { PureComponent } from 'react';
import { FormattedMessage, injectIntl } from 'react-intl';
import classnames from 'classnames';
import { withRouter } from 'react-router-dom';
import ImmutablePropTypes from 'react-immutable-proptypes';
import { connect } from 'react-redux';
import ChevronRightIcon from '@/material-icons/400-24px/chevron_right.svg?react';
import { Icon } from 'mastodon/components/icon';
2025-03-28 13:34:51 +01:00
import { Poll } from 'mastodon/components/poll';
import { identityContextPropShape, withIdentity } from 'mastodon/identity_context';
2025-09-30 15:06:02 +02:00
import { languages as preloadedLanguages } from 'mastodon/initial_state';
import { isModernEmojiEnabled } from '../utils/environment';
2025-09-30 15:06:02 +02:00
import { EmojiHTML } from './emoji/html';
2025-10-06 11:31:10 +02:00
import { HandledLink } from './status/handled_link';
2025-09-30 15:06:02 +02:00
const MAX_HEIGHT = 706; // 22px * 32 (+ 2px padding at the top)
/**
*
* @param {any} status
* @returns {string}
*/
export function getStatusContent(status) {
return status.getIn(['translation', 'contentHtml']) || status.get('contentHtml');
}
2023-05-23 10:52:27 +02:00
class TranslateButton extends PureComponent {
static propTypes = {
translation: ImmutablePropTypes.map,
onClick: PropTypes.func,
};
render () {
const { translation, onClick } = this.props;
if (translation) {
const language = preloadedLanguages.find(lang => lang[0] === translation.get('detected_source_language'));
2025-01-03 16:29:25 +01:00
const languageName = language ? language[1] : translation.get('detected_source_language');
const provider = translation.get('provider');
return (
<div className='translate-button'>
<button className='link-button' onClick={onClick}>
<FormattedMessage id='status.show_original' defaultMessage='Show original' />
</button>
<div className='translate-button__meta'>
<FormattedMessage id='status.translated_from_with' defaultMessage='Translated from {lang} using {provider}' values={{ lang: languageName, provider }} />
</div>
</div>
);
}
return (
2023-07-08 00:12:31 +02:00
<button className='status__content__translate-button' onClick={onClick}>
<FormattedMessage id='status.translate' defaultMessage='Translate' />
</button>
);
}
}
const mapStateToProps = state => ({
languages: state.getIn(['server', 'translationLanguages', 'items']),
});
2023-05-23 10:52:27 +02:00
class StatusContent extends PureComponent {
static propTypes = {
identity: identityContextPropShape,
status: ImmutablePropTypes.map.isRequired,
statusContent: PropTypes.string,
onTranslate: PropTypes.func,
onClick: PropTypes.func,
collapsible: PropTypes.bool,
Summary: fix slowness due to layout thrashing when reloading a large … (#12661) * Summary: fix slowness due to layout thrashing when reloading a large set of status updates in order to limit the maximum size of a status in a list view (e.g. the home timeline), so as to avoid having to scroll all the way through an abnormally large status update (see https://github.com/tootsuite/mastodon/pull/8205), the following steps are taken: •the element containing the status is rendered in the browser •its height is calculated, to determine if it exceeds the maximum height threshold. Unfortunately for performance, these steps are carried out in the componentDidMount(/Update) method, which also performs style modifications on the element. The combination of height request and style modification during javascript evaluation in the browser leads to layout-thrashing, where the elements are repeatedly re-laid-out (see https://developers.google.com/web/fundamentals/performance/rendering/avoid-large-complex-layouts-and-layout-thrashing & https://developer.mozilla.org/en-US/docs/Mozilla/Firefox/Performance_best_practices_for_Firefox_fe_engineers). The solution implemented here is to memoize the collapsed state in Redux the first time the status is seen (e.g. when fetched as part of a small batch, to populate the home timeline) , so that on subsequent re-renders, the value can be queried, rather than recalculated. This strategy is derived from https://github.com/tootsuite/mastodon/pull/4439 & https://github.com/tootsuite/mastodon/pull/4909, and should resolve https://github.com/tootsuite/mastodon/issues/12455. Andrew Lin (https://github.com/onethreeseven) is thanked for his assistance in root cause analysis and solution brainstorming * remove getSnapshotBeforeUpdate from status * remove componentWillUnmount from status * persist last-intersected status update and restore when ScrollableList is restored e.g. when navigating from home-timeline to a status conversational thread and <Back again * cache currently-viewing status id to avoid calling redux with identical value * refactor collapse toggle to pass explicit boolean
2019-12-28 23:39:48 -05:00
onCollapsedToggle: PropTypes.func,
languages: ImmutablePropTypes.map,
intl: PropTypes.object,
// from react-router
match: PropTypes.object.isRequired,
location: PropTypes.object.isRequired,
history: PropTypes.object.isRequired
};
_updateStatusLinks () {
const node = this.node;
if (!node) {
return;
}
const { status, onCollapsedToggle } = this.props;
2025-10-06 11:31:10 +02:00
if (status.get('collapsed', null) === null && onCollapsedToggle) {
const { collapsible, onClick } = this.props;
const collapsed =
collapsible
&& onClick
&& node.clientHeight > MAX_HEIGHT
&& status.get('spoiler_text').length === 0;
onCollapsedToggle(collapsed);
}
// Exit if modern emoji is enabled, as it handles links using the HandledLink component.
if (isModernEmojiEnabled()) {
return;
}
const links = node.querySelectorAll('a');
let link, mention;
for (var i = 0; i < links.length; ++i) {
link = links[i];
if (link.classList.contains('status-link')) {
continue;
}
link.classList.add('status-link');
mention = this.props.status.get('mentions').find(item => link.href === item.get('url'));
if (mention) {
link.addEventListener('click', this.onMentionClick.bind(this, mention), false);
link.setAttribute('title', `@${mention.get('acct')}`);
link.setAttribute('href', `/@${mention.get('acct')}`);
link.setAttribute('data-hover-card-account', mention.get('id'));
2016-11-05 17:54:19 +01:00
} else if (link.textContent[0] === '#' || (link.previousSibling && link.previousSibling.textContent && link.previousSibling.textContent[link.previousSibling.textContent.length - 1] === '#')) {
2016-11-05 15:20:05 +01:00
link.addEventListener('click', this.onHashtagClick.bind(this, link.text), false);
link.setAttribute('href', `/tags/${link.text.replace(/^#/, '')}`);
link.setAttribute('data-menu-hashtag', this.props.status.getIn(['account', 'id']));
} else {
link.setAttribute('title', link.href);
link.classList.add('unhandled-link');
}
}
}
componentDidMount () {
this._updateStatusLinks();
}
componentDidUpdate () {
this._updateStatusLinks();
}
onMentionClick = (mention, e) => {
if (this.props.history && e.button === 0 && !(e.ctrlKey || e.metaKey)) {
e.preventDefault();
this.props.history.push(`/@${mention.get('acct')}`);
}
2023-01-29 19:45:35 -05:00
};
2016-10-03 18:17:06 +02:00
onHashtagClick = (hashtag, e) => {
hashtag = hashtag.replace(/^#/, '');
2016-11-05 15:20:05 +01:00
if (this.props.history && e.button === 0 && !(e.ctrlKey || e.metaKey)) {
2016-11-05 15:20:05 +01:00
e.preventDefault();
this.props.history.push(`/tags/${hashtag}`);
2016-11-05 15:20:05 +01:00
}
2023-01-29 19:45:35 -05:00
};
handleMouseDown = (e) => {
this.startXY = [e.clientX, e.clientY];
2023-01-29 19:45:35 -05:00
};
handleMouseUp = (e) => {
if (!this.startXY) {
return;
}
const [ startX, startY ] = this.startXY;
const [ deltaX, deltaY ] = [Math.abs(e.clientX - startX), Math.abs(e.clientY - startY)];
let element = e.target;
while (element) {
if (element.localName === 'button' || element.localName === 'a' || element.localName === 'label') {
return;
}
element = element.parentNode;
}
if (deltaX + deltaY < 5 && (e.button === 0 || e.button === 1) && e.detail >= 1 && this.props.onClick) {
this.props.onClick(e);
}
this.startXY = null;
2023-01-29 19:45:35 -05:00
};
handleTranslate = () => {
this.props.onTranslate();
2023-01-29 19:45:35 -05:00
};
setRef = (c) => {
this.node = c;
2023-01-29 19:45:35 -05:00
};
handleElement = (element, { key, ...props }, children) => {
2025-10-06 11:31:10 +02:00
if (element instanceof HTMLAnchorElement) {
const mention = this.props.status.get('mentions').find(item => element.href === item.get('url'));
return (
<HandledLink
{...props}
href={element.href}
text={element.innerText}
hashtagAccountId={this.props.status.getIn(['account', 'id'])}
mention={mention?.toJSON()}
2025-10-06 11:31:10 +02:00
key={key}
>
{children}
</HandledLink>
2025-10-06 11:31:10 +02:00
);
} else if (element.classList.contains('quote-inline')) {
return null;
2025-10-06 11:31:10 +02:00
}
return undefined;
}
render () {
const { status, intl, statusContent } = this.props;
Summary: fix slowness due to layout thrashing when reloading a large … (#12661) * Summary: fix slowness due to layout thrashing when reloading a large set of status updates in order to limit the maximum size of a status in a list view (e.g. the home timeline), so as to avoid having to scroll all the way through an abnormally large status update (see https://github.com/tootsuite/mastodon/pull/8205), the following steps are taken: •the element containing the status is rendered in the browser •its height is calculated, to determine if it exceeds the maximum height threshold. Unfortunately for performance, these steps are carried out in the componentDidMount(/Update) method, which also performs style modifications on the element. The combination of height request and style modification during javascript evaluation in the browser leads to layout-thrashing, where the elements are repeatedly re-laid-out (see https://developers.google.com/web/fundamentals/performance/rendering/avoid-large-complex-layouts-and-layout-thrashing & https://developer.mozilla.org/en-US/docs/Mozilla/Firefox/Performance_best_practices_for_Firefox_fe_engineers). The solution implemented here is to memoize the collapsed state in Redux the first time the status is seen (e.g. when fetched as part of a small batch, to populate the home timeline) , so that on subsequent re-renders, the value can be queried, rather than recalculated. This strategy is derived from https://github.com/tootsuite/mastodon/pull/4439 & https://github.com/tootsuite/mastodon/pull/4909, and should resolve https://github.com/tootsuite/mastodon/issues/12455. Andrew Lin (https://github.com/onethreeseven) is thanked for his assistance in root cause analysis and solution brainstorming * remove getSnapshotBeforeUpdate from status * remove componentWillUnmount from status * persist last-intersected status update and restore when ScrollableList is restored e.g. when navigating from home-timeline to a status conversational thread and <Back again * cache currently-viewing status id to avoid calling redux with identical value * refactor collapse toggle to pass explicit boolean
2019-12-28 23:39:48 -05:00
const renderReadMore = this.props.onClick && status.get('collapsed');
const contentLocale = intl.locale.replace(/[_-].*/, '');
const targetLanguages = this.props.languages?.get(status.get('language') || 'und');
const renderTranslate = this.props.onTranslate && this.props.identity.signedIn && ['public', 'unlisted'].includes(status.get('visibility')) && status.get('search_index').trim().length > 0 && targetLanguages?.includes(contentLocale);
2016-11-30 16:10:19 +01:00
2025-07-22 16:43:15 +02:00
const content = statusContent ?? getStatusContent(status);
const language = status.getIn(['translation', 'language']) || status.get('language');
const classNames = classnames('status__content', {
'status__content--with-action': this.props.onClick && this.props.history,
Summary: fix slowness due to layout thrashing when reloading a large … (#12661) * Summary: fix slowness due to layout thrashing when reloading a large set of status updates in order to limit the maximum size of a status in a list view (e.g. the home timeline), so as to avoid having to scroll all the way through an abnormally large status update (see https://github.com/tootsuite/mastodon/pull/8205), the following steps are taken: •the element containing the status is rendered in the browser •its height is calculated, to determine if it exceeds the maximum height threshold. Unfortunately for performance, these steps are carried out in the componentDidMount(/Update) method, which also performs style modifications on the element. The combination of height request and style modification during javascript evaluation in the browser leads to layout-thrashing, where the elements are repeatedly re-laid-out (see https://developers.google.com/web/fundamentals/performance/rendering/avoid-large-complex-layouts-and-layout-thrashing & https://developer.mozilla.org/en-US/docs/Mozilla/Firefox/Performance_best_practices_for_Firefox_fe_engineers). The solution implemented here is to memoize the collapsed state in Redux the first time the status is seen (e.g. when fetched as part of a small batch, to populate the home timeline) , so that on subsequent re-renders, the value can be queried, rather than recalculated. This strategy is derived from https://github.com/tootsuite/mastodon/pull/4439 & https://github.com/tootsuite/mastodon/pull/4909, and should resolve https://github.com/tootsuite/mastodon/issues/12455. Andrew Lin (https://github.com/onethreeseven) is thanked for his assistance in root cause analysis and solution brainstorming * remove getSnapshotBeforeUpdate from status * remove componentWillUnmount from status * persist last-intersected status update and restore when ScrollableList is restored e.g. when navigating from home-timeline to a status conversational thread and <Back again * cache currently-viewing status id to avoid calling redux with identical value * refactor collapse toggle to pass explicit boolean
2019-12-28 23:39:48 -05:00
'status__content--collapsed': renderReadMore,
});
const readMoreButton = renderReadMore && (
<button className='status__content__read-more-button' onClick={this.props.onClick} key='read-more'>
<FormattedMessage id='status.read_more' defaultMessage='Read more' /><Icon id='angle-right' icon={ChevronRightIcon} />
</button>
);
const translateButton = renderTranslate && (
<TranslateButton onClick={this.handleTranslate} translation={status.get('translation')} />
);
const poll = !!status.get('poll') && (
2025-03-28 13:34:51 +01:00
<Poll pollId={status.get('poll')} status={status} lang={language} />
);
if (this.props.onClick) {
return (
<>
2025-09-23 10:53:14 +02:00
<div
className={classNames}
ref={this.setRef}
onMouseDown={this.handleMouseDown}
onMouseUp={this.handleMouseUp}
key='status-content'
>
2025-07-22 16:43:15 +02:00
<EmojiHTML
className='status__content__text status__content__text--visible translate'
lang={language}
htmlString={content}
extraEmojis={status.get('emojis')}
onElement={this.handleElement}
2025-07-22 16:43:15 +02:00
/>
{poll}
{translateButton}
</div>
{readMoreButton}
</>
);
} else {
return (
2025-09-23 10:53:14 +02:00
<div className={classNames} ref={this.setRef}>
2025-07-22 16:43:15 +02:00
<EmojiHTML
className='status__content__text status__content__text--visible translate'
lang={language}
htmlString={content}
extraEmojis={status.get('emojis')}
onElement={this.handleElement}
2025-07-22 16:43:15 +02:00
/>
{poll}
{translateButton}
</div>
);
}
}
}
export default withRouter(withIdentity(connect(mapStateToProps)(injectIntl(StatusContent))));