phanpy/src/pages/http-route.jsx

88 lines
2.5 KiB
React
Raw Normal View History

2023-11-25 16:26:27 +03:00
import { useLayoutEffect, useState } from 'preact/hooks';
2023-04-17 14:00:41 +03:00
import { useLocation } from 'react-router-dom';
import Link from '../components/link';
2023-11-25 16:26:27 +03:00
import Loader from '../components/loader';
import { api } from '../utils/api';
import getInstanceStatusURL, {
getInstanceStatusObject,
} from '../utils/get-instance-status-url';
2023-04-17 14:00:41 +03:00
export default function HttpRoute() {
const location = useLocation();
const url = location.pathname.replace(/^\//, '');
2023-11-25 16:26:27 +03:00
const statusObject = getInstanceStatusObject(url);
// const statusURL = getInstanceStatusURL(url);
const statusURL = statusObject?.instance
? `/${statusObject.instance}/s/${statusObject.id}`
: null;
const [uiState, setUIState] = useState('loading');
2023-08-08 12:29:04 +03:00
useLayoutEffect(() => {
2023-11-25 16:26:27 +03:00
setUIState('loading');
(async () => {
// Check if status returns 200
try {
2023-12-20 19:36:55 +03:00
const { instance, id } = statusObject;
const { masto } = api({ instance });
2023-11-25 16:26:27 +03:00
const status = await masto.v1.statuses.$select(id).fetch();
if (status) {
window.location.hash = statusURL + '?view=full';
return;
}
} catch (e) {}
// Fallback to search
{
const { masto: currentMasto, instance: currentInstance } = api();
const result = await currentMasto.v2.search.fetch({
q: url,
limit: 1,
resolve: true,
});
if (result.statuses.length) {
const status = result.statuses[0];
window.location.hash = `/${currentInstance}/s/${status.id}?view=full`;
2024-01-05 20:03:30 +03:00
} else if (result.accounts.length) {
const account = result.accounts[0];
window.location.hash = `/${currentInstance}/a/${account.id}`;
} else if (statusURL) {
2023-11-25 16:26:27 +03:00
// Fallback to original URL, which will probably show error
window.location.hash = statusURL + '?view=full';
2024-01-05 20:03:30 +03:00
} else {
setUIState('error');
2023-11-25 16:26:27 +03:00
}
}
})();
2023-08-08 12:29:04 +03:00
}, [statusURL]);
2023-04-17 14:00:41 +03:00
return (
<div class="ui-state" tabIndex="-1">
2023-11-25 16:26:27 +03:00
{uiState === 'loading' ? (
2023-08-08 12:29:04 +03:00
<>
2023-11-25 16:26:27 +03:00
<Loader abrupt />
<h2>Resolving</h2>
2023-08-08 12:29:04 +03:00
<p>
2023-11-25 16:26:27 +03:00
<a href={url} target="_blank" rel="noopener noreferrer">
{url}
</a>
2023-08-08 12:29:04 +03:00
</p>
</>
) : (
<>
2023-11-25 16:26:27 +03:00
<h2>Unable to resolve URL</h2>
2023-08-08 12:29:04 +03:00
<p>
2023-09-26 05:55:36 +03:00
<a href={url} target="_blank" rel="noopener noreferrer">
2023-08-08 12:29:04 +03:00
{url}
</a>
</p>
</>
)}
2023-04-17 14:00:41 +03:00
<hr />
<p>
<Link to="/">Go home</Link>
</p>
</div>
);
}