Files
suwayomi-material-you-webui/src/screens/SearchAll.tsx

243 lines
8.6 KiB
TypeScript
Raw Normal View History

/*
* Copyright (C) Contributors to the Suwayomi project
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
import { Card, CardActionArea, Typography } from '@mui/material';
2023-05-20 13:23:30 +02:00
import React, { useCallback, useContext, useEffect, useMemo, useState } from 'react';
import { Link } from 'react-router-dom';
import { StringParam, useQueryParam } from 'use-query-params';
import { useTranslation } from 'react-i18next';
import { ISource } from '@/typings';
2023-08-15 13:54:29 +02:00
import requestManager from '@/lib/requests/RequestManager.ts';
import useLocalStorage from '@/util/useLocalStorage';
import { langSortCmp, sourceDefualtLangs, sourceForcedDefaultLangs } from '@/util/language';
import { translateExtensionLanguage } from '@/screens/util/Extensions';
import AppbarSearch from '@/components/util/AppbarSearch';
import LangSelect from '@/components/navbar/action/LangSelect';
import MangaGrid from '@/components/MangaGrid';
import NavbarContext from '@/components/context/NavbarContext';
import { useDebounce } from '@/components/manga/hooks';
2023-05-20 13:23:30 +02:00
type SourceLoadingState = { isLoading: boolean; hasResults: boolean; emptySearch: boolean };
type SourceToLoadingStateMap = Map<string, SourceLoadingState>;
function sourceToLangList(sources: ISource[]) {
const result: string[] = [];
sources.forEach((source) => {
if (result.indexOf(source.lang) === -1) {
result.push(source.lang);
}
});
result.sort(langSortCmp);
return result;
}
const compareSourceByName = (sourceA: ISource, sourceB: ISource): -1 | 0 | 1 => {
if (sourceA.displayName < sourceB.displayName) {
return -1;
}
if (sourceA.displayName > sourceB.displayName) {
return 1;
}
return 0;
};
const compareSourcesBySearchResult = (
sourceA: ISource,
sourceB: ISource,
2023-05-20 13:23:30 +02:00
sourceToFetchedStateMap: SourceToLoadingStateMap,
): -1 | 0 | 1 => {
2023-05-20 13:23:30 +02:00
const isSourceAFetched = !sourceToFetchedStateMap.get(sourceA.id)?.isLoading ?? true;
const isSourceBFetched = !sourceToFetchedStateMap.get(sourceB.id)?.isLoading ?? true;
if (isSourceAFetched && !isSourceBFetched) {
return -1;
}
if (!isSourceAFetched && isSourceBFetched) {
return 1;
}
if (!isSourceAFetched && !isSourceBFetched) {
return 0;
}
2023-05-20 13:23:30 +02:00
const isSourceASearchResultEmpty = !sourceToFetchedStateMap.get(sourceA.id)?.hasResults;
const isSourceBSearchResultEmpty = !sourceToFetchedStateMap.get(sourceB.id)?.hasResults;
if (isSourceASearchResultEmpty && !isSourceBSearchResultEmpty) {
return 1;
}
if (isSourceBSearchResultEmpty && !isSourceASearchResultEmpty) {
return -1;
}
2023-05-20 13:23:30 +02:00
return 0;
};
2023-05-20 13:23:30 +02:00
const TRIGGER_SEARCH_THRESHOLD = 1000; // ms
const SourceSearchPreview = React.memo(
({
source,
onSearchRequestFinished,
searchString,
emptyQuery,
}: {
source: ISource;
onSearchRequestFinished: (
source: ISource,
isLoading: boolean,
hasResults: boolean,
emptySearch: boolean,
) => void;
searchString: string | null | undefined;
emptyQuery: boolean;
}) => {
const { t } = useTranslation();
const skipRequest = !searchString;
const { id, displayName, lang } = source;
const {
data: searchResult,
isLoading,
error,
abortRequest,
} = requestManager.useSourceQuickSearch(id, searchString ?? '', [], 1, { skipRequest });
const mangas = !isLoading ? searchResult?.[0]?.mangaList ?? [] : [];
const noMangasFound = !isLoading && !mangas.length;
useEffect(() => {
onSearchRequestFinished(source, isLoading, !noMangasFound, !searchString);
}, [isLoading, noMangasFound, searchString]);
let errorMessage: string | undefined;
if (error) {
errorMessage = t('search.error.label.source_search_failed');
} else if (noMangasFound) {
errorMessage = t('manga.error.label.no_mangas_found');
}
2023-05-20 13:23:30 +02:00
useEffect(
() => () => {
// INFO:
// with strict mode + dev mode the first request will be aborted. due to using SWR there won't be an
// immediate second request since it's the same key. instead the "second" request will be the error handling of SWR
abortRequest(
new Error(`SourceSearchPreview(${source.id}, ${source.displayName}): search string changed`),
);
},
[searchString],
);
2023-05-20 13:23:30 +02:00
if ((!isLoading && !searchString) || emptyQuery) {
return null;
}
return (
<>
<Card sx={{ margin: '10px' }}>
<CardActionArea component={Link} to={`/sources/${id}?query=${searchString}`} sx={{ p: 3 }}>
<Typography variant="h5">{displayName}</Typography>
<Typography variant="caption">{translateExtensionLanguage(lang)}</Typography>
</CardActionArea>
</Card>
<MangaGrid
mangas={mangas}
isLoading={isLoading}
hasNextPage={false}
Feature/virtualize manga grid (#363) * Disable ssr by default for "useMediaQuery" SSR would cause the hook to run once with default values and only after the first render with real values. This can cause issue on rendering when depending on useMediaQuery results like in 8c129f2e08e8c807b57c7eef802556faa2edcf1b * Virtualize manga grids * Remove SourceMangas load more guard Was required due to the previous load more trigger logic from the MangaGrid. Due to using Virtuoso now, load more will be triggered only once when the bottom of the grid was reached and thus won't trigger multiple load more requests * Remove old Library pagination Pagination is handled by virtuoso, thus, the previous pagination can be removed * Increase initial loaded pages to make infinite load work virtuoso requires enough initial items to be rendered, so that actual virtualization takes effect, for it to fire "endReached" * Prevent virtuoso grid scrollbar from jumping around In case the items have a big height difference there is a bug where the scrollbar starts jumping around the moment these new items are rendered * Restore scroll position For some reason the UI jumps around when accessing "document.documentElement" during loading more items. After the items are rendered the loading placeholder gets removed and the previous items jump to the bottom of the viewport. * Limit manga grid titles to two lines * Remove "last page" info from MangaGrid Info is not needed. The only thing the MangaGrid has to do is to trigger a request to load more data
2023-06-17 16:50:17 +02:00
loadMore={() => undefined}
horizontal
noFaces
message={errorMessage}
inLibraryIndicator
/>
</>
);
},
);
const SearchAll: React.FC = () => {
const { t } = useTranslation();
const { setTitle, setAction } = useContext(NavbarContext);
const [query] = useQueryParam('query', StringParam);
const searchString = useDebounce(query, TRIGGER_SEARCH_THRESHOLD);
const [shownLangs, setShownLangs] = useLocalStorage<string[]>('shownSourceLangs', sourceDefualtLangs());
const [showNsfw] = useLocalStorage<boolean>('showNsfw', true);
2023-05-20 13:23:30 +02:00
const { data: sources = [] } = requestManager.useGetSourceList();
const [sourceToLoadingStateMap, setSourceToLoadingStateMap] = useState<SourceToLoadingStateMap>(new Map());
const debouncedSourceToLoadingStateMap = useDebounce(sourceToLoadingStateMap, 500);
2023-05-20 13:23:30 +02:00
const sourcesSortedByName = useMemo(() => [...sources].sort(compareSourceByName), [sources]);
const sourcesFilteredByLang = useMemo(
() => sourcesSortedByName.filter((source) => shownLangs.includes(source.lang)),
[sourcesSortedByName, shownLangs],
);
const sourcesFilteredByNsfw = useMemo(
() => sourcesFilteredByLang.filter((source) => showNsfw || !source.isNsfw),
[sourcesFilteredByLang, showNsfw],
);
const sourcesSortedByResult = useMemo(
() =>
[...sourcesFilteredByNsfw].sort((sourceA, sourceB) =>
compareSourcesBySearchResult(sourceA, sourceB, debouncedSourceToLoadingStateMap),
2023-05-20 13:23:30 +02:00
),
[sourcesFilteredByNsfw, debouncedSourceToLoadingStateMap],
2023-05-20 13:23:30 +02:00
);
const updateSourceLoadingState = useCallback(
({ id }: ISource, isLoading: boolean, hasResults: boolean, emptySearch: boolean) => {
setSourceToLoadingStateMap((currentMap) => {
const mapCopy = new Map(currentMap);
mapCopy.set(id, { isLoading, hasResults, emptySearch });
return mapCopy;
});
},
[setSourceToLoadingStateMap],
2023-05-20 13:23:30 +02:00
);
useEffect(() => {
setTitle(t('search.title.global_search'));
setAction(
<>
<AppbarSearch autoOpen />
<LangSelect
shownLangs={shownLangs}
setShownLangs={setShownLangs}
2023-05-20 13:23:30 +02:00
allLangs={sourceToLangList(sources)}
forcedLangs={sourceForcedDefaultLangs()}
/>
</>,
);
2023-05-20 13:23:30 +02:00
}, [t, shownLangs, setShownLangs, sources]);
2023-05-20 13:23:30 +02:00
useEffect(() => {
// make sure all of forcedDefaultLangs() exists in shownLangs
const missingDefaultLangs = sourceForcedDefaultLangs().filter(
(defaultLang) => !shownLangs.includes(defaultLang),
);
2023-05-20 13:23:30 +02:00
setShownLangs([...shownLangs, ...missingDefaultLangs]);
}, []);
2023-05-20 13:23:30 +02:00
return (
<>
{sourcesSortedByResult.map((source) => (
<SourceSearchPreview
key={source.id}
source={source}
onSearchRequestFinished={updateSourceLoadingState}
searchString={searchString}
emptyQuery={!query}
2023-05-20 13:23:30 +02:00
/>
))}
</>
);
};
export default SearchAll;