2
0

Add button to load new replies in web UI (#35210)

This commit is contained in:
Eugen Rochko
2025-07-23 15:42:07 +02:00
committed by GitHub
parent cec26d58c8
commit 14a781fa24
18 changed files with 411 additions and 26 deletions

View File

@@ -1,3 +1,5 @@
import { createAction } from '@reduxjs/toolkit';
import { apiGetContext } from 'mastodon/api/statuses';
import { createDataLoadingThunk } from 'mastodon/store/typed_functions';
@@ -6,13 +8,18 @@ import { importFetchedStatuses } from './importer';
export const fetchContext = createDataLoadingThunk(
'status/context',
({ statusId }: { statusId: string }) => apiGetContext(statusId),
(context, { dispatch }) => {
({ context, refresh }, { dispatch }) => {
const statuses = context.ancestors.concat(context.descendants);
dispatch(importFetchedStatuses(statuses));
return {
context,
refresh,
};
},
);
export const completeContextRefresh = createAction<{ statusId: string }>(
'status/context/complete',
);

View File

@@ -20,6 +20,50 @@ export const getLinks = (response: AxiosResponse) => {
return LinkHeader.parse(value);
};
export interface AsyncRefreshHeader {
id: string;
retry: number;
}
const isAsyncRefreshHeader = (obj: object): obj is AsyncRefreshHeader =>
'id' in obj && 'retry' in obj;
export const getAsyncRefreshHeader = (
response: AxiosResponse,
): AsyncRefreshHeader | null => {
const value = response.headers['mastodon-async-refresh'] as
| string
| undefined;
if (!value) {
return null;
}
const asyncRefreshHeader: Record<string, unknown> = {};
value.split(/,\s*/).forEach((pair) => {
const [key, val] = pair.split('=', 2);
let typedValue: string | number;
if (key && ['id', 'retry'].includes(key) && val) {
if (val.startsWith('"')) {
typedValue = val.slice(1, -1);
} else {
typedValue = parseInt(val);
}
asyncRefreshHeader[key] = typedValue;
}
});
if (isAsyncRefreshHeader(asyncRefreshHeader)) {
return asyncRefreshHeader;
}
return null;
};
const csrfHeader: RawAxiosRequestHeaders = {};
const setCSRFHeader = () => {
@@ -83,7 +127,7 @@ export default function api(withAuthorization = true) {
return instance;
}
type ApiUrl = `v${1 | 2}/${string}`;
type ApiUrl = `v${1 | '1_alpha' | 2}/${string}`;
type RequestParamsOrData = Record<string, unknown>;
export async function apiRequest<ApiResponse = unknown>(

View File

@@ -0,0 +1,5 @@
import { apiRequestGet } from 'mastodon/api';
import type { ApiAsyncRefreshJSON } from 'mastodon/api_types/async_refreshes';
export const apiGetAsyncRefresh = (id: string) =>
apiRequestGet<ApiAsyncRefreshJSON>(`v1_alpha/async_refreshes/${id}`);

View File

@@ -1,5 +1,14 @@
import { apiRequestGet } from 'mastodon/api';
import api, { getAsyncRefreshHeader } from 'mastodon/api';
import type { ApiContextJSON } from 'mastodon/api_types/statuses';
export const apiGetContext = (statusId: string) =>
apiRequestGet<ApiContextJSON>(`v1/statuses/${statusId}/context`);
export const apiGetContext = async (statusId: string) => {
const response = await api().request<ApiContextJSON>({
method: 'GET',
url: `/api/v1/statuses/${statusId}/context`,
});
return {
context: response.data,
refresh: getAsyncRefreshHeader(response),
};
};

View File

@@ -0,0 +1,7 @@
export interface ApiAsyncRefreshJSON {
async_refresh: {
id: string;
status: 'running' | 'finished';
result_count: number;
};
}

View File

@@ -0,0 +1,111 @@
import { useEffect, useState, useCallback } from 'react';
import { useIntl, defineMessages, FormattedMessage } from 'react-intl';
import classNames from 'classnames';
import {
fetchContext,
completeContextRefresh,
} from 'mastodon/actions/statuses';
import type { AsyncRefreshHeader } from 'mastodon/api';
import { apiGetAsyncRefresh } from 'mastodon/api/async_refreshes';
import { LoadingIndicator } from 'mastodon/components/loading_indicator';
import { useAppSelector, useAppDispatch } from 'mastodon/store';
const messages = defineMessages({
loading: {
id: 'status.context.loading',
defaultMessage: 'Checking for more replies',
},
});
export const RefreshController: React.FC<{
statusId: string;
withBorder?: boolean;
}> = ({ statusId, withBorder }) => {
const refresh = useAppSelector(
(state) => state.contexts.refreshing[statusId],
);
const dispatch = useAppDispatch();
const intl = useIntl();
const [ready, setReady] = useState(false);
const [loading, setLoading] = useState(false);
useEffect(() => {
let timeoutId: ReturnType<typeof setTimeout>;
const scheduleRefresh = (refresh: AsyncRefreshHeader) => {
timeoutId = setTimeout(() => {
void apiGetAsyncRefresh(refresh.id).then((result) => {
if (result.async_refresh.status === 'finished') {
dispatch(completeContextRefresh({ statusId }));
if (result.async_refresh.result_count > 0) {
setReady(true);
}
} else {
scheduleRefresh(refresh);
}
return '';
});
}, refresh.retry * 1000);
};
if (refresh) {
scheduleRefresh(refresh);
}
return () => {
clearTimeout(timeoutId);
};
}, [dispatch, setReady, statusId, refresh]);
const handleClick = useCallback(() => {
setLoading(true);
setReady(false);
dispatch(fetchContext({ statusId }))
.then(() => {
setLoading(false);
return '';
})
.catch(() => {
setLoading(false);
});
}, [dispatch, setReady, statusId]);
if (ready && !loading) {
return (
<button
className={classNames('load-more load-gap', {
'timeline-hint--with-descendants': withBorder,
})}
onClick={handleClick}
>
<FormattedMessage
id='status.context.load_new_replies'
defaultMessage='New replies available'
/>
</button>
);
}
if (!refresh && !loading) {
return null;
}
return (
<div
className={classNames('load-more load-gap', {
'timeline-hint--with-descendants': withBorder,
})}
aria-busy
aria-live='polite'
aria-label={intl.formatMessage(messages.loading)}
>
<LoadingIndicator />
</div>
);
};

View File

@@ -68,7 +68,7 @@ import { attachFullscreenListener, detachFullscreenListener, isFullscreen } from
import ActionBar from './components/action_bar';
import { DetailedStatus } from './components/detailed_status';
import { RefreshController } from './components/refresh_controller';
const messages = defineMessages({
revealAll: { id: 'status.show_more_all', defaultMessage: 'Show more for all' },
@@ -548,7 +548,7 @@ class Status extends ImmutablePureComponent {
render () {
let ancestors, descendants, remoteHint;
const { isLoading, status, ancestorsIds, descendantsIds, intl, domain, multiColumn, pictureInPicture } = this.props;
const { isLoading, status, ancestorsIds, descendantsIds, refresh, intl, domain, multiColumn, pictureInPicture } = this.props;
const { fullscreen } = this.state;
if (isLoading) {
@@ -578,11 +578,9 @@ class Status extends ImmutablePureComponent {
if (!isLocal) {
remoteHint = (
<TimelineHint
className={classNames(!!descendants && 'timeline-hint--with-descendants')}
url={status.get('url')}
message={<FormattedMessage id='hints.threads.replies_may_be_missing' defaultMessage='Replies from other servers may be missing.' />}
label={<FormattedMessage id='hints.threads.see_more' defaultMessage='See more replies on {domain}' values={{ domain: <strong>{status.getIn(['account', 'acct']).split('@')[1]}</strong> }} />}
<RefreshController
statusId={status.get('id')}
withBorder={!!descendants}
/>
);
}

View File

@@ -424,8 +424,6 @@
"hints.profiles.see_more_followers": "See more followers on {domain}",
"hints.profiles.see_more_follows": "See more follows on {domain}",
"hints.profiles.see_more_posts": "See more posts on {domain}",
"hints.threads.replies_may_be_missing": "Replies from other servers may be missing.",
"hints.threads.see_more": "See more replies on {domain}",
"home.column_settings.show_quotes": "Show quotes",
"home.column_settings.show_reblogs": "Show boosts",
"home.column_settings.show_replies": "Show replies",
@@ -847,6 +845,8 @@
"status.bookmark": "Bookmark",
"status.cancel_reblog_private": "Unboost",
"status.cannot_reblog": "This post cannot be boosted",
"status.context.load_new_replies": "New replies available",
"status.context.loading": "Checking for more replies",
"status.continued_thread": "Continued thread",
"status.copy": "Copy link to post",
"status.delete": "Delete",

View File

@@ -4,6 +4,7 @@ import type { Draft, UnknownAction } from '@reduxjs/toolkit';
import type { List as ImmutableList } from 'immutable';
import { timelineDelete } from 'mastodon/actions/timelines_typed';
import type { AsyncRefreshHeader } from 'mastodon/api';
import type { ApiRelationshipJSON } from 'mastodon/api_types/relationships';
import type {
ApiStatusJSON,
@@ -12,7 +13,7 @@ import type {
import type { Status } from 'mastodon/models/status';
import { blockAccountSuccess, muteAccountSuccess } from '../actions/accounts';
import { fetchContext } from '../actions/statuses';
import { fetchContext, completeContextRefresh } from '../actions/statuses';
import { TIMELINE_UPDATE } from '../actions/timelines';
import { compareId } from '../compare_id';
@@ -25,11 +26,13 @@ interface TimelineUpdateAction extends UnknownAction {
interface State {
inReplyTos: Record<string, string>;
replies: Record<string, string[]>;
refreshing: Record<string, AsyncRefreshHeader>;
}
const initialState: State = {
inReplyTos: {},
replies: {},
refreshing: {},
};
const normalizeContext = (
@@ -127,6 +130,13 @@ export const contextsReducer = createReducer(initialState, (builder) => {
builder
.addCase(fetchContext.fulfilled, (state, action) => {
normalizeContext(state, action.meta.arg.statusId, action.payload.context);
if (action.payload.refresh) {
state.refreshing[action.meta.arg.statusId] = action.payload.refresh;
}
})
.addCase(completeContextRefresh, (state, action) => {
delete state.refreshing[action.payload.statusId];
})
.addCase(blockAccountSuccess, (state, action) => {
filterContexts(