phanpy/src/pages/search.jsx

473 wiersze
15 KiB
React
Czysty Zwykły widok Historia

import './search.css';
2023-10-30 01:24:36 +00:00
import { useAutoAnimate } from '@formkit/auto-animate/preact';
2023-09-04 06:49:39 +00:00
import { useEffect, useLayoutEffect, useRef, useState } from 'preact/hooks';
import { useHotkeys } from 'react-hotkeys-hook';
import { InView } from 'react-intersection-observer';
import { useParams, useSearchParams } from 'react-router-dom';
2023-02-12 11:29:03 +00:00
import AccountBlock from '../components/account-block';
import Icon from '../components/icon';
import Link from '../components/link';
2023-02-11 08:27:52 +00:00
import Loader from '../components/loader';
2023-04-26 05:09:44 +00:00
import NavMenu from '../components/nav-menu';
2023-09-04 06:49:39 +00:00
import SearchForm from '../components/search-form';
import Status from '../components/status';
import { api } from '../utils/api';
2023-12-20 05:55:56 +00:00
import { fetchRelationships } from '../utils/relationships';
2023-10-30 01:22:19 +00:00
import shortenNumber from '../utils/shorten-number';
2023-12-22 10:01:41 +00:00
import usePageVisibility from '../utils/usePageVisibility';
2023-02-11 09:57:26 +00:00
import useTitle from '../utils/useTitle';
const SHORT_LIMIT = 5;
const LIMIT = 40;
2023-12-22 10:01:41 +00:00
const emptySearchParams = new URLSearchParams();
2023-12-22 10:01:41 +00:00
function Search({ columnMode, ...props }) {
const params = columnMode ? {} : useParams();
const { masto, instance, authenticated } = api({
instance: params.instance,
});
2023-08-14 03:22:42 +00:00
const [uiState, setUIState] = useState('default');
2023-12-22 10:01:41 +00:00
const [searchParams] = columnMode ? [emptySearchParams] : useSearchParams();
const searchFormRef = useRef();
2023-02-18 12:48:24 +00:00
const q = props?.query || searchParams.get('q');
2023-12-22 10:01:41 +00:00
const type = columnMode
? 'statuses'
: props?.type || searchParams.get('type');
useTitle(
q
? `Search: ${q}${
type
? ` (${
{
statuses: 'Posts',
accounts: 'Accounts',
hashtags: 'Hashtags',
}[type]
})`
: ''
}`
: 'Search',
`/search`,
);
2023-02-11 09:57:26 +00:00
const [showMore, setShowMore] = useState(false);
const offsetRef = useRef(0);
useEffect(() => {
offsetRef.current = 0;
}, [q, type]);
const scrollableRef = useRef();
useLayoutEffect(() => {
scrollableRef.current?.scrollTo?.(0, 0);
}, [q, type]);
const [statusResults, setStatusResults] = useState([]);
const [accountResults, setAccountResults] = useState([]);
2023-02-10 16:05:18 +00:00
const [hashtagResults, setHashtagResults] = useState([]);
useEffect(() => {
setStatusResults([]);
setAccountResults([]);
setHashtagResults([]);
}, [q]);
const setTypeResultsFunc = {
statuses: setStatusResults,
accounts: setAccountResults,
hashtags: setHashtagResults,
};
2023-12-20 05:55:56 +00:00
const [relationshipsMap, setRelationshipsMap] = useState({});
const loadRelationships = async (accounts) => {
if (!accounts?.length) return;
const relationships = await fetchRelationships(accounts, relationshipsMap);
if (relationships) {
setRelationshipsMap({
...relationshipsMap,
...relationships,
});
}
};
function loadResults(firstLoad) {
2023-12-22 10:01:41 +00:00
if (firstLoad) {
offsetRef.current = 0;
}
if (!firstLoad && !authenticated) {
// Search results pagination is only available to authenticated users
return;
}
2023-08-14 03:22:42 +00:00
setUIState('loading');
if (firstLoad && !type) {
setStatusResults(statusResults.slice(0, SHORT_LIMIT));
setAccountResults(accountResults.slice(0, SHORT_LIMIT));
setHashtagResults(hashtagResults.slice(0, SHORT_LIMIT));
}
(async () => {
const params = {
q,
resolve: authenticated,
limit: SHORT_LIMIT,
};
if (type) {
params.limit = LIMIT;
params.type = type;
if (authenticated) params.offset = offsetRef.current;
}
try {
const results = await masto.v2.search.fetch(params);
console.log(results);
if (type) {
if (firstLoad) {
setTypeResultsFunc[type](results[type]);
const length = results[type]?.length;
offsetRef.current = LIMIT;
setShowMore(!!length);
} else {
setTypeResultsFunc[type]((prev) => [...prev, ...results[type]]);
const length = results[type]?.length;
offsetRef.current = offsetRef.current + LIMIT;
setShowMore(!!length);
}
} else {
2023-12-03 03:00:24 +00:00
setStatusResults(results.statuses || []);
setAccountResults(results.accounts || []);
setHashtagResults(results.hashtags || []);
offsetRef.current = 0;
setShowMore(false);
}
2023-12-20 05:55:56 +00:00
loadRelationships(results.accounts);
2023-08-14 03:22:42 +00:00
setUIState('default');
} catch (err) {
console.error(err);
2023-08-14 03:22:42 +00:00
setUIState('error');
}
})();
}
2023-12-22 10:01:41 +00:00
const lastHiddenTime = useRef();
usePageVisibility((visible) => {
2024-01-02 04:20:36 +00:00
const reachStart = scrollableRef.current?.scrollTop === 0;
2023-12-22 10:01:41 +00:00
if (visible && reachStart) {
const timeDiff = Date.now() - lastHiddenTime.current;
if (!lastHiddenTime.current || timeDiff > 1000 * 3) {
// 3 seconds
loadResults(true);
} else {
lastHiddenTime.current = Date.now();
}
}
});
useEffect(() => {
2023-12-22 15:03:05 +00:00
searchFormRef.current?.setValue?.(q || '');
if (q) {
loadResults(true);
2023-09-04 06:49:39 +00:00
} else {
searchFormRef.current?.focus?.();
}
}, [q, type, instance]);
2023-09-04 06:49:39 +00:00
useHotkeys(
['/', 'Slash'],
2023-09-04 06:49:39 +00:00
(e) => {
searchFormRef.current?.focus?.();
2024-04-03 01:28:59 +00:00
searchFormRef.current?.select?.();
2023-09-04 06:49:39 +00:00
},
{
preventDefault: true,
},
);
2023-10-30 01:24:36 +00:00
const [filterBarParent] = useAutoAnimate();
return (
<div id="search-page" class="deck-container" ref={scrollableRef}>
<div class="timeline-deck deck">
2023-10-20 04:53:23 +00:00
<header class={uiState === 'loading' ? 'loading' : ''}>
<div class="header-grid">
<div class="header-side">
2023-04-26 05:09:44 +00:00
<NavMenu />
</div>
<SearchForm ref={searchFormRef} />
2023-12-22 10:01:41 +00:00
<div class="header-side">
<button
type="button"
class="plain"
onClick={() => {
loadResults(true);
}}
disabled={uiState === 'loading'}
>
<Icon icon="search" size="l" />
</button>
</div>
</div>
</header>
<main>
2023-12-22 10:01:41 +00:00
{!!q && !columnMode && (
2023-10-30 01:24:36 +00:00
<div
ref={filterBarParent}
class={`filter-bar ${uiState === 'loading' ? 'loading' : ''}`}
>
2023-09-04 09:01:06 +00:00
{!!type && (
<Link to={`/search${q ? `?q=${encodeURIComponent(q)}` : ''}`}>
All
</Link>
)}
{[
{
label: 'Accounts',
type: 'accounts',
2023-09-04 09:01:06 +00:00
to: `/search?q=${encodeURIComponent(q)}&type=accounts`,
},
{
label: 'Hashtags',
type: 'hashtags',
2023-09-04 09:01:06 +00:00
to: `/search?q=${encodeURIComponent(q)}&type=hashtags`,
},
{
label: 'Posts',
type: 'statuses',
2023-09-04 09:01:06 +00:00
to: `/search?q=${encodeURIComponent(q)}&type=statuses`,
},
]
.sort((a, b) => {
if (a.type === type) return -1;
if (b.type === type) return 1;
return 0;
})
.map((link) => (
2023-10-20 04:52:56 +00:00
<Link to={link.to} key={link.type}>
{link.label}
</Link>
))}
</div>
)}
{!!q ? (
2023-02-10 16:05:18 +00:00
<>
{(!type || type === 'accounts') && (
<>
{type !== 'accounts' && (
2024-01-29 13:11:08 +00:00
<h2 class="timeline-header">
Accounts{' '}
<Link
to={`/search?q=${encodeURIComponent(q)}&type=accounts`}
>
<Icon icon="arrow-right" size="l" />
</Link>
</h2>
)}
{accountResults.length > 0 ? (
<>
<ul class="timeline flat accounts-list">
{accountResults.map((account) => (
<li key={account.id}>
<AccountBlock
account={account}
instance={instance}
showStats
2023-12-20 05:55:56 +00:00
relationship={relationshipsMap[account.id]}
/>
</li>
))}
</ul>
{type !== 'accounts' && (
<div class="ui-state">
<Link
class="plain button"
2024-01-29 13:11:08 +00:00
to={`/search?q=${encodeURIComponent(
q,
)}&type=accounts`}
>
See more accounts <Icon icon="arrow-right" />
</Link>
</div>
)}
</>
) : (
!type &&
(uiState === 'loading' ? (
<p class="ui-state">
<Loader abrupt />
</p>
) : (
<p class="ui-state">No accounts found.</p>
))
)}
</>
2023-02-10 16:05:18 +00:00
)}
{(!type || type === 'hashtags') && (
<>
{type !== 'hashtags' && (
2024-01-29 13:11:08 +00:00
<h2 class="timeline-header">
Hashtags{' '}
<Link
to={`/search?q=${encodeURIComponent(q)}&type=hashtags`}
>
<Icon icon="arrow-right" size="l" />
</Link>
</h2>
)}
{hashtagResults.length > 0 ? (
<>
<ul class="link-list hashtag-list">
2023-10-30 01:22:19 +00:00
{hashtagResults.map((hashtag) => {
const { name, history } = hashtag;
const total = history?.reduce?.(
2023-10-30 01:22:19 +00:00
(acc, cur) => acc + +cur.uses,
0,
);
return (
<li key={`${name}-${total}`}>
2023-10-30 01:22:19 +00:00
<Link
to={
instance
? `/${instance}/t/${name}`
: `/t/${name}`
2023-10-30 01:22:19 +00:00
}
>
<Icon icon="hashtag" />
<span>{name}</span>
2023-10-30 01:22:19 +00:00
{!!total && (
<span class="count">
{shortenNumber(total)}
</span>
)}
</Link>
</li>
);
})}
</ul>
{type !== 'hashtags' && (
<div class="ui-state">
<Link
class="plain button"
2024-01-29 13:11:08 +00:00
to={`/search?q=${encodeURIComponent(
q,
)}&type=hashtags`}
>
See more hashtags <Icon icon="arrow-right" />
</Link>
</div>
)}
</>
) : (
!type &&
(uiState === 'loading' ? (
<p class="ui-state">
<Loader abrupt />
</p>
) : (
<p class="ui-state">No hashtags found.</p>
))
)}
</>
2023-02-10 16:05:18 +00:00
)}
{(!type || type === 'statuses') && (
<>
{type !== 'statuses' && (
2024-01-29 13:11:08 +00:00
<h2 class="timeline-header">
Posts{' '}
<Link
to={`/search?q=${encodeURIComponent(q)}&type=statuses`}
>
<Icon icon="arrow-right" size="l" />
</Link>
</h2>
)}
{statusResults.length > 0 ? (
<>
<ul class="timeline">
{statusResults.map((status) => (
<li key={status.id}>
<Link
class="status-link"
to={
instance
? `/${instance}/s/${status.id}`
: `/s/${status.id}`
}
>
<Status status={status} />
</Link>
</li>
))}
</ul>
{type !== 'statuses' && (
<div class="ui-state">
<Link
class="plain button"
2024-01-29 13:11:08 +00:00
to={`/search?q=${encodeURIComponent(
q,
)}&type=statuses`}
>
See more posts <Icon icon="arrow-right" />
</Link>
</div>
)}
</>
) : (
!type &&
(uiState === 'loading' ? (
<p class="ui-state">
<Loader abrupt />
</p>
) : (
<p class="ui-state">No posts found.</p>
))
)}
</>
2023-02-10 16:05:18 +00:00
)}
{!!type &&
(uiState === 'default' ? (
showMore ? (
<InView
onChange={(inView) => {
if (inView) {
loadResults();
}
}}
>
<button
type="button"
class="plain block"
onClick={() => loadResults()}
style={{ marginBlockEnd: '6em' }}
>
Show more&hellip;
</button>
</InView>
) : (
<p class="ui-state insignificant">The end.</p>
)
) : (
uiState === 'loading' && (
<p class="ui-state">
<Loader abrupt />
</p>
)
))}
2023-02-10 16:05:18 +00:00
</>
2023-02-11 08:27:52 +00:00
) : uiState === 'loading' ? (
<p class="ui-state">
<Loader abrupt />
</p>
2023-02-10 16:05:18 +00:00
) : (
2023-02-11 09:57:44 +00:00
<p class="ui-state">
Enter your search term or paste a URL above to get started.
</p>
)}
</main>
</div>
</div>
);
}
export default Search;