Merge branch 'next-status-loading' into 'next'

Next: Improve status loading, refactor Status components to TSX

See merge request soapbox-pub/soapbox-fe!1179
This commit is contained in:
Alex Gleason 2022-04-04 21:36:47 +00:00
commit 20aa17ce64
18 changed files with 678 additions and 627 deletions

View File

@ -83,7 +83,7 @@ export default (getState: () => RootState, authType: string = 'user'): AxiosInst
const state = getState(); const state = getState();
const accessToken = getToken(state, authType); const accessToken = getToken(state, authType);
const me = state.me; const me = state.me;
const baseURL = getAuthBaseURL(state, me); const baseURL = me ? getAuthBaseURL(state, me) : '';
return baseClient(accessToken, baseURL); return baseClient(accessToken, baseURL);
}; };

View File

@ -16,7 +16,7 @@ const listenerOptions = supportsPassiveEvents ? { passive: true } : false;
let id = 0; let id = 0;
export interface MenuItem { export interface MenuItem {
action: React.EventHandler<React.KeyboardEvent | React.MouseEvent>, action?: React.EventHandler<React.KeyboardEvent | React.MouseEvent>,
middleClick?: React.EventHandler<React.MouseEvent>, middleClick?: React.EventHandler<React.MouseEvent>,
text: string, text: string,
href?: string, href?: string,

View File

@ -4,7 +4,6 @@ import PTRComponent from 'react-simple-pull-to-refresh';
import { Spinner } from 'soapbox/components/ui'; import { Spinner } from 'soapbox/components/ui';
interface IPullToRefresh { interface IPullToRefresh {
children: JSX.Element & React.ReactNode,
onRefresh?: () => Promise<any> onRefresh?: () => Promise<any>
} }
@ -12,7 +11,7 @@ interface IPullToRefresh {
* PullToRefresh: * PullToRefresh:
* Wrapper around a third-party PTR component with Soapbox defaults. * Wrapper around a third-party PTR component with Soapbox defaults.
*/ */
const PullToRefresh = ({ children, onRefresh, ...rest }: IPullToRefresh) => { const PullToRefresh: React.FC<IPullToRefresh> = ({ children, onRefresh, ...rest }): JSX.Element => {
const handleRefresh = () => { const handleRefresh = () => {
if (onRefresh) { if (onRefresh) {
return onRefresh(); return onRefresh();
@ -33,7 +32,8 @@ const PullToRefresh = ({ children, onRefresh, ...rest }: IPullToRefresh) => {
resistance={2} resistance={2}
{...rest} {...rest}
> >
{children} {/* This thing really wants a single JSX element as its child (TypeScript), so wrap it in one */}
<>{children}</>
</PTRComponent> </PTRComponent>
); );
}; };

View File

@ -87,8 +87,8 @@ interface IStatus extends RouteComponentProps {
muted: boolean, muted: boolean,
hidden: boolean, hidden: boolean,
unread: boolean, unread: boolean,
onMoveUp: (statusId: string, featured: string) => void, onMoveUp: (statusId: string, featured?: string) => void,
onMoveDown: (statusId: string, featured: string) => void, onMoveDown: (statusId: string, featured?: string) => void,
getScrollPosition?: () => ScrollPosition | undefined, getScrollPosition?: () => ScrollPosition | undefined,
updateScrollBottom?: (bottom: number) => void, updateScrollBottom?: (bottom: number) => void,
cacheMediaWidth: () => void, cacheMediaWidth: () => void,
@ -658,8 +658,8 @@ class Status extends ImmutablePureComponent<IStatus, IStatusState> {
{quote} {quote}
<StatusActionBar <StatusActionBar
// @ts-ignore what?
status={status} status={status}
// @ts-ignore what?
account={account} account={account}
emojiSelectorFocused={this.state.emojiSelectorFocused} emojiSelectorFocused={this.state.emojiSelectorFocused}
handleEmojiSelectorUnfocus={this.handleEmojiSelectorUnfocus} handleEmojiSelectorUnfocus={this.handleEmojiSelectorUnfocus}

View File

@ -3,7 +3,7 @@ import React from 'react';
import ImmutablePureComponent from 'react-immutable-pure-component'; import ImmutablePureComponent from 'react-immutable-pure-component';
import { defineMessages, injectIntl, IntlShape } from 'react-intl'; import { defineMessages, injectIntl, IntlShape } from 'react-intl';
import { connect } from 'react-redux'; import { connect } from 'react-redux';
import { withRouter } from 'react-router-dom'; import { withRouter, RouteComponentProps } from 'react-router-dom';
import { simpleEmojiReact } from 'soapbox/actions/emoji_reacts'; import { simpleEmojiReact } from 'soapbox/actions/emoji_reacts';
import EmojiSelector from 'soapbox/components/emoji_selector'; import EmojiSelector from 'soapbox/components/emoji_selector';
@ -68,7 +68,7 @@ const messages = defineMessages({
quotePost: { id: 'status.quote', defaultMessage: 'Quote post' }, quotePost: { id: 'status.quote', defaultMessage: 'Quote post' },
}); });
interface IStatusActionBar { interface IStatusActionBar extends RouteComponentProps {
status: Status, status: Status,
onOpenUnauthorizedModal: (modalType?: string) => void, onOpenUnauthorizedModal: (modalType?: string) => void,
onOpenReblogsModal: (acct: string, statusId: string) => void, onOpenReblogsModal: (acct: string, statusId: string) => void,
@ -718,9 +718,6 @@ const mapDispatchToProps = (dispatch: Dispatch, { status }: { status: Status}) =
}, },
}); });
const WrappedComponent = withRouter(injectIntl(StatusActionBar));
// @ts-ignore // @ts-ignore
export default withRouter(injectIntl( export default connect(mapStateToProps, mapDispatchToProps, null, { forwardRef: true })(WrappedComponent);
// @ts-ignore
connect(mapStateToProps, mapDispatchToProps, null, { forwardRef: true },
// @ts-ignore
)(StatusActionBar)));

View File

@ -1,20 +1,27 @@
import classNames from 'classnames'; import classNames from 'classnames';
import PropTypes from 'prop-types';
import React from 'react'; import React from 'react';
import ImmutablePropTypes from 'react-immutable-proptypes'; import { defineMessages, injectIntl, WrappedComponentProps as IntlComponentProps } from 'react-intl';
import { defineMessages, injectIntl } from 'react-intl';
import { connect } from 'react-redux'; import { connect } from 'react-redux';
import { withRouter } from 'react-router-dom'; import { withRouter, RouteComponentProps } from 'react-router-dom';
import { isUserTouching } from 'soapbox/is_mobile'; import { isUserTouching } from 'soapbox/is_mobile';
import { getReactForStatus } from 'soapbox/utils/emoji_reacts'; import { getReactForStatus } from 'soapbox/utils/emoji_reacts';
import { getFeatures } from 'soapbox/utils/features'; import { getFeatures } from 'soapbox/utils/features';
import SoapboxPropTypes from 'soapbox/utils/soapbox_prop_types';
import { openModal } from '../../../actions/modals'; import { openModal } from '../../../actions/modals';
import { HStack, IconButton } from '../../../components/ui'; import { HStack, IconButton } from '../../../components/ui';
import DropdownMenuContainer from '../../../containers/dropdown_menu_container'; import DropdownMenuContainer from '../../../containers/dropdown_menu_container';
import type { History } from 'history';
import type { List as ImmutableList } from 'immutable';
import type { AnyAction } from 'redux';
import type { ThunkDispatch } from 'redux-thunk';
import type { Menu } from 'soapbox/components/dropdown_menu';
import type { RootState } from 'soapbox/store';
import type { Account as AccountEntity, Status as StatusEntity } from 'soapbox/types/entities';
type Dispatch = ThunkDispatch<RootState, void, AnyAction>;
const messages = defineMessages({ const messages = defineMessages({
delete: { id: 'status.delete', defaultMessage: 'Delete' }, delete: { id: 'status.delete', defaultMessage: 'Delete' },
redraft: { id: 'status.redraft', defaultMessage: 'Delete & re-draft' }, redraft: { id: 'status.redraft', defaultMessage: 'Delete & re-draft' },
@ -57,10 +64,10 @@ const messages = defineMessages({
quotePost: { id: 'status.quote', defaultMessage: 'Quote post' }, quotePost: { id: 'status.quote', defaultMessage: 'Quote post' },
}); });
const mapStateToProps = state => { const mapStateToProps = (state: RootState) => {
const me = state.get('me'); const me = state.me;
const account = state.getIn(['accounts', me]); const account = state.accounts.get(me);
const instance = state.get('instance'); const instance = state.instance;
return { return {
me, me,
@ -70,54 +77,56 @@ const mapStateToProps = state => {
}; };
}; };
const mapDispatchToProps = (dispatch, { status }) => ({ const mapDispatchToProps = (dispatch: Dispatch, { status }: OwnProps) => ({
onOpenUnauthorizedModal(action) { onOpenUnauthorizedModal(action: string) {
dispatch(openModal('UNAUTHORIZED', { dispatch(openModal('UNAUTHORIZED', {
action, action,
ap_id: status.get('url'), ap_id: status.url,
})); }));
}, },
}); });
@withRouter interface OwnProps {
class ActionBar extends React.PureComponent { status: StatusEntity,
onReply: (status: StatusEntity) => void,
onReblog: (status: StatusEntity, e: React.MouseEvent) => void,
onQuote: (status: StatusEntity, history: History) => void,
onFavourite: (status: StatusEntity) => void,
onEmojiReact: (status: StatusEntity, emoji: string) => void,
onDelete: (status: StatusEntity, history: History, redraft?: boolean) => void,
onBookmark: (status: StatusEntity) => void,
onDirect: (account: AccountEntity, history: History) => void,
onChat: (account: AccountEntity, history: History) => void,
onMention: (account: AccountEntity, history: History) => void,
onMute: (account: AccountEntity) => void,
onMuteConversation: (status: StatusEntity) => void,
onBlock: (status: StatusEntity) => void,
onReport: (status: StatusEntity) => void,
onPin: (status: StatusEntity) => void,
onEmbed: (status: StatusEntity) => void,
onDeactivateUser: (status: StatusEntity) => void,
onDeleteUser: (status: StatusEntity) => void,
onDeleteStatus: (status: StatusEntity) => void,
onToggleStatusSensitivity: (status: StatusEntity) => void,
allowedEmoji: ImmutableList<string>,
emojiSelectorFocused: boolean,
handleEmojiSelectorExpand: React.EventHandler<React.KeyboardEvent>,
handleEmojiSelectorUnfocus: React.EventHandler<React.KeyboardEvent>,
}
static propTypes = { type StateProps = ReturnType<typeof mapStateToProps>;
status: ImmutablePropTypes.record.isRequired, type DispatchProps = ReturnType<typeof mapDispatchToProps>;
onReply: PropTypes.func.isRequired,
onReblog: PropTypes.func.isRequired,
onQuote: PropTypes.func.isRequired,
onFavourite: PropTypes.func.isRequired,
onEmojiReact: PropTypes.func.isRequired,
onDelete: PropTypes.func.isRequired,
onBookmark: PropTypes.func,
onDirect: PropTypes.func.isRequired,
onChat: PropTypes.func,
onMention: PropTypes.func.isRequired,
onMute: PropTypes.func,
onMuteConversation: PropTypes.func,
onBlock: PropTypes.func,
onReport: PropTypes.func,
onPin: PropTypes.func,
onEmbed: PropTypes.func,
onDeactivateUser: PropTypes.func,
onDeleteUser: PropTypes.func,
onDeleteStatus: PropTypes.func,
onToggleStatusSensitivity: PropTypes.func,
intl: PropTypes.object.isRequired,
onOpenUnauthorizedModal: PropTypes.func.isRequired,
me: SoapboxPropTypes.me,
isStaff: PropTypes.bool.isRequired,
isAdmin: PropTypes.bool.isRequired,
allowedEmoji: ImmutablePropTypes.list,
emojiSelectorFocused: PropTypes.bool,
handleEmojiSelectorExpand: PropTypes.func.isRequired,
handleEmojiSelectorUnfocus: PropTypes.func.isRequired,
features: PropTypes.object.isRequired,
history: PropTypes.object,
};
static defaultProps = { type IActionBar = OwnProps & StateProps & DispatchProps & RouteComponentProps & IntlComponentProps;
interface IActionBarState {
emojiSelectorVisible: boolean,
emojiSelectorFocused: boolean,
}
class ActionBar extends React.PureComponent<IActionBar, IActionBarState> {
static defaultProps: Partial<IActionBar> = {
isStaff: false, isStaff: false,
} }
@ -126,7 +135,9 @@ class ActionBar extends React.PureComponent {
emojiSelectorFocused: false, emojiSelectorFocused: false,
} }
handleReplyClick = (e) => { node: HTMLDivElement | null = null;
handleReplyClick: React.EventHandler<React.MouseEvent> = (e) => {
const { me, onReply, onOpenUnauthorizedModal } = this.props; const { me, onReply, onOpenUnauthorizedModal } = this.props;
e.preventDefault(); e.preventDefault();
@ -137,7 +148,7 @@ class ActionBar extends React.PureComponent {
} }
} }
handleReblogClick = (e) => { handleReblogClick: React.EventHandler<React.MouseEvent> = (e) => {
const { me, onReblog, onOpenUnauthorizedModal, status } = this.props; const { me, onReblog, onOpenUnauthorizedModal, status } = this.props;
e.preventDefault(); e.preventDefault();
@ -148,7 +159,7 @@ class ActionBar extends React.PureComponent {
} }
} }
handleQuoteClick = () => { handleQuoteClick: React.EventHandler<React.MouseEvent> = () => {
const { me, onQuote, onOpenUnauthorizedModal, status } = this.props; const { me, onQuote, onOpenUnauthorizedModal, status } = this.props;
if (me) { if (me) {
onQuote(status, this.props.history); onQuote(status, this.props.history);
@ -157,12 +168,12 @@ class ActionBar extends React.PureComponent {
} }
} }
handleBookmarkClick = () => { handleBookmarkClick: React.EventHandler<React.MouseEvent> = () => {
this.props.onBookmark(this.props.status); this.props.onBookmark(this.props.status);
} }
handleFavouriteClick = (e) => { handleFavouriteClick: React.EventHandler<React.MouseEvent> = (e) => {
const { me, onFavourite, onOpenUnauthorizedModal } = this.props; const { me, onFavourite, onOpenUnauthorizedModal, status } = this.props;
e.preventDefault(); e.preventDefault();
@ -173,7 +184,7 @@ class ActionBar extends React.PureComponent {
} }
} }
handleLikeButtonHover = e => { handleLikeButtonHover: React.EventHandler<React.MouseEvent> = () => {
const { features } = this.props; const { features } = this.props;
if (features.emojiReacts && !isUserTouching()) { if (features.emojiReacts && !isUserTouching()) {
@ -181,7 +192,7 @@ class ActionBar extends React.PureComponent {
} }
} }
handleLikeButtonLeave = e => { handleLikeButtonLeave: React.EventHandler<React.MouseEvent> = () => {
const { features } = this.props; const { features } = this.props;
if (features.emojiReacts && !isUserTouching()) { if (features.emojiReacts && !isUserTouching()) {
@ -189,23 +200,23 @@ class ActionBar extends React.PureComponent {
} }
} }
handleLikeButtonClick = e => { handleLikeButtonClick: React.EventHandler<React.MouseEvent> = e => {
const { features } = this.props; const { features } = this.props;
const meEmojiReact = getReactForStatus(this.props.status, this.props.allowedEmoji) || '👍'; const meEmojiReact = getReactForStatus(this.props.status, this.props.allowedEmoji) || '👍';
if (features.emojiReacts && isUserTouching()) { if (features.emojiReacts && isUserTouching()) {
if (this.state.emojiSelectorVisible) { if (this.state.emojiSelectorVisible) {
this.handleReactClick(meEmojiReact)(); this.handleReactClick(meEmojiReact)(e);
} else { } else {
this.setState({ emojiSelectorVisible: true }); this.setState({ emojiSelectorVisible: true });
} }
} else { } else {
this.handleReactClick(meEmojiReact)(); this.handleReactClick(meEmojiReact)(e);
} }
} }
handleReactClick = emoji => { handleReactClick = (emoji: string): React.EventHandler<React.MouseEvent> => {
return e => { return () => {
const { me, onEmojiReact, onOpenUnauthorizedModal, status } = this.props; const { me, onEmojiReact, onOpenUnauthorizedModal, status } = this.props;
if (me) { if (me) {
onEmojiReact(status, emoji); onEmojiReact(status, emoji);
@ -222,35 +233,43 @@ class ActionBar extends React.PureComponent {
this.setState({ emojiSelectorVisible: !emojiSelectorVisible }); this.setState({ emojiSelectorVisible: !emojiSelectorVisible });
} }
handleDeleteClick = () => { handleDeleteClick: React.EventHandler<React.MouseEvent> = () => {
this.props.onDelete(this.props.status, this.props.history); this.props.onDelete(this.props.status, this.props.history);
} }
handleRedraftClick = () => { handleRedraftClick: React.EventHandler<React.MouseEvent> = () => {
this.props.onDelete(this.props.status, this.props.history, true); this.props.onDelete(this.props.status, this.props.history, true);
} }
handleDirectClick = () => { handleDirectClick: React.EventHandler<React.MouseEvent> = () => {
this.props.onDirect(this.props.status.get('account'), this.props.history); const { account } = this.props.status;
if (!account || typeof account !== 'object') return;
this.props.onDirect(account, this.props.history);
} }
handleChatClick = () => { handleChatClick: React.EventHandler<React.MouseEvent> = () => {
this.props.onChat(this.props.status.get('account'), this.props.history); const { account } = this.props.status;
if (!account || typeof account !== 'object') return;
this.props.onChat(account, this.props.history);
} }
handleMentionClick = () => { handleMentionClick: React.EventHandler<React.MouseEvent> = () => {
this.props.onMention(this.props.status.get('account'), this.props.history); const { account } = this.props.status;
if (!account || typeof account !== 'object') return;
this.props.onMention(account, this.props.history);
} }
handleMuteClick = () => { handleMuteClick: React.EventHandler<React.MouseEvent> = () => {
this.props.onMute(this.props.status.get('account')); const { account } = this.props.status;
if (!account || typeof account !== 'object') return;
this.props.onMute(account);
} }
handleConversationMuteClick = () => { handleConversationMuteClick: React.EventHandler<React.MouseEvent> = () => {
this.props.onMuteConversation(this.props.status); this.props.onMuteConversation(this.props.status);
} }
handleBlockClick = () => { handleBlockClick: React.EventHandler<React.MouseEvent> = () => {
this.props.onBlock(this.props.status); this.props.onBlock(this.props.status);
} }
@ -258,14 +277,14 @@ class ActionBar extends React.PureComponent {
this.props.onReport(this.props.status); this.props.onReport(this.props.status);
} }
handlePinClick = () => { handlePinClick: React.EventHandler<React.MouseEvent> = () => {
this.props.onPin(this.props.status); this.props.onPin(this.props.status);
} }
handleShare = () => { handleShare = () => {
navigator.share({ navigator.share({
text: this.props.status.get('search_index'), text: this.props.status.search_index,
url: this.props.status.get('url'), url: this.props.status.url,
}); });
} }
@ -274,7 +293,7 @@ class ActionBar extends React.PureComponent {
} }
handleCopy = () => { handleCopy = () => {
const url = this.props.status.get('url'); const url = this.props.status.url;
const textarea = document.createElement('textarea'); const textarea = document.createElement('textarea');
textarea.textContent = url; textarea.textContent = url;
@ -308,13 +327,13 @@ class ActionBar extends React.PureComponent {
this.props.onDeleteStatus(this.props.status); this.props.onDeleteStatus(this.props.status);
} }
setRef = c => { setRef: React.RefCallback<HTMLDivElement> = c => {
this.node = c; this.node = c;
} }
componentDidMount() { componentDidMount() {
document.addEventListener('click', e => { document.addEventListener('click', e => {
if (this.node && !this.node.contains(e.target)) if (this.node && !this.node.contains(e.target as Element))
this.setState({ emojiSelectorVisible: false, emojiSelectorFocused: false }); this.setState({ emojiSelectorVisible: false, emojiSelectorFocused: false });
}); });
} }
@ -322,20 +341,25 @@ class ActionBar extends React.PureComponent {
render() { render() {
const { status, intl, me, isStaff, isAdmin, allowedEmoji, features } = this.props; const { status, intl, me, isStaff, isAdmin, allowedEmoji, features } = this.props;
const ownAccount = status.getIn(['account', 'id']) === me; const ownAccount = status.getIn(['account', 'id']) === me;
const username = String(status.getIn(['account', 'acct']));
const publicStatus = ['public', 'unlisted'].includes(status.get('visibility')); const publicStatus = ['public', 'unlisted'].includes(status.visibility);
const mutingConversation = status.get('muted'); const mutingConversation = status.muted;
const meEmojiReact = getReactForStatus(status, allowedEmoji);
const meEmojiTitle = intl.formatMessage({ const meEmojiReact = getReactForStatus(status, allowedEmoji) as keyof typeof reactMessages | undefined;
const reactMessages = {
'👍': messages.reactionLike, '👍': messages.reactionLike,
'❤️': messages.reactionHeart, '❤️': messages.reactionHeart,
'😆': messages.reactionLaughing, '😆': messages.reactionLaughing,
'😮': messages.reactionOpenMouth, '😮': messages.reactionOpenMouth,
'😢': messages.reactionCry, '😢': messages.reactionCry,
'😩': messages.reactionWeary, '😩': messages.reactionWeary,
}[meEmojiReact] || messages.favourite); };
const menu = []; const meEmojiTitle = intl.formatMessage(meEmojiReact ? reactMessages[meEmojiReact] : messages.favourite);
const menu: Menu = [];
if (publicStatus) { if (publicStatus) {
menu.push({ menu.push({
@ -364,12 +388,12 @@ class ActionBar extends React.PureComponent {
if (ownAccount) { if (ownAccount) {
if (publicStatus) { if (publicStatus) {
menu.push({ menu.push({
text: intl.formatMessage(status.get('pinned') ? messages.unpin : messages.pin), text: intl.formatMessage(status.pinned ? messages.unpin : messages.pin),
action: this.handlePinClick, action: this.handlePinClick,
icon: require(mutingConversation ? '@tabler/icons/icons/pinned-off.svg' : '@tabler/icons/icons/pin.svg'), icon: require(mutingConversation ? '@tabler/icons/icons/pinned-off.svg' : '@tabler/icons/icons/pin.svg'),
}); });
} else { } else {
if (status.get('visibility') === 'private') { if (status.visibility === 'private') {
menu.push({ menu.push({
text: intl.formatMessage(status.get('reblogged') ? messages.cancel_reblog_private : messages.reblog_private), text: intl.formatMessage(status.get('reblogged') ? messages.cancel_reblog_private : messages.reblog_private),
action: this.handleReblogClick, action: this.handleReblogClick,
@ -399,20 +423,20 @@ class ActionBar extends React.PureComponent {
}); });
} else { } else {
menu.push({ menu.push({
text: intl.formatMessage(messages.mention, { name: status.getIn(['account', 'username']) }), text: intl.formatMessage(messages.mention, { name: username }),
action: this.handleMentionClick, action: this.handleMentionClick,
icon: require('@tabler/icons/icons/at.svg'), icon: require('@tabler/icons/icons/at.svg'),
}); });
// if (status.getIn(['account', 'pleroma', 'accepts_chat_messages'], false) === true) { // if (status.getIn(['account', 'pleroma', 'accepts_chat_messages'], false) === true) {
// menu.push({ // menu.push({
// text: intl.formatMessage(messages.chat, { name: status.getIn(['account', 'username']) }), // text: intl.formatMessage(messages.chat, { name: username }),
// action: this.handleChatClick, // action: this.handleChatClick,
// icon: require('@tabler/icons/icons/messages.svg'), // icon: require('@tabler/icons/icons/messages.svg'),
// }); // });
// } else { // } else {
// menu.push({ // menu.push({
// text: intl.formatMessage(messages.direct, { name: status.getIn(['account', 'username']) }), // text: intl.formatMessage(messages.direct, { name: username }),
// action: this.handleDirectClick, // action: this.handleDirectClick,
// icon: require('@tabler/icons/icons/mail.svg'), // icon: require('@tabler/icons/icons/mail.svg'),
// }); // });
@ -420,17 +444,17 @@ class ActionBar extends React.PureComponent {
menu.push(null); menu.push(null);
menu.push({ menu.push({
text: intl.formatMessage(messages.mute, { name: status.getIn(['account', 'username']) }), text: intl.formatMessage(messages.mute, { name: username }),
action: this.handleMuteClick, action: this.handleMuteClick,
icon: require('@tabler/icons/icons/circle-x.svg'), icon: require('@tabler/icons/icons/circle-x.svg'),
}); });
menu.push({ menu.push({
text: intl.formatMessage(messages.block, { name: status.getIn(['account', 'username']) }), text: intl.formatMessage(messages.block, { name: username }),
action: this.handleBlockClick, action: this.handleBlockClick,
icon: require('@tabler/icons/icons/ban.svg'), icon: require('@tabler/icons/icons/ban.svg'),
}); });
menu.push({ menu.push({
text: intl.formatMessage(messages.report, { name: status.getIn(['account', 'username']) }), text: intl.formatMessage(messages.report, { name: username }),
action: this.handleReport, action: this.handleReport,
icon: require('@tabler/icons/icons/flag.svg'), icon: require('@tabler/icons/icons/flag.svg'),
}); });
@ -441,13 +465,13 @@ class ActionBar extends React.PureComponent {
if (isAdmin) { if (isAdmin) {
menu.push({ menu.push({
text: intl.formatMessage(messages.admin_account, { name: status.getIn(['account', 'username']) }), text: intl.formatMessage(messages.admin_account, { name: username }),
href: `/pleroma/admin/#/users/${status.getIn(['account', 'id'])}/`, href: `/pleroma/admin/#/users/${status.getIn(['account', 'id'])}/`,
icon: require('@tabler/icons/icons/gavel.svg'), icon: require('@tabler/icons/icons/gavel.svg'),
}); });
menu.push({ menu.push({
text: intl.formatMessage(messages.admin_status), text: intl.formatMessage(messages.admin_status),
href: `/pleroma/admin/#/statuses/${status.get('id')}/`, href: `/pleroma/admin/#/statuses/${status.id}/`,
icon: require('@tabler/icons/icons/pencil.svg'), icon: require('@tabler/icons/icons/pencil.svg'),
}); });
} }
@ -460,12 +484,12 @@ class ActionBar extends React.PureComponent {
if (!ownAccount) { if (!ownAccount) {
menu.push({ menu.push({
text: intl.formatMessage(messages.deactivateUser, { name: status.getIn(['account', 'username']) }), text: intl.formatMessage(messages.deactivateUser, { name: username }),
action: this.handleDeactivateUser, action: this.handleDeactivateUser,
icon: require('@tabler/icons/icons/user-off.svg'), icon: require('@tabler/icons/icons/user-off.svg'),
}); });
menu.push({ menu.push({
text: intl.formatMessage(messages.deleteUser, { name: status.getIn(['account', 'username']) }), text: intl.formatMessage(messages.deleteUser, { name: username }),
action: this.handleDeleteUser, action: this.handleDeleteUser,
icon: require('@tabler/icons/icons/user-minus.svg'), icon: require('@tabler/icons/icons/user-minus.svg'),
destructive: true, destructive: true,
@ -496,7 +520,7 @@ class ActionBar extends React.PureComponent {
let reblogButton; let reblogButton;
if (me && features.quotePosts) { if (me && features.quotePosts) {
const reblogMenu = [ const reblogMenu: Menu = [
{ {
text: intl.formatMessage(status.get('reblogged') ? messages.cancel_reblog_private : messages.reblog), text: intl.formatMessage(status.get('reblogged') ? messages.cancel_reblog_private : messages.reblog),
action: this.handleReblogClick, action: this.handleReblogClick,
@ -517,7 +541,6 @@ class ActionBar extends React.PureComponent {
pressed={status.get('reblogged')} pressed={status.get('reblogged')}
title={!publicStatus ? intl.formatMessage(messages.cannot_reblog) : intl.formatMessage(messages.reblog)} title={!publicStatus ? intl.formatMessage(messages.cannot_reblog) : intl.formatMessage(messages.reblog)}
src={reblogIcon} src={reblogIcon}
direction='right'
text={intl.formatMessage(messages.reblog)} text={intl.formatMessage(messages.reblog)}
onShiftClick={this.handleReblogClick} onShiftClick={this.handleReblogClick}
/> />
@ -577,7 +600,6 @@ class ActionBar extends React.PureComponent {
<DropdownMenuContainer <DropdownMenuContainer
src={require('@tabler/icons/icons/dots.svg')} src={require('@tabler/icons/icons/dots.svg')}
items={menu} items={menu}
direction='left'
title='More' title='More'
/> />
</HStack> </HStack>
@ -586,5 +608,5 @@ class ActionBar extends React.PureComponent {
} }
export default injectIntl( const WrappedComponent = withRouter(injectIntl(ActionBar));
connect(mapStateToProps, mapDispatchToProps)(ActionBar)); export default connect(mapStateToProps, mapDispatchToProps)(WrappedComponent);

View File

@ -1,11 +1,9 @@
import classNames from 'classnames'; import classNames from 'classnames';
import PropTypes from 'prop-types';
import React from 'react'; import React from 'react';
import ImmutablePropTypes from 'react-immutable-proptypes';
import ImmutablePureComponent from 'react-immutable-pure-component'; import ImmutablePureComponent from 'react-immutable-pure-component';
import { FormattedMessage, injectIntl } from 'react-intl'; import { FormattedMessage, injectIntl, WrappedComponentProps as IntlProps } from 'react-intl';
import { FormattedDate } from 'react-intl'; import { FormattedDate } from 'react-intl';
import { Link, NavLink } from 'react-router-dom'; import { Link } from 'react-router-dom';
import Icon from 'soapbox/components/icon'; import Icon from 'soapbox/components/icon';
import QuotedStatus from 'soapbox/features/status/containers/quoted_status_container'; import QuotedStatus from 'soapbox/features/status/containers/quoted_status_container';
@ -21,29 +19,39 @@ import scheduleIdleTask from '../../ui/util/schedule_idle_task';
import Video from '../../video'; import Video from '../../video';
import Card from './card'; import Card from './card';
import StatusInteractionBar from './status_interaction_bar'; import StatusInteractionBar from './status-interaction-bar';
export default @injectIntl import type { List as ImmutableList } from 'immutable';
class DetailedStatus extends ImmutablePureComponent { import type { Attachment as AttachmentEntity, Status as StatusEntity } from 'soapbox/types/entities';
static propTypes = { interface IDetailedStatus extends IntlProps {
status: ImmutablePropTypes.record, status: StatusEntity,
onOpenMedia: PropTypes.func.isRequired, onOpenMedia: (media: ImmutableList<AttachmentEntity>, index: number) => void,
onOpenVideo: PropTypes.func.isRequired, onOpenVideo: (media: ImmutableList<AttachmentEntity>, start: number) => void,
onToggleHidden: PropTypes.func.isRequired, onToggleHidden: (status: StatusEntity) => void,
measureHeight: PropTypes.bool, measureHeight: boolean,
onHeightChange: PropTypes.func, onHeightChange: () => void,
domain: PropTypes.string, domain: string,
compact: PropTypes.bool, compact: boolean,
showMedia: PropTypes.bool, showMedia: boolean,
onToggleMediaVisibility: PropTypes.func, onToggleMediaVisibility: () => void,
}; }
interface IDetailedStatusState {
height: number | null,
mediaWrapperWidth: number,
}
class DetailedStatus extends ImmutablePureComponent<IDetailedStatus, IDetailedStatusState> {
state = { state = {
height: null, height: null,
mediaWrapperWidth: NaN,
}; };
handleOpenVideo = (media, startTime) => { node: HTMLDivElement | null = null;
handleOpenVideo = (media: ImmutableList<AttachmentEntity>, startTime: number) => {
this.props.onOpenVideo(media, startTime); this.props.onOpenVideo(media, startTime);
} }
@ -51,7 +59,7 @@ class DetailedStatus extends ImmutablePureComponent {
this.props.onToggleHidden(this.props.status); this.props.onToggleHidden(this.props.status);
} }
_measureHeight(heightJustChanged) { _measureHeight(heightJustChanged = false) {
if (this.props.measureHeight && this.node) { if (this.props.measureHeight && this.node) {
scheduleIdleTask(() => this.node && this.setState({ height: Math.ceil(this.node.scrollHeight) + 1 })); scheduleIdleTask(() => this.node && this.setState({ height: Math.ceil(this.node.scrollHeight) + 1 }));
@ -61,7 +69,7 @@ class DetailedStatus extends ImmutablePureComponent {
} }
} }
setRef = c => { setRef: React.RefCallback<HTMLDivElement> = c => {
this.node = c; this.node = c;
this._measureHeight(); this._measureHeight();
@ -70,35 +78,41 @@ class DetailedStatus extends ImmutablePureComponent {
} }
} }
componentDidUpdate(prevProps, prevState) { componentDidUpdate(prevProps: IDetailedStatus, prevState: IDetailedStatusState) {
this._measureHeight(prevState.height !== this.state.height); this._measureHeight(prevState.height !== this.state.height);
} }
handleModalLink = e => { // handleModalLink = e => {
e.preventDefault(); // e.preventDefault();
//
// let href;
//
// if (e.target.nodeName !== 'A') {
// href = e.target.parentNode.href;
// } else {
// href = e.target.href;
// }
//
// window.open(href, 'soapbox-intent', 'width=445,height=600,resizable=no,menubar=no,status=no,scrollbars=yes');
// }
let href; getActualStatus = () => {
const { status } = this.props;
if (e.target.nodeName !== 'A') { if (!status) return undefined;
href = e.target.parentNode.href; return status.reblog && typeof status.reblog === 'object' ? status.reblog : status;
} else {
href = e.target.href;
}
window.open(href, 'soapbox-intent', 'width=445,height=600,resizable=no,menubar=no,status=no,scrollbars=yes');
} }
render() { render() {
const status = (this.props.status && this.props.status.get('reblog')) ? this.props.status.get('reblog') : this.props.status; const status = this.getActualStatus();
const outerStyle = { boxSizing: 'border-box' }; if (!status) return null;
const { compact } = this.props; const { account } = status;
const favicon = status.getIn(['account', 'pleroma', 'favicon']); if (!account || typeof account !== 'object') return null;
const domain = getDomain(status.get('account'));
const size = status.get('media_attachments').size; const outerStyle: React.CSSProperties = { boxSizing: 'border-box' };
const { compact } = this.props;
const favicon = account.getIn(['pleroma', 'favicon']);
const domain = getDomain(account);
if (!status) {
return null;
}
let media = null; let media = null;
let statusTypeIcon = null; let statusTypeIcon = null;
@ -107,12 +121,15 @@ class DetailedStatus extends ImmutablePureComponent {
outerStyle.height = `${this.state.height}px`; outerStyle.height = `${this.state.height}px`;
} }
if (size > 0) { const size = status.media_attachments.size;
if (size === 1 && status.getIn(['media_attachments', 0, 'type']) === 'video') { const firstAttachment = status.media_attachments.get(0);
const video = status.getIn(['media_attachments', 0]);
if (size > 0 && firstAttachment) {
if (size === 1 && firstAttachment.type === 'video') {
const video = firstAttachment;
if (video.external_video_id && status.card?.html) { if (video.external_video_id && status.card?.html) {
const { mediaWrapperWidth } = this.state; const { mediaWrapperWidth } = this.state;
const height = mediaWrapperWidth / (video.getIn(['meta', 'original', 'width']) / video.getIn(['meta', 'original', 'height'])); const height = mediaWrapperWidth / Number(video.meta.getIn(['original', 'width'])) / Number(video.meta.getIn(['original', 'height']));
media = ( media = (
<div className='status-card horizontal interactive status-card--video'> <div className='status-card horizontal interactive status-card--video'>
<div <div
@ -126,33 +143,33 @@ class DetailedStatus extends ImmutablePureComponent {
} else { } else {
media = ( media = (
<Video <Video
preview={video.get('preview_url')} preview={video.preview_url}
blurhash={video.get('blurhash')} blurhash={video.blurhash}
src={video.get('url')} src={video.url}
alt={video.get('description')} alt={video.description}
aspectRatio={video.getIn(['meta', 'original', 'aspect'])} aspectRatio={video.meta.getIn(['original', 'aspect'])}
width={300} width={300}
height={150} height={150}
inline inline
onOpenVideo={this.handleOpenVideo} onOpenVideo={this.handleOpenVideo}
sensitive={status.get('sensitive')} sensitive={status.sensitive}
visible={this.props.showMedia} visible={this.props.showMedia}
onToggleVisibility={this.props.onToggleMediaVisibility} onToggleVisibility={this.props.onToggleMediaVisibility}
/> />
); );
} }
} else if (size === 1 && status.getIn(['media_attachments', 0, 'type']) === 'audio' && status.get('media_attachments').size === 1) { } else if (size === 1 && firstAttachment.type === 'audio') {
const attachment = status.getIn(['media_attachments', 0]); const attachment = firstAttachment;
media = ( media = (
<Audio <Audio
src={attachment.get('url')} src={attachment.url}
alt={attachment.get('description')} alt={attachment.description}
duration={attachment.getIn(['meta', 'original', 'duration'], 0)} duration={attachment.meta.getIn(['original', 'duration', 0])}
poster={attachment.get('preview_url') !== attachment.get('url') ? attachment.get('preview_url') : status.getIn(['account', 'avatar_static'])} poster={attachment.preview_url !== attachment.url ? attachment.preview_url : account.avatar_static}
backgroundColor={attachment.getIn(['meta', 'colors', 'background'])} backgroundColor={attachment.meta.getIn(['colors', 'background'])}
foregroundColor={attachment.getIn(['meta', 'colors', 'foreground'])} foregroundColor={attachment.meta.getIn(['colors', 'foreground'])}
accentColor={attachment.getIn(['meta', 'colors', 'accent'])} accentColor={attachment.meta.getIn(['colors', 'accent'])}
height={150} height={150}
/> />
); );
@ -160,8 +177,8 @@ class DetailedStatus extends ImmutablePureComponent {
media = ( media = (
<MediaGallery <MediaGallery
standalone standalone
sensitive={status.get('sensitive')} sensitive={status.sensitive}
media={status.get('media_attachments')} media={status.media_attachments}
height={300} height={300}
onOpenMedia={this.props.onOpenMedia} onOpenMedia={this.props.onOpenMedia}
visible={this.props.showMedia} visible={this.props.showMedia}
@ -169,27 +186,27 @@ class DetailedStatus extends ImmutablePureComponent {
/> />
); );
} }
} else if (status.get('spoiler_text').length === 0 && !status.get('quote')) { } else if (status.spoiler_text.length === 0 && !status.quote) {
media = <Card onOpenMedia={this.props.onOpenMedia} card={status.get('card', null)} />; media = <Card onOpenMedia={this.props.onOpenMedia} card={status.card} />;
} }
let quote; let quote;
if (status.get('quote')) { if (status.quote) {
if (status.getIn(['pleroma', 'quote_visible'], true) === false) { if (status.pleroma.get('quote_visible', true) === false) {
quote = ( quote = (
<div className='quoted-status-tombstone'> <div className='quoted-status-tombstone'>
<p><FormattedMessage id='statuses.quote_tombstone' defaultMessage='Post is unavailable.' /></p> <p><FormattedMessage id='statuses.quote_tombstone' defaultMessage='Post is unavailable.' /></p>
</div> </div>
); );
} else { } else {
quote = <QuotedStatus statusId={status.get('quote')} />; quote = <QuotedStatus statusId={status.quote} />;
} }
} }
if (status.get('visibility') === 'direct') { if (status.visibility === 'direct') {
statusTypeIcon = <Icon src={require('@tabler/icons/icons/mail.svg')} />; statusTypeIcon = <Icon src={require('@tabler/icons/icons/mail.svg')} />;
} else if (status.get('visibility') === 'private') { } else if (status.visibility === 'private') {
statusTypeIcon = <Icon src={require('@tabler/icons/icons/lock.svg')} />; statusTypeIcon = <Icon src={require('@tabler/icons/icons/lock.svg')} />;
} }
@ -198,25 +215,25 @@ class DetailedStatus extends ImmutablePureComponent {
<div ref={this.setRef} className={classNames('detailed-status', { compact })}> <div ref={this.setRef} className={classNames('detailed-status', { compact })}>
<div className='mb-4'> <div className='mb-4'>
<AccountContainer <AccountContainer
key={status.getIn(['account', 'id'])} key={account.id}
id={status.getIn(['account', 'id'])} id={account.id}
timestamp={status.get('created_at')} timestamp={status.created_at}
avatarSize={42} avatarSize={42}
hideActions hideActions
/> />
</div> </div>
{status.get('group') && ( {/* status.group && (
<div className='status__meta'> <div className='status__meta'>
Posted in <NavLink to={`/groups/${status.getIn(['group', 'id'])}`}>{status.getIn(['group', 'title'])}</NavLink> Posted in <NavLink to={`/groups/${status.getIn(['group', 'id'])}`}>{status.getIn(['group', 'title'])}</NavLink>
</div> </div>
)} )*/}
<StatusReplyMentions status={status} /> <StatusReplyMentions status={status} />
<StatusContent <StatusContent
status={status} status={status}
expanded={!status.get('hidden')} expanded={!status.hidden}
onExpandedToggle={this.handleExpandedToggle} onExpandedToggle={this.handleExpandedToggle}
/> />
@ -227,18 +244,19 @@ class DetailedStatus extends ImmutablePureComponent {
<StatusInteractionBar status={status} /> <StatusInteractionBar status={status} />
<div className='detailed-status__timestamp'> <div className='detailed-status__timestamp'>
{favicon && {typeof favicon === 'string' && (
<div className='status__favicon'> <div className='status__favicon'>
<Link to={`/timeline/${domain}`}> <Link to={`/timeline/${domain}`}>
<img src={favicon} alt='' title={domain} /> <img src={favicon} alt='' title={domain} />
</Link> </Link>
</div>} </div>
)}
{statusTypeIcon} {statusTypeIcon}
<a href={status.get('url')} target='_blank' rel='noopener' className='hover:underline'> <a href={status.url} target='_blank' rel='noopener' className='hover:underline'>
<Text tag='span' theme='muted' size='sm'> <Text tag='span' theme='muted' size='sm'>
<FormattedDate value={new Date(status.get('created_at'))} hour12={false} year='numeric' month='short' day='2-digit' hour='2-digit' minute='2-digit' /> <FormattedDate value={new Date(status.created_at)} hour12={false} year='numeric' month='short' day='2-digit' hour='2-digit' minute='2-digit' />
</Text> </Text>
</a> </a>
</div> </div>
@ -249,3 +267,5 @@ class DetailedStatus extends ImmutablePureComponent {
} }
} }
export default injectIntl(DetailedStatus);

View File

@ -0,0 +1,186 @@
import classNames from 'classnames';
import { Map as ImmutableMap, List as ImmutableList } from 'immutable';
import React from 'react';
import { FormattedNumber } from 'react-intl';
import { useDispatch } from 'react-redux';
import { openModal } from 'soapbox/actions/modals';
import emojify from 'soapbox/features/emoji/emoji';
import { useAppSelector, useSoapboxConfig, useFeatures } from 'soapbox/hooks';
import { reduceEmoji } from 'soapbox/utils/emoji_reacts';
import { HStack, IconButton, Text } from '../../../components/ui';
import type { Status } from 'soapbox/types/entities';
interface IStatusInteractionBar {
status: Status,
}
const StatusInteractionBar: React.FC<IStatusInteractionBar> = ({ status }): JSX.Element | null => {
const me = useAppSelector(({ me }) => me);
const { allowedEmoji } = useSoapboxConfig();
const dispatch = useDispatch();
const features = useFeatures();
const { account } = status;
if (!account || typeof account !== 'object') return null;
const onOpenUnauthorizedModal = () => {
dispatch(openModal('UNAUTHORIZED'));
};
const onOpenReblogsModal = (username: string, statusId: string): void => {
dispatch(openModal('REBLOGS', {
username,
statusId,
}));
};
const onOpenFavouritesModal = (username: string, statusId: string): void => {
dispatch(openModal('FAVOURITES', {
username,
statusId,
}));
};
const onOpenReactionsModal = (username: string, statusId: string, reaction: string): void => {
dispatch(openModal('REACTIONS', {
username,
statusId,
reaction,
}));
};
const getNormalizedReacts = () => {
return reduceEmoji(
ImmutableList(status.getIn(['pleroma', 'emoji_reactions']) as any),
status.favourites_count,
status.favourited,
allowedEmoji,
).reverse();
};
const handleOpenReblogsModal: React.EventHandler<React.MouseEvent> = (e) => {
e.preventDefault();
if (!me) onOpenUnauthorizedModal();
else onOpenReblogsModal(account.acct, status.id);
};
const getReposts = () => {
if (status.reblogs_count) {
return (
<HStack space={0.5} alignItems='center'>
<IconButton
className='text-success-600 cursor-pointer'
src={require('@tabler/icons/icons/repeat.svg')}
role='presentation'
onClick={handleOpenReblogsModal}
/>
<Text theme='muted' size='sm'>
<FormattedNumber value={status.reblogs_count} />
</Text>
</HStack>
);
}
return '';
};
const handleOpenFavouritesModal: React.EventHandler<React.MouseEvent<HTMLButtonElement>> = (e) => {
e.preventDefault();
if (!me) onOpenUnauthorizedModal();
else onOpenFavouritesModal(account.acct, status.id);
};
const getFavourites = () => {
if (status.favourites_count) {
return (
<HStack space={0.5} alignItems='center'>
<IconButton
className={classNames({
'text-accent-300': true,
'cursor-default': !features.exposableReactions,
})}
src={require('@tabler/icons/icons/heart.svg')}
iconClassName='fill-accent-300'
role='presentation'
onClick={features.exposableReactions ? handleOpenFavouritesModal : undefined}
/>
<Text theme='muted' size='sm'>
<FormattedNumber value={status.favourites_count} />
</Text>
</HStack>
);
}
return '';
};
const handleOpenReactionsModal = (reaction: ImmutableMap<string, any>) => () => {
if (!me) onOpenUnauthorizedModal();
else onOpenReactionsModal(account.acct, status.id, String(reaction.get('name')));
};
const getEmojiReacts = () => {
const emojiReacts = getNormalizedReacts();
const count = emojiReacts.reduce((acc, cur) => (
acc + cur.get('count')
), 0);
if (count > 0) {
return (
<div className='emoji-reacts-container'>
<div className='emoji-reacts'>
{emojiReacts.map((e, i) => {
const emojiReact = (
<>
<span
className='emoji-react__emoji'
dangerouslySetInnerHTML={{ __html: emojify(e.get('name')) }}
/>
<span className='emoji-react__count'>{e.get('count')}</span>
</>
);
if (features.exposableReactions) {
return (
<span
className='emoji-react'
role='presentation'
key={i}
onClick={handleOpenReactionsModal(e)}
>
{emojiReact}
</span>
);
}
return <span className='emoji-react' key={i}>{emojiReact}</span>;
})}
</div>
<div className='emoji-reacts__count'>
{count}
</div>
</div>
);
}
return '';
};
return (
<HStack space={3}>
{features.emojiReacts ? getEmojiReacts() : getFavourites()}
{getReposts()}
</HStack>
);
};
export default StatusInteractionBar;

View File

@ -1,213 +0,0 @@
import classNames from 'classnames';
import PropTypes from 'prop-types';
import React from 'react';
import ImmutablePropTypes from 'react-immutable-proptypes';
import ImmutablePureComponent from 'react-immutable-pure-component';
import { FormattedNumber } from 'react-intl';
import { connect } from 'react-redux';
import { openModal } from 'soapbox/actions/modals';
import { getSoapboxConfig } from 'soapbox/actions/soapbox';
import emojify from 'soapbox/features/emoji/emoji';
import { reduceEmoji } from 'soapbox/utils/emoji_reacts';
import { getFeatures } from 'soapbox/utils/features';
import SoapboxPropTypes from 'soapbox/utils/soapbox_prop_types';
import { HStack, IconButton, Text } from '../../../components/ui';
const mapStateToProps = state => {
const me = state.get('me');
const instance = state.get('instance');
return {
me,
allowedEmoji: getSoapboxConfig(state).get('allowedEmoji'),
features: getFeatures(instance),
};
};
const mapDispatchToProps = (dispatch) => ({
onOpenUnauthorizedModal() {
dispatch(openModal('UNAUTHORIZED'));
},
onOpenReblogsModal(username, statusId) {
dispatch(openModal('REBLOGS', {
username,
statusId,
}));
},
onOpenFavouritesModal(username, statusId) {
dispatch(openModal('FAVOURITES', {
username,
statusId,
}));
},
onOpenReactionsModal(username, statusId, reaction) {
dispatch(openModal('REACTIONS', {
username,
statusId,
reaction,
}));
},
});
export default @connect(mapStateToProps, mapDispatchToProps)
class StatusInteractionBar extends ImmutablePureComponent {
static propTypes = {
status: ImmutablePropTypes.record,
me: SoapboxPropTypes.me,
allowedEmoji: ImmutablePropTypes.list,
features: PropTypes.object.isRequired,
onOpenReblogsModal: PropTypes.func,
onOpenReactionsModal: PropTypes.func,
}
getNormalizedReacts = () => {
const { status } = this.props;
return reduceEmoji(
status.getIn(['pleroma', 'emoji_reactions']),
status.get('favourites_count'),
status.get('favourited'),
this.props.allowedEmoji,
).reverse();
}
handleOpenReblogsModal = (event) => {
const { me, status, onOpenUnauthorizedModal, onOpenReblogsModal } = this.props;
event.preventDefault();
if (!me) onOpenUnauthorizedModal();
else onOpenReblogsModal(status.getIn(['account', 'acct']), status.get('id'));
}
getReposts = () => {
const { status } = this.props;
if (status.get('reblogs_count')) {
return (
<HStack space={0.5} alignItems='center'>
<IconButton
className='text-success-600 cursor-pointer'
src={require('@tabler/icons/icons/repeat.svg')}
role='presentation'
onClick={this.handleOpenReblogsModal}
/>
<Text theme='muted' size='sm'>
<FormattedNumber value={status.get('reblogs_count')} />
</Text>
</HStack>
);
}
return '';
}
handleOpenFavouritesModal = (event) => {
const { me, status, onOpenUnauthorizedModal, onOpenFavouritesModal } = this.props;
event.preventDefault();
if (!me) onOpenUnauthorizedModal();
else onOpenFavouritesModal(status.getIn(['account', 'acct']), status.get('id'));
}
getFavourites = () => {
const { features, status } = this.props;
if (status.get('favourites_count')) {
return (
<HStack space={0.5} alignItems='center'>
<IconButton
className={classNames({
'text-accent-300': true,
'cursor-default': !features.exposableReactions,
})}
src={require('@tabler/icons/icons/heart.svg')}
iconClassName='fill-accent-300'
role='presentation'
onClick={features.exposableReactions ? this.handleOpenFavouritesModal : null}
/>
<Text theme='muted' size='sm'>
<FormattedNumber value={status.get('favourites_count')} />
</Text>
</HStack>
);
}
return '';
}
handleOpenReactionsModal = (reaction) => () => {
const { me, status, onOpenUnauthorizedModal, onOpenReactionsModal } = this.props;
if (!me) onOpenUnauthorizedModal();
else onOpenReactionsModal(status.getIn(['account', 'acct']), status.get('id'), reaction.get('name'));
}
getEmojiReacts = () => {
const { features } = this.props;
const emojiReacts = this.getNormalizedReacts();
const count = emojiReacts.reduce((acc, cur) => (
acc + cur.get('count')
), 0);
if (count > 0) {
return (
<div className='emoji-reacts-container'>
<div className='emoji-reacts'>
{emojiReacts.map((e, i) => {
const emojiReact = (
<>
<span
className='emoji-react__emoji'
dangerouslySetInnerHTML={{ __html: emojify(e.get('name')) }}
/>
<span className='emoji-react__count'>{e.get('count')}</span>
</>
);
if (features.exposableReactions) {
return (
<span
className='emoji-react'
type='button'
role='presentation'
key={i}
onClick={this.handleOpenReactionsModal(e)}
>
{emojiReact}
</span>
);
}
return <span className='emoji-react' key={i}>{emojiReact}</span>;
})}
</div>
<div className='emoji-reacts__count'>
{count}
</div>
</div>
);
}
return '';
};
render() {
const { features } = this.props;
return (
<HStack space={3}>
{features.emojiReacts ? this.getEmojiReacts() : this.getFavourites()}
{this.getReposts()}
</HStack>
);
}
}

View File

@ -0,0 +1,51 @@
import classNames from 'classnames';
import { OrderedSet as ImmutableOrderedSet } from 'immutable';
import React from 'react';
import StatusContainer from 'soapbox/containers/status_container';
import PlaceholderStatus from 'soapbox/features/placeholder/components/placeholder_status';
import { useAppSelector } from 'soapbox/hooks';
interface IThreadStatus {
id: string,
focusedStatusId: string,
}
const ThreadStatus: React.FC<IThreadStatus> = (props): JSX.Element => {
const { id, focusedStatusId } = props;
const replyToId = useAppSelector(state => state.contexts.getIn(['inReplyTos', id]));
const replyCount = useAppSelector(state => state.contexts.getIn(['replies', id], ImmutableOrderedSet()).size);
const isLoaded = useAppSelector(state => Boolean(state.statuses.get(id)));
const renderConnector = (): JSX.Element | null => {
const isConnectedTop = replyToId && replyToId !== focusedStatusId;
const isConnectedBottom = replyCount > 0;
const isConnected = isConnectedTop || isConnectedBottom;
if (!isConnected) return null;
return (
<div
className={classNames('thread__connector', {
'thread__connector--top': isConnectedTop,
'thread__connector--bottom': isConnectedBottom,
})}
/>
);
};
return (
<div className='thread__status'>
{renderConnector()}
{isLoaded ? (
// @ts-ignore FIXME
<StatusContainer {...props} />
) : (
<PlaceholderStatus thread />
)}
</div>
);
};
export default ThreadStatus;

View File

@ -1,64 +0,0 @@
import classNames from 'classnames';
import { OrderedSet as ImmutableOrderedSet } from 'immutable';
import PropTypes from 'prop-types';
import React from 'react';
import { connect } from 'react-redux';
import StatusContainer from 'soapbox/containers/status_container';
import PlaceholderStatus from 'soapbox/features/placeholder/components/placeholder_status';
const mapStateToProps = (state, { id }) => {
return {
replyToId: state.getIn(['contexts', 'inReplyTos', id]),
replyCount: state.getIn(['contexts', 'replies', id], ImmutableOrderedSet()).size,
isLoaded: Boolean(state.getIn(['statuses', id])),
};
};
export default @connect(mapStateToProps)
class ThreadStatus extends React.Component {
static propTypes = {
focusedStatusId: PropTypes.string,
replyToId: PropTypes.string,
replyCount: PropTypes.number,
isLoaded: PropTypes.bool,
}
renderConnector() {
const { focusedStatusId, replyToId, replyCount } = this.props;
const isConnectedTop = replyToId && replyToId !== focusedStatusId;
const isConnectedBottom = replyCount > 0;
const isConnected = isConnectedTop || isConnectedBottom;
if (!isConnected) {
return null;
}
return (
<div
className={classNames('thread__connector', {
'thread__connector--top': isConnectedTop,
'thread__connector--bottom': isConnectedBottom,
})}
/>
);
}
render() {
const { isLoaded } = this.props;
return (
<div className='thread__status'>
{this.renderConnector()}
{isLoaded ? (
<StatusContainer {...this.props} />
) : (
<PlaceholderStatus thread />
)}
</div>
);
}
}

View File

@ -34,7 +34,7 @@ import {
revealStatus, revealStatus,
} from '../../../actions/statuses'; } from '../../../actions/statuses';
import { makeGetStatus } from '../../../selectors'; import { makeGetStatus } from '../../../selectors';
import DetailedStatus from '../components/detailed_status'; import DetailedStatus from '../components/detailed-status';
const messages = defineMessages({ const messages = defineMessages({
deleteConfirm: { id: 'confirmations.delete.confirm', defaultMessage: 'Delete' }, deleteConfirm: { id: 'confirmations.delete.confirm', defaultMessage: 'Delete' },

View File

@ -1,13 +1,11 @@
import classNames from 'classnames'; import classNames from 'classnames';
import { List as ImmutableList, OrderedSet as ImmutableOrderedSet } from 'immutable'; import { List as ImmutableList, OrderedSet as ImmutableOrderedSet } from 'immutable';
import PropTypes from 'prop-types';
import React from 'react'; import React from 'react';
import { HotKeys } from 'react-hotkeys'; import { HotKeys } from 'react-hotkeys';
import ImmutablePropTypes from 'react-immutable-proptypes';
import ImmutablePureComponent from 'react-immutable-pure-component'; import ImmutablePureComponent from 'react-immutable-pure-component';
import { defineMessages, injectIntl, FormattedMessage } from 'react-intl'; import { defineMessages, injectIntl, FormattedMessage, WrappedComponentProps as IntlComponentProps } from 'react-intl';
import { connect } from 'react-redux'; import { connect } from 'react-redux';
import { withRouter } from 'react-router-dom'; import { withRouter, RouteComponentProps } from 'react-router-dom';
import { createSelector } from 'reselect'; import { createSelector } from 'reselect';
import { launchChat } from 'soapbox/actions/chats'; import { launchChat } from 'soapbox/actions/chats';
@ -22,6 +20,7 @@ import { getSoapboxConfig } from 'soapbox/actions/soapbox';
import PullToRefresh from 'soapbox/components/pull-to-refresh'; import PullToRefresh from 'soapbox/components/pull-to-refresh';
import SubNavigation from 'soapbox/components/sub_navigation'; import SubNavigation from 'soapbox/components/sub_navigation';
import { Column } from 'soapbox/components/ui'; import { Column } from 'soapbox/components/ui';
import PlaceholderStatus from 'soapbox/features/placeholder/components/placeholder_status';
import PendingStatus from 'soapbox/features/ui/components/pending_status'; import PendingStatus from 'soapbox/features/ui/components/pending_status';
import { blockAccount } from '../../actions/accounts'; import { blockAccount } from '../../actions/accounts';
@ -58,9 +57,20 @@ import { textForScreenReader, defaultMediaVisibility } from '../../components/st
import { makeGetStatus } from '../../selectors'; import { makeGetStatus } from '../../selectors';
import { attachFullscreenListener, detachFullscreenListener, isFullscreen } from '../ui/util/fullscreen'; import { attachFullscreenListener, detachFullscreenListener, isFullscreen } from '../ui/util/fullscreen';
import ActionBar from './components/action_bar'; import ActionBar from './components/action-bar';
import DetailedStatus from './components/detailed_status'; import DetailedStatus from './components/detailed-status';
import ThreadStatus from './components/thread_status'; import ThreadStatus from './components/thread-status';
import type { AxiosError } from 'axios';
import type { History } from 'history';
import type { AnyAction } from 'redux';
import type { ThunkDispatch } from 'redux-thunk';
import type { RootState } from 'soapbox/store';
import type {
Account as AccountEntity,
Attachment as AttachmentEntity,
Status as StatusEntity,
} from 'soapbox/types/entities';
const messages = defineMessages({ const messages = defineMessages({
title: { id: 'status.title', defaultMessage: '@{username}\'s Post' }, title: { id: 'status.title', defaultMessage: '@{username}\'s Post' },
@ -84,8 +94,8 @@ const makeMapStateToProps = () => {
const getStatus = makeGetStatus(); const getStatus = makeGetStatus();
const getAncestorsIds = createSelector([ const getAncestorsIds = createSelector([
(_, { id }) => id, (_: RootState, statusId: string) => statusId,
state => state.getIn(['contexts', 'inReplyTos']), (state: RootState) => state.contexts.get('inReplyTos'),
], (statusId, inReplyTos) => { ], (statusId, inReplyTos) => {
let ancestorsIds = ImmutableOrderedSet(); let ancestorsIds = ImmutableOrderedSet();
let id = statusId; let id = statusId;
@ -99,8 +109,8 @@ const makeMapStateToProps = () => {
}); });
const getDescendantsIds = createSelector([ const getDescendantsIds = createSelector([
(_, { id }) => id, (_: RootState, statusId: string) => statusId,
state => state.getIn(['contexts', 'replies']), (state: RootState) => state.contexts.get('replies'),
], (statusId, contextReplies) => { ], (statusId, contextReplies) => {
let descendantsIds = ImmutableOrderedSet(); let descendantsIds = ImmutableOrderedSet();
const ids = [statusId]; const ids = [statusId];
@ -118,7 +128,7 @@ const makeMapStateToProps = () => {
} }
if (replies) { if (replies) {
replies.reverse().forEach(reply => { replies.reverse().forEach((reply: string) => {
ids.unshift(reply); ids.unshift(reply);
}); });
} }
@ -127,15 +137,15 @@ const makeMapStateToProps = () => {
return descendantsIds; return descendantsIds;
}); });
const mapStateToProps = (state, props) => { const mapStateToProps = (state: RootState, props: { params: RouteParams }) => {
const status = getStatus(state, { id: props.params.statusId }); const status = getStatus(state, { id: props.params.statusId });
let ancestorsIds = ImmutableOrderedSet(); let ancestorsIds = ImmutableOrderedSet();
let descendantsIds = ImmutableOrderedSet(); let descendantsIds = ImmutableOrderedSet();
if (status) { if (status) {
const statusId = status.get('id'); const statusId = status.id;
ancestorsIds = getAncestorsIds(state, { id: state.getIn(['contexts', 'inReplyTos', statusId]) }); ancestorsIds = getAncestorsIds(state, state.contexts.getIn(['inReplyTos', statusId]));
descendantsIds = getDescendantsIds(state, { id: statusId }); descendantsIds = getDescendantsIds(state, statusId);
ancestorsIds = ancestorsIds.delete(statusId).subtract(descendantsIds); ancestorsIds = ancestorsIds.delete(statusId).subtract(descendantsIds);
descendantsIds = descendantsIds.delete(statusId).subtract(ancestorsIds); descendantsIds = descendantsIds.delete(statusId).subtract(ancestorsIds);
} }
@ -146,42 +156,56 @@ const makeMapStateToProps = () => {
status, status,
ancestorsIds, ancestorsIds,
descendantsIds, descendantsIds,
askReplyConfirmation: state.getIn(['compose', 'text']).trim().length !== 0, askReplyConfirmation: state.compose.get('text', '').trim().length !== 0,
domain: state.getIn(['meta', 'domain']), me: state.me,
me: state.get('me'),
displayMedia: getSettings(state).get('displayMedia'), displayMedia: getSettings(state).get('displayMedia'),
allowedEmoji: soapbox.get('allowedEmoji'), allowedEmoji: soapbox.allowedEmoji,
}; };
}; };
return mapStateToProps; return mapStateToProps;
}; };
export default @connect(makeMapStateToProps) type DisplayMedia = 'default' | 'hide_all' | 'show_all';
@injectIntl type RouteParams = { statusId: string };
@withRouter
class Status extends ImmutablePureComponent {
static propTypes = { interface IStatus extends RouteComponentProps, IntlComponentProps {
params: PropTypes.object.isRequired, params: RouteParams,
dispatch: PropTypes.func.isRequired, dispatch: ThunkDispatch<RootState, void, AnyAction>,
status: ImmutablePropTypes.record, status: StatusEntity,
ancestorsIds: ImmutablePropTypes.orderedSet, ancestorsIds: ImmutableOrderedSet<string>,
descendantsIds: ImmutablePropTypes.orderedSet, descendantsIds: ImmutableOrderedSet<string>,
intl: PropTypes.object.isRequired, askReplyConfirmation: boolean,
askReplyConfirmation: PropTypes.bool, displayMedia: DisplayMedia,
domain: PropTypes.string, allowedEmoji: ImmutableList<string>,
displayMedia: PropTypes.string, onOpenMedia: (media: ImmutableList<AttachmentEntity>, index: number) => void,
history: PropTypes.object, onOpenVideo: (video: AttachmentEntity, time: number) => void,
}; }
interface IStatusState {
fullscreen: boolean,
showMedia: boolean,
loadedStatusId?: string,
emojiSelectorFocused: boolean,
isLoaded: boolean,
error?: AxiosError,
}
class Status extends ImmutablePureComponent<IStatus, IStatusState> {
state = { state = {
fullscreen: false, fullscreen: false,
showMedia: defaultMediaVisibility(this.props.status, this.props.displayMedia), showMedia: defaultMediaVisibility(this.props.status, this.props.displayMedia),
loadedStatusId: undefined, loadedStatusId: undefined,
emojiSelectorFocused: false, emojiSelectorFocused: false,
isLoaded: Boolean(this.props.status),
error: undefined,
}; };
node: HTMLDivElement | null = null;
status: HTMLDivElement | null = null;
_scrolledIntoView: boolean = false;
fetchData = () => { fetchData = () => {
const { dispatch, params } = this.props; const { dispatch, params } = this.props;
const { statusId } = params; const { statusId } = params;
@ -190,7 +214,11 @@ class Status extends ImmutablePureComponent {
} }
componentDidMount() { componentDidMount() {
this.fetchData(); this.fetchData().then(() => {
this.setState({ isLoaded: true });
}).catch(error => {
this.setState({ error, isLoaded: true });
});
attachFullscreenListener(this.onFullScreenChange); attachFullscreenListener(this.onFullScreenChange);
} }
@ -198,35 +226,35 @@ class Status extends ImmutablePureComponent {
this.setState({ showMedia: !this.state.showMedia }); this.setState({ showMedia: !this.state.showMedia });
} }
handleEmojiReactClick = (status, emoji) => { handleEmojiReactClick = (status: StatusEntity, emoji: string) => {
this.props.dispatch(simpleEmojiReact(status, emoji)); this.props.dispatch(simpleEmojiReact(status, emoji));
} }
handleFavouriteClick = (status) => { handleFavouriteClick = (status: StatusEntity) => {
if (status.get('favourited')) { if (status.favourited) {
this.props.dispatch(unfavourite(status)); this.props.dispatch(unfavourite(status));
} else { } else {
this.props.dispatch(favourite(status)); this.props.dispatch(favourite(status));
} }
} }
handlePin = (status) => { handlePin = (status: StatusEntity) => {
if (status.get('pinned')) { if (status.pinned) {
this.props.dispatch(unpin(status)); this.props.dispatch(unpin(status));
} else { } else {
this.props.dispatch(pin(status)); this.props.dispatch(pin(status));
} }
} }
handleBookmark = (status) => { handleBookmark = (status: StatusEntity) => {
if (status.get('bookmarked')) { if (status.bookmarked) {
this.props.dispatch(unbookmark(status)); this.props.dispatch(unbookmark(status));
} else { } else {
this.props.dispatch(bookmark(status)); this.props.dispatch(bookmark(status));
} }
} }
handleReplyClick = (status) => { handleReplyClick = (status: StatusEntity) => {
const { askReplyConfirmation, dispatch, intl } = this.props; const { askReplyConfirmation, dispatch, intl } = this.props;
if (askReplyConfirmation) { if (askReplyConfirmation) {
dispatch(openModal('CONFIRM', { dispatch(openModal('CONFIRM', {
@ -239,14 +267,14 @@ class Status extends ImmutablePureComponent {
} }
} }
handleModalReblog = (status) => { handleModalReblog = (status: StatusEntity) => {
this.props.dispatch(reblog(status)); this.props.dispatch(reblog(status));
} }
handleReblogClick = (status, e) => { handleReblogClick = (status: StatusEntity, e?: React.MouseEvent) => {
this.props.dispatch((_, getState) => { this.props.dispatch((_, getState) => {
const boostModal = getSettings(getState()).get('boostModal'); const boostModal = getSettings(getState()).get('boostModal');
if (status.get('reblogged')) { if (status.reblogged) {
this.props.dispatch(unreblog(status)); this.props.dispatch(unreblog(status));
} else { } else {
if ((e && e.shiftKey) || !boostModal) { if ((e && e.shiftKey) || !boostModal) {
@ -258,7 +286,7 @@ class Status extends ImmutablePureComponent {
}); });
} }
handleQuoteClick = (status, e) => { handleQuoteClick = (status: StatusEntity) => {
const { askReplyConfirmation, dispatch, intl } = this.props; const { askReplyConfirmation, dispatch, intl } = this.props;
if (askReplyConfirmation) { if (askReplyConfirmation) {
dispatch(openModal('CONFIRM', { dispatch(openModal('CONFIRM', {
@ -271,147 +299,148 @@ class Status extends ImmutablePureComponent {
} }
} }
handleDeleteClick = (status, history, withRedraft = false) => { handleDeleteClick = (status: StatusEntity, history: History, withRedraft = false) => {
const { dispatch, intl } = this.props; const { dispatch, intl } = this.props;
this.props.dispatch((_, getState) => { this.props.dispatch((_, getState) => {
const deleteModal = getSettings(getState()).get('deleteModal'); const deleteModal = getSettings(getState()).get('deleteModal');
if (!deleteModal) { if (!deleteModal) {
dispatch(deleteStatus(status.get('id'), history, withRedraft)); dispatch(deleteStatus(status.id, history, withRedraft));
} else { } else {
dispatch(openModal('CONFIRM', { dispatch(openModal('CONFIRM', {
icon: withRedraft ? require('@tabler/icons/icons/edit.svg') : require('@tabler/icons/icons/trash.svg'), icon: withRedraft ? require('@tabler/icons/icons/edit.svg') : require('@tabler/icons/icons/trash.svg'),
heading: intl.formatMessage(withRedraft ? messages.redraftHeading : messages.deleteHeading), heading: intl.formatMessage(withRedraft ? messages.redraftHeading : messages.deleteHeading),
message: intl.formatMessage(withRedraft ? messages.redraftMessage : messages.deleteMessage), message: intl.formatMessage(withRedraft ? messages.redraftMessage : messages.deleteMessage),
confirm: intl.formatMessage(withRedraft ? messages.redraftConfirm : messages.deleteConfirm), confirm: intl.formatMessage(withRedraft ? messages.redraftConfirm : messages.deleteConfirm),
onConfirm: () => dispatch(deleteStatus(status.get('id'), history, withRedraft)), onConfirm: () => dispatch(deleteStatus(status.id, history, withRedraft)),
})); }));
} }
}); });
} }
handleDirectClick = (account, router) => { handleDirectClick = (account: AccountEntity, router: History) => {
this.props.dispatch(directCompose(account, router)); this.props.dispatch(directCompose(account, router));
} }
handleChatClick = (account, router) => { handleChatClick = (account: AccountEntity, router: History) => {
this.props.dispatch(launchChat(account.get('id'), router)); this.props.dispatch(launchChat(account.id, router));
} }
handleMentionClick = (account, router) => { handleMentionClick = (account: AccountEntity, router: History) => {
this.props.dispatch(mentionCompose(account, router)); this.props.dispatch(mentionCompose(account, router));
} }
handleOpenMedia = (media, index) => { handleOpenMedia = (media: ImmutableList<AttachmentEntity>, index: number) => {
this.props.dispatch(openModal('MEDIA', { media, index })); this.props.dispatch(openModal('MEDIA', { media, index }));
} }
handleOpenVideo = (media, time) => { handleOpenVideo = (media: ImmutableList<AttachmentEntity>, time: number) => {
this.props.dispatch(openModal('VIDEO', { media, time })); this.props.dispatch(openModal('VIDEO', { media, time }));
} }
handleHotkeyOpenMedia = e => { handleHotkeyOpenMedia = (e?: KeyboardEvent) => {
const { onOpenMedia, onOpenVideo } = this.props; const { status, onOpenMedia, onOpenVideo } = this.props;
const status = this._properStatus(); const firstAttachment = status.media_attachments.get(0);
e.preventDefault(); e?.preventDefault();
if (status.get('media_attachments').size > 0) { if (status.media_attachments.size > 0 && firstAttachment) {
if (status.getIn(['media_attachments', 0, 'type']) === 'video') { if (firstAttachment.type === 'video') {
onOpenVideo(status.getIn(['media_attachments', 0]), 0); onOpenVideo(firstAttachment, 0);
} else { } else {
onOpenMedia(status.get('media_attachments'), 0); onOpenMedia(status.media_attachments, 0);
} }
} }
} }
handleMuteClick = (account) => { handleMuteClick = (account: AccountEntity) => {
this.props.dispatch(initMuteModal(account)); this.props.dispatch(initMuteModal(account));
} }
handleConversationMuteClick = (status) => { handleConversationMuteClick = (status: StatusEntity) => {
if (status.get('muted')) { if (status.muted) {
this.props.dispatch(unmuteStatus(status.get('id'))); this.props.dispatch(unmuteStatus(status.id));
} else { } else {
this.props.dispatch(muteStatus(status.get('id'))); this.props.dispatch(muteStatus(status.id));
} }
} }
handleToggleHidden = (status) => { handleToggleHidden = (status: StatusEntity) => {
if (status.get('hidden')) { if (status.hidden) {
this.props.dispatch(revealStatus(status.get('id'))); this.props.dispatch(revealStatus(status.id));
} else { } else {
this.props.dispatch(hideStatus(status.get('id'))); this.props.dispatch(hideStatus(status.id));
} }
} }
handleToggleAll = () => { handleToggleAll = () => {
const { status, ancestorsIds, descendantsIds } = this.props; const { status, ancestorsIds, descendantsIds } = this.props;
const statusIds = [status.get('id')].concat(ancestorsIds.toJS(), descendantsIds.toJS()); const statusIds = [status.id].concat(ancestorsIds.toArray(), descendantsIds.toArray());
if (status.get('hidden')) { if (status.hidden) {
this.props.dispatch(revealStatus(statusIds)); this.props.dispatch(revealStatus(statusIds));
} else { } else {
this.props.dispatch(hideStatus(statusIds)); this.props.dispatch(hideStatus(statusIds));
} }
} }
handleBlockClick = (status) => { handleBlockClick = (status: StatusEntity) => {
const { dispatch, intl } = this.props; const { dispatch, intl } = this.props;
const account = status.get('account'); const { account } = status;
if (!account || typeof account !== 'object') return;
dispatch(openModal('CONFIRM', { dispatch(openModal('CONFIRM', {
icon: require('@tabler/icons/icons/ban.svg'), icon: require('@tabler/icons/icons/ban.svg'),
heading: <FormattedMessage id='confirmations.block.heading' defaultMessage='Block @{name}' values={{ name: account.get('acct') }} />, heading: <FormattedMessage id='confirmations.block.heading' defaultMessage='Block @{name}' values={{ name: account.acct }} />,
message: <FormattedMessage id='confirmations.block.message' defaultMessage='Are you sure you want to block {name}?' values={{ name: <strong>@{account.get('acct')}</strong> }} />, message: <FormattedMessage id='confirmations.block.message' defaultMessage='Are you sure you want to block {name}?' values={{ name: <strong>@{account.acct}</strong> }} />,
confirm: intl.formatMessage(messages.blockConfirm), confirm: intl.formatMessage(messages.blockConfirm),
onConfirm: () => dispatch(blockAccount(account.get('id'))), onConfirm: () => dispatch(blockAccount(account.id)),
secondary: intl.formatMessage(messages.blockAndReport), secondary: intl.formatMessage(messages.blockAndReport),
onSecondary: () => { onSecondary: () => {
dispatch(blockAccount(account.get('id'))); dispatch(blockAccount(account.id));
dispatch(initReport(account, status)); dispatch(initReport(account, status));
}, },
})); }));
} }
handleReport = (status) => { handleReport = (status: StatusEntity) => {
this.props.dispatch(initReport(status.get('account'), status)); this.props.dispatch(initReport(status.account, status));
} }
handleEmbed = (status) => { handleEmbed = (status: StatusEntity) => {
this.props.dispatch(openModal('EMBED', { url: status.get('url') })); this.props.dispatch(openModal('EMBED', { url: status.url }));
} }
handleDeactivateUser = (status) => { handleDeactivateUser = (status: StatusEntity) => {
const { dispatch, intl } = this.props; const { dispatch, intl } = this.props;
dispatch(deactivateUserModal(intl, status.getIn(['account', 'id']))); dispatch(deactivateUserModal(intl, status.getIn(['account', 'id'])));
} }
handleDeleteUser = (status) => { handleDeleteUser = (status: StatusEntity) => {
const { dispatch, intl } = this.props; const { dispatch, intl } = this.props;
dispatch(deleteUserModal(intl, status.getIn(['account', 'id']))); dispatch(deleteUserModal(intl, status.getIn(['account', 'id'])));
} }
handleToggleStatusSensitivity = (status) => { handleToggleStatusSensitivity = (status: StatusEntity) => {
const { dispatch, intl } = this.props; const { dispatch, intl } = this.props;
dispatch(toggleStatusSensitivityModal(intl, status.get('id'), status.get('sensitive'))); dispatch(toggleStatusSensitivityModal(intl, status.id, status.sensitive));
} }
handleDeleteStatus = (status) => { handleDeleteStatus = (status: StatusEntity) => {
const { dispatch, intl } = this.props; const { dispatch, intl } = this.props;
dispatch(deleteStatusModal(intl, status.get('id'))); dispatch(deleteStatusModal(intl, status.id));
} }
handleHotkeyMoveUp = () => { handleHotkeyMoveUp = () => {
this.handleMoveUp(this.props.status.get('id')); this.handleMoveUp(this.props.status.id);
} }
handleHotkeyMoveDown = () => { handleHotkeyMoveDown = () => {
this.handleMoveDown(this.props.status.get('id')); this.handleMoveDown(this.props.status.id);
} }
handleHotkeyReply = e => { handleHotkeyReply = (e?: KeyboardEvent) => {
e.preventDefault(); e?.preventDefault();
this.handleReplyClick(this.props.status); this.handleReplyClick(this.props.status);
} }
@ -423,9 +452,11 @@ class Status extends ImmutablePureComponent {
this.handleReblogClick(this.props.status); this.handleReblogClick(this.props.status);
} }
handleHotkeyMention = e => { handleHotkeyMention = (e?: KeyboardEvent) => {
e.preventDefault(); e?.preventDefault();
this.handleMentionClick(this.props.status.get('account')); const { account } = this.props.status;
if (!account || typeof account !== 'object') return;
this.handleMentionClick(account, this.props.history);
} }
handleHotkeyOpenProfile = () => { handleHotkeyOpenProfile = () => {
@ -444,10 +475,10 @@ class Status extends ImmutablePureComponent {
this._expandEmojiSelector(); this._expandEmojiSelector();
} }
handleMoveUp = id => { handleMoveUp = (id: string) => {
const { status, ancestorsIds, descendantsIds } = this.props; const { status, ancestorsIds, descendantsIds } = this.props;
if (id === status.get('id')) { if (id === status.id) {
this._selectChild(ancestorsIds.size - 1, true); this._selectChild(ancestorsIds.size - 1, true);
} else { } else {
let index = ImmutableList(ancestorsIds).indexOf(id); let index = ImmutableList(ancestorsIds).indexOf(id);
@ -461,10 +492,10 @@ class Status extends ImmutablePureComponent {
} }
} }
handleMoveDown = id => { handleMoveDown = (id: string) => {
const { status, ancestorsIds, descendantsIds } = this.props; const { status, ancestorsIds, descendantsIds } = this.props;
if (id === status.get('id')) { if (id === status.id) {
this._selectChild(ancestorsIds.size + 1, false); this._selectChild(ancestorsIds.size + 1, false);
} else { } else {
let index = ImmutableList(ancestorsIds).indexOf(id); let index = ImmutableList(ancestorsIds).indexOf(id);
@ -478,26 +509,28 @@ class Status extends ImmutablePureComponent {
} }
} }
handleEmojiSelectorExpand = e => { handleEmojiSelectorExpand: React.EventHandler<React.KeyboardEvent> = e => {
if (e.key === 'Enter') { if (e.key === 'Enter') {
this._expandEmojiSelector(); this._expandEmojiSelector();
} }
e.preventDefault(); e.preventDefault();
} }
handleEmojiSelectorUnfocus = () => { handleEmojiSelectorUnfocus: React.EventHandler<React.KeyboardEvent> = () => {
this.setState({ emojiSelectorFocused: false }); this.setState({ emojiSelectorFocused: false });
} }
_expandEmojiSelector = () => { _expandEmojiSelector = () => {
if (!this.status) return;
this.setState({ emojiSelectorFocused: true }); this.setState({ emojiSelectorFocused: true });
const firstEmoji = this.status.querySelector('.emoji-react-selector .emoji-react-selector__emoji'); const firstEmoji: HTMLButtonElement | null = this.status.querySelector('.emoji-react-selector .emoji-react-selector__emoji');
firstEmoji.focus(); firstEmoji?.focus();
}; };
_selectChild(index, align_top) { _selectChild(index: number, align_top: boolean) {
const container = this.node; const container = this.node;
const element = container.querySelectorAll('.focusable')[index]; if (!container) return;
const element = container.querySelectorAll('.focusable')[index] as HTMLButtonElement;
if (element) { if (element) {
if (align_top && container.scrollTop > element.offsetTop) { if (align_top && container.scrollTop > element.offsetTop) {
@ -509,7 +542,7 @@ class Status extends ImmutablePureComponent {
} }
} }
renderTombstone(id) { renderTombstone(id: string) {
return ( return (
<div className='tombstone' key={id}> <div className='tombstone' key={id}>
<p><FormattedMessage id='statuses.tombstone' defaultMessage='One or more posts is unavailable.' /></p> <p><FormattedMessage id='statuses.tombstone' defaultMessage='One or more posts is unavailable.' /></p>
@ -517,22 +550,23 @@ class Status extends ImmutablePureComponent {
); );
} }
renderStatus(id) { renderStatus(id: string) {
const { status } = this.props; const { status } = this.props;
return ( return (
<ThreadStatus <ThreadStatus
key={id} key={id}
id={id} id={id}
focusedStatusId={status && status.get('id')} focusedStatusId={status.id}
// @ts-ignore FIXME
onMoveUp={this.handleMoveUp} onMoveUp={this.handleMoveUp}
onMoveDown={this.handleMoveDown} onMoveDown={this.handleMoveDown}
contextType='thread'
/> />
); );
} }
renderPendingStatus(id) { renderPendingStatus(id: string) {
const { status } = this.props;
const idempotencyKey = id.replace(/^末pending-/, ''); const idempotencyKey = id.replace(/^末pending-/, '');
return ( return (
@ -540,7 +574,7 @@ class Status extends ImmutablePureComponent {
className='thread__status' className='thread__status'
key={id} key={id}
idempotencyKey={idempotencyKey} idempotencyKey={idempotencyKey}
focusedStatusId={status && status.get('id')} focusedStatusId={status.id}
onMoveUp={this.handleMoveUp} onMoveUp={this.handleMoveUp}
onMoveDown={this.handleMoveDown} onMoveDown={this.handleMoveDown}
contextType='thread' contextType='thread'
@ -548,7 +582,7 @@ class Status extends ImmutablePureComponent {
); );
} }
renderChildren(list) { renderChildren(list: ImmutableOrderedSet<string>) {
return list.map(id => { return list.map(id => {
if (id.endsWith('-tombstone')) { if (id.endsWith('-tombstone')) {
return this.renderTombstone(id); return this.renderTombstone(id);
@ -560,16 +594,16 @@ class Status extends ImmutablePureComponent {
}); });
} }
setRef = c => { setRef: React.RefCallback<HTMLDivElement> = c => {
this.node = c; this.node = c;
} }
setStatusRef = c => { setStatusRef: React.RefCallback<HTMLDivElement> = c => {
this.status = c; this.status = c;
} }
componentDidUpdate(prevProps, prevState) { componentDidUpdate(prevProps: IStatus, prevState: IStatusState) {
const { params, status } = this.props; const { params, status, displayMedia } = this.props;
const { ancestorsIds } = prevProps; const { ancestorsIds } = prevProps;
if (params.statusId !== prevProps.params.statusId) { if (params.statusId !== prevProps.params.statusId) {
@ -577,8 +611,8 @@ class Status extends ImmutablePureComponent {
this.fetchData(); this.fetchData();
} }
if (status && status.get('id') !== prevState.loadedStatusId) { if (status && status.id !== prevState.loadedStatusId) {
this.setState({ showMedia: defaultMediaVisibility(status), loadedStatusId: status.get('id') }); this.setState({ showMedia: defaultMediaVisibility(status, displayMedia), loadedStatusId: status.id });
} }
if (this._scrolledIntoView) { if (this._scrolledIntoView) {
@ -589,7 +623,7 @@ class Status extends ImmutablePureComponent {
const element = this.node.querySelector('.detailed-status'); const element = this.node.querySelector('.detailed-status');
window.requestAnimationFrame(() => { window.requestAnimationFrame(() => {
element.scrollIntoView(true); element?.scrollIntoView(true);
}); });
this._scrolledIntoView = true; this._scrolledIntoView = true;
} }
@ -609,12 +643,17 @@ class Status extends ImmutablePureComponent {
render() { render() {
let ancestors, descendants; let ancestors, descendants;
const { status, ancestorsIds, descendantsIds, intl, domain } = this.props; const { status, ancestorsIds, descendantsIds, intl } = this.props;
if (status === null) { if (!status && this.state.isLoaded) {
// TODO: handle errors other than 404 with `this.state.error?.response?.status`
return ( return (
<MissingIndicator /> <MissingIndicator />
); );
} else if (!status) {
return (
<PlaceholderStatus />
);
} }
if (ancestorsIds && ancestorsIds.size > 0) { if (ancestorsIds && ancestorsIds.size > 0) {
@ -625,7 +664,9 @@ class Status extends ImmutablePureComponent {
descendants = this.renderChildren(descendantsIds); descendants = this.renderChildren(descendantsIds);
} }
const handlers = { type HotkeyHandlers = { [key: string]: (keyEvent?: KeyboardEvent) => void };
const handlers: HotkeyHandlers = {
moveUp: this.handleHotkeyMoveUp, moveUp: this.handleHotkeyMoveUp,
moveDown: this.handleHotkeyMoveDown, moveDown: this.handleHotkeyMoveDown,
reply: this.handleHotkeyReply, reply: this.handleHotkeyReply,
@ -639,8 +680,8 @@ class Status extends ImmutablePureComponent {
react: this.handleHotkeyReact, react: this.handleHotkeyReact,
}; };
const username = status.getIn(['account', 'acct']); const username = String(status.getIn(['account', 'acct']));
const titleMessage = status && status.get('visibility') === 'direct' ? messages.titleDirect : messages.title; const titleMessage = status.visibility === 'direct' ? messages.titleDirect : messages.title;
return ( return (
<Column label={intl.formatMessage(titleMessage, { username })} transparent> <Column label={intl.formatMessage(titleMessage, { username })} transparent>
@ -656,13 +697,19 @@ class Status extends ImmutablePureComponent {
<div className='thread__status thread__status--focused'> <div className='thread__status thread__status--focused'>
<HotKeys handlers={handlers}> <HotKeys handlers={handlers}>
<div ref={this.setStatusRef} className={classNames('detailed-status__wrapper')} tabIndex='0' aria-label={textForScreenReader(intl, status, false)}> <div
ref={this.setStatusRef}
className={classNames('detailed-status__wrapper')}
tabIndex={0}
// FIXME: no "reblogged by" text is added for the screen reader
aria-label={textForScreenReader(intl, status)}
>
{/* @ts-ignore */}
<DetailedStatus <DetailedStatus
status={status} status={status}
onOpenVideo={this.handleOpenVideo} onOpenVideo={this.handleOpenVideo}
onOpenMedia={this.handleOpenMedia} onOpenMedia={this.handleOpenMedia}
onToggleHidden={this.handleToggleHidden} onToggleHidden={this.handleToggleHidden}
domain={domain}
showMedia={this.state.showMedia} showMedia={this.state.showMedia}
onToggleMediaVisibility={this.handleToggleMediaVisibility} onToggleMediaVisibility={this.handleToggleMediaVisibility}
/> />
@ -713,3 +760,7 @@ class Status extends ImmutablePureComponent {
} }
} }
const WrappedComponent = withRouter(injectIntl(Status));
// @ts-ignore
export default connect(makeMapStateToProps)(WrappedComponent);

View File

@ -7,7 +7,7 @@ import { Link } from 'react-router-dom';
import { logOut, switchAccount } from 'soapbox/actions/auth'; import { logOut, switchAccount } from 'soapbox/actions/auth';
import { fetchOwnAccounts } from 'soapbox/actions/auth'; import { fetchOwnAccounts } from 'soapbox/actions/auth';
import { Menu, MenuButton, MenuDivider, MenuItem, MenuLink, MenuList } from 'soapbox/components/ui'; import { Menu, MenuButton, MenuDivider, MenuItem, MenuLink, MenuList } from 'soapbox/components/ui';
import { useAppSelector } from 'soapbox/hooks'; import { useAppSelector, useOwnAccount } from 'soapbox/hooks';
import { makeGetAccount } from 'soapbox/selectors'; import { makeGetAccount } from 'soapbox/selectors';
import Account from '../../../components/account'; import Account from '../../../components/account';
@ -36,8 +36,7 @@ const ProfileDropdown: React.FC<IProfileDropdown> = ({ account, children }) => {
const dispatch = useDispatch(); const dispatch = useDispatch();
const intl = useIntl(); const intl = useIntl();
const me = useAppSelector((state) => state.me); const currentAccount = useOwnAccount();
const currentAccount = useAppSelector((state) => getAccount(state, me));
const authUsers = useAppSelector((state) => state.auth.get('users')); const authUsers = useAppSelector((state) => state.auth.get('users'));
const isCurrentAccountStaff = Boolean(currentAccount?.staff); const isCurrentAccountStaff = Boolean(currentAccount?.staff);
const otherAccounts = useAppSelector((state) => authUsers.map((authUser: any) => getAccount(state, authUser.get('id')))); const otherAccounts = useAppSelector((state) => authUsers.map((authUser: any) => getAccount(state, authUser.get('id'))));

View File

@ -1,15 +1,13 @@
import React from 'react'; import React from 'react';
import { FormattedMessage } from 'react-intl'; import { FormattedMessage } from 'react-intl';
import { getSoapboxConfig } from 'soapbox/actions/soapbox';
import { Button, Stack, Text } from 'soapbox/components/ui'; import { Button, Stack, Text } from 'soapbox/components/ui';
import { useAppSelector } from 'soapbox/hooks'; import { useAppSelector, useSoapboxConfig } from 'soapbox/hooks';
const SignUpPanel = () => { const SignUpPanel = () => {
const soapboxConfig = useAppSelector((state) => getSoapboxConfig(state)); const { singleUserMode } = useSoapboxConfig();
const siteTitle: string = useAppSelector((state) => state.instance.title); const siteTitle = useAppSelector((state) => state.instance.title);
const me: boolean | null = useAppSelector((state) => state.me); const me = useAppSelector((state) => state.me);
const singleUserMode: boolean = soapboxConfig.get('singleUserMode');
if (me || singleUserMode) return null; if (me || singleUserMode) return null;

View File

@ -49,7 +49,7 @@ export interface ReducerAccount extends AccountRecord {
moved: string | null, moved: string | null,
} }
type State = ImmutableMap<string | number, ReducerAccount>; type State = ImmutableMap<any, ReducerAccount>;
const initialState: State = ImmutableMap(); const initialState: State = ImmutableMap();

View File

@ -10,17 +10,21 @@ import {
ME_PATCH_SUCCESS, ME_PATCH_SUCCESS,
} from '../actions/me'; } from '../actions/me';
const initialState = null; import type { AxiosError } from 'axios';
import type { AnyAction } from 'redux';
import type { Me } from 'soapbox/types/soapbox';
const handleForbidden = (state, error) => { const initialState: Me = null;
if ([401, 403].includes(error.response?.status)) {
const handleForbidden = (state: Me, error: AxiosError) => {
if (([401, 403] as any[]).includes(error.response?.status)) {
return false; return false;
} else { } else {
return state; return state;
} }
}; };
export default function me(state = initialState, action) { export default function me(state: Me = initialState, action: AnyAction): Me {
switch(action.type) { switch(action.type) {
case ME_FETCH_SUCCESS: case ME_FETCH_SUCCESS:
case ME_PATCH_SUCCESS: case ME_PATCH_SUCCESS:

View File

@ -98,12 +98,12 @@ const toServerSideType = (columnType: string): string => {
} }
}; };
type FilterContext = { contextType: string }; type FilterContext = { contextType?: string };
export const getFilters = (state: RootState, { contextType }: FilterContext) => { export const getFilters = (state: RootState, query: FilterContext) => {
return state.filters.filter((filter): boolean => { return state.filters.filter((filter): boolean => {
return contextType return query?.contextType
&& filter.get('context').includes(toServerSideType(contextType)) && filter.get('context').includes(toServerSideType(query.contextType))
&& (filter.get('expires_at') === null && (filter.get('expires_at') === null
|| Date.parse(filter.get('expires_at')) > new Date().getTime()); || Date.parse(filter.get('expires_at')) > new Date().getTime());
}); });
@ -132,7 +132,7 @@ export const regexFromFilters = (filters: ImmutableList<ImmutableMap<string, any
}).join('|'), 'i'); }).join('|'), 'i');
}; };
type APIStatus = { id: string, username: string }; type APIStatus = { id: string, username?: string };
export const makeGetStatus = () => { export const makeGetStatus = () => {
return createSelector( return createSelector(