phanpy/src/pages/trending.jsx

314 lines
9.3 KiB
React
Raw Normal View History

2023-10-22 14:40:46 +03:00
import './trending.css';
2023-10-03 10:07:47 +03:00
import { MenuItem } from '@szhsin/react-menu';
2023-10-22 14:40:46 +03:00
import { getBlurHashAverageColor } from 'fast-blurhash';
import { useMemo, useRef, useState } from 'preact/hooks';
2023-04-05 20:14:38 +03:00
import { useNavigate, useParams } from 'react-router-dom';
import { useSnapshot } from 'valtio';
import Icon from '../components/icon';
import Link from '../components/link';
2023-06-13 12:46:37 +03:00
import Menu2 from '../components/menu2';
2023-10-22 14:40:46 +03:00
import RelativeTime from '../components/relative-time';
2023-04-05 20:14:38 +03:00
import Timeline from '../components/timeline';
import { api } from '../utils/api';
import { oklab2rgb, rgb2oklab } from '../utils/color-utils';
2023-04-05 20:14:38 +03:00
import { filteredItems } from '../utils/filters';
2023-10-22 14:40:46 +03:00
import pmem from '../utils/pmem';
2023-10-30 04:22:19 +03:00
import shortenNumber from '../utils/shorten-number';
2023-04-05 20:14:38 +03:00
import states from '../utils/states';
import { saveStatus } from '../utils/states';
import useTitle from '../utils/useTitle';
const LIMIT = 20;
2023-10-22 14:40:46 +03:00
const fetchLinks = pmem(
(masto) => {
return masto.v1.trends.links.list().next();
},
{
// News last much longer
maxAge: 10 * 60 * 1000, // 10 minutes
},
);
function Trending({ columnMode, ...props }) {
2023-04-05 20:14:38 +03:00
const snapStates = useSnapshot(states);
const params = columnMode ? {} : useParams();
2023-04-05 20:14:38 +03:00
const { masto, instance } = api({
instance: props?.instance || params.instance,
});
const { masto: currentMasto, instance: currentInstance } = api();
2023-04-05 20:14:38 +03:00
const title = `Trending (${instance})`;
useTitle(title, `/:instance?/trending`);
// const navigate = useNavigate();
2023-04-05 20:14:38 +03:00
const latestItem = useRef();
const [hashtags, setHashtags] = useState([]);
2023-10-22 14:40:46 +03:00
const [links, setLinks] = useState([]);
2023-04-05 20:14:38 +03:00
const trendIterator = useRef();
async function fetchTrend(firstLoad) {
if (firstLoad || !trendIterator.current) {
trendIterator.current = masto.v1.trends.statuses.list({
2023-04-05 20:14:38 +03:00
limit: LIMIT,
});
// Get hashtags
try {
const iterator = masto.v1.trends.tags.list();
const { value: tags } = await iterator.next();
2023-10-22 14:40:46 +03:00
console.log('tags', tags);
2023-10-22 20:36:07 +03:00
if (tags?.length) {
setHashtags(tags);
}
} catch (e) {
console.error(e);
}
2023-10-22 14:40:46 +03:00
// Get links
try {
2023-10-23 03:55:22 +03:00
const { value } = await fetchLinks(masto);
// 4 types available: link, photo, video, rich
// Only want links for now
const links = value?.filter?.((link) => link.type === 'link');
2023-10-22 14:40:46 +03:00
console.log('links', links);
2023-10-22 20:36:07 +03:00
if (links?.length) {
setLinks(links);
}
2023-10-22 14:40:46 +03:00
} catch (e) {
console.error(e);
}
2023-04-05 20:14:38 +03:00
}
const results = await trendIterator.current.next();
let { value } = results;
if (value?.length) {
if (firstLoad) {
latestItem.current = value[0].id;
}
// value = filteredItems(value, 'public'); // Might not work here
2023-04-05 20:14:38 +03:00
value.forEach((item) => {
saveStatus(item, instance);
});
}
2023-05-14 16:13:36 +03:00
return {
...results,
value,
};
2023-04-05 20:14:38 +03:00
}
async function checkForUpdates() {
try {
const results = await masto.v1.trends.statuses
.list({
2023-04-05 20:14:38 +03:00
limit: 1,
// NOT SUPPORTED
// since_id: latestItem.current,
2023-04-05 20:14:38 +03:00
})
.next();
let { value } = results;
value = filteredItems(value, 'public');
if (value?.length && value[0].id !== latestItem.current) {
latestItem.current = value[0].id;
2023-04-05 20:14:38 +03:00
return true;
}
return false;
} catch (e) {
return false;
}
}
const TimelineStart = useMemo(() => {
return (
2023-10-22 14:40:46 +03:00
<>
{!!hashtags.length && (
2023-10-26 19:58:42 +03:00
<div class="filter-bar expandable">
2023-10-22 14:40:46 +03:00
<Icon icon="chart" class="insignificant" size="l" />
{hashtags.map((tag, i) => {
const { name, history } = tag;
const total = history.reduce((acc, cur) => acc + +cur.uses, 0);
return (
<Link to={`/${instance}/t/${name}`} key={name}>
<span>
<span class="more-insignificant">#</span>
{name}
</span>
2023-10-30 04:22:19 +03:00
<span class="filter-count">{shortenNumber(total)}</span>
2023-10-22 14:40:46 +03:00
</Link>
);
})}
</div>
)}
{!!links.length && (
<div class="links-bar">
2023-10-22 20:36:07 +03:00
<header>
<h3>Trending News</h3>
</header>
2023-10-22 14:40:46 +03:00
{links.map((link) => {
const {
authorName,
authorUrl,
blurhash,
description,
height,
image,
imageDescription,
language,
providerName,
providerUrl,
publishedAt,
title,
url,
width,
} = link;
const domain = new URL(url).hostname
.replace(/^www\./, '')
.replace(/\/$/, '');
let accentColor;
if (blurhash) {
const averageColor = getBlurHashAverageColor(blurhash);
const labAverageColor = rgb2oklab(averageColor);
accentColor = oklab2rgb([
0.6,
labAverageColor[1],
labAverageColor[2],
]);
}
2023-10-22 14:40:46 +03:00
return (
<a
key={url}
href={url}
target="_blank"
rel="noopener noreferrer"
style={
accentColor
? {
'--accent-color': `rgb(${accentColor.join(',')})`,
'--accent-alpha-color': `rgba(${accentColor.join(
',',
)}, 0.4)`,
}
: {}
}
2023-10-22 14:40:46 +03:00
>
<article>
<figure>
<img
src={image}
alt={imageDescription}
width={width}
height={height}
2023-10-22 15:08:19 +03:00
loading="lazy"
2023-10-22 14:40:46 +03:00
/>
</figure>
<div class="article-body">
<header>
<div class="article-meta">
<span class="domain">{domain}</span>{' '}
{!!publishedAt && <>&middot; </>}
{!!publishedAt && (
<>
<RelativeTime
datetime={publishedAt}
format="micro"
/>
</>
)}
</div>
2023-10-23 06:12:15 +03:00
{!!title && (
<h1 class="title" lang={language} dir="auto">
{title}
</h1>
)}
2023-10-22 14:40:46 +03:00
</header>
{!!description && (
2023-10-23 06:12:15 +03:00
<p class="description" lang={language} dir="auto">
{description}
</p>
2023-10-22 14:40:46 +03:00
)}
</div>
</article>
</a>
);
})}
</div>
)}
</>
);
2023-10-22 14:40:46 +03:00
}, [hashtags, links]);
2023-04-05 20:14:38 +03:00
return (
<Timeline
key={instance}
title={title}
titleComponent={
<h1 class="header-double-lines">
2023-04-05 20:14:38 +03:00
<b>Trending</b>
<div>{instance}</div>
</h1>
}
id="trending"
instance={instance}
emptyText="No trending posts."
errorText="Unable to load posts"
fetchItems={fetchTrend}
checkForUpdates={checkForUpdates}
checkForUpdatesInterval={5 * 60 * 1000} // 5 minutes
2023-04-05 20:14:38 +03:00
useItemID
headerStart={<></>}
boostsCarousel={snapStates.settings.boostsCarousel}
// allowFilters
filterContext="public"
timelineStart={TimelineStart}
2023-04-05 20:14:38 +03:00
headerEnd={
2023-06-13 12:46:37 +03:00
<Menu2
portal
2023-04-05 20:14:38 +03:00
// setDownOverflow
overflow="auto"
viewScroll="close"
position="anchor"
menuButton={
<button type="button" class="plain">
<Icon icon="more" size="l" />
</button>
}
>
<MenuItem
onClick={() => {
let newInstance = prompt(
'Enter a new instance e.g. "mastodon.social"',
);
if (!/\./.test(newInstance)) {
if (newInstance) alert('Invalid instance');
return;
}
if (newInstance) {
newInstance = newInstance.toLowerCase().trim();
// navigate(`/${newInstance}/trending`);
location.hash = `/${newInstance}/trending`;
2023-04-05 20:14:38 +03:00
}
}}
>
<Icon icon="bus" /> <span>Go to another instance</span>
</MenuItem>
{currentInstance !== instance && (
<MenuItem
onClick={() => {
location.hash = `/${currentInstance}/trending`;
}}
>
<Icon icon="bus" />{' '}
<small class="menu-double-lines">
Go to my instance (<b>{currentInstance}</b>)
</small>
</MenuItem>
)}
2023-06-13 12:46:37 +03:00
</Menu2>
2023-04-05 20:14:38 +03:00
}
/>
);
}
export default Trending;