Feature/swr for library screens (#186)

* Wrap data fetching in library and manga screen with swr for better dev and user experience. Refactor some API calls and data handling. Add manual refresh to manga detail.

* Fix manga card layout

* Fix refresh button position on small screens

* Revert "Fix manga card layout"

This reverts commit d85da3d8385e1ef64feed1789e4cd4591c8bd563.

* Fix manga not setting title

* Move chapters loading to Manga component, join data fetching, add auto online fetch if fetched data is old

* Revert some changes
This commit is contained in:
Valter Martinek
2022-11-02 10:42:02 +01:00
committed by GitHub
parent 14a9ffa558
commit 6f8755fa05
12 changed files with 345 additions and 319 deletions

View File

@@ -22,6 +22,7 @@
"react-router-dom": "^5.2.0", "react-router-dom": "^5.2.0",
"react-scripts": "4.0.3", "react-scripts": "4.0.3",
"react-virtuoso": "^1.8.6", "react-virtuoso": "^1.8.6",
"swr": "^1.3.0",
"use-query-params": "^1.2.3", "use-query-params": "^1.2.3",
"web-vitals": "^2.1.0" "web-vitals": "^2.1.0"
}, },

View File

@@ -21,6 +21,8 @@ import {
Theme, Theme,
StyledEngineProvider, StyledEngineProvider,
} from '@mui/material/styles'; } from '@mui/material/styles';
import { SWRConfig } from 'swr';
import { fetcher } from 'util/client';
import DefaultNavBar from 'components/navbar/DefaultNavBar'; import DefaultNavBar from 'components/navbar/DefaultNavBar';
import DarkTheme from 'components/context/DarkTheme'; import DarkTheme from 'components/context/DarkTheme';
import useLocalStorage from 'util/useLocalStorage'; import useLocalStorage from 'util/useLocalStorage';
@@ -83,111 +85,114 @@ export default function App() {
); );
return ( return (
<Router> <SWRConfig value={{ fetcher }}>
<StyledEngineProvider injectFirst> <Router>
<ThemeProvider theme={theme}> <StyledEngineProvider injectFirst>
<QueryParamProvider ReactRouterRoute={Route}> <ThemeProvider theme={theme}>
<LibraryOptionsContextProvider> <QueryParamProvider ReactRouterRoute={Route}>
<NavBarContextProvider> <LibraryOptionsContextProvider>
<CssBaseline /> <NavBarContextProvider>
<DefaultNavBar /> <CssBaseline />
<Container <DefaultNavBar />
id="appMainContainer" <Container
maxWidth={false} id="appMainContainer"
disableGutters maxWidth={false}
sx={{ disableGutters
mt: 8, sx={{
ml: { sm: 8 }, mt: 8,
mb: { xs: 8, sm: 0 }, ml: { sm: 8 },
width: 'auto', mb: { xs: 8, sm: 0 },
overflow: 'auto', width: 'auto',
}} overflow: 'auto',
> }}
>
<Switch>
{/* General Routes */}
<Route
exact
path="/"
render={() => (
<Redirect to="/library" />
)}
/>
<Route path="/settings/about">
<About />
</Route>
<Route path="/settings/categories">
<Categories />
</Route>
<Route path="/settings/backup">
<Backup />
</Route>
<Route path="/settings">
<DarkTheme.Provider
value={darkThemeContext}
>
<Settings />
</DarkTheme.Provider>
</Route>
{/* Manga Routes */}
<Route path="/sources/:sourceId/popular/">
<SourceMangas popular />
</Route>
<Route path="/sources/:sourceId/latest/">
<SourceMangas popular={false} />
</Route>
<Route path="/sources/:sourceId/configure/">
<SourceConfigure />
</Route>
<Route path="/sources/all/search/">
<SearchAll />
</Route>
<Route path="/downloads">
<DownloadQueue />
</Route>
<Route path="/manga/:mangaId/chapter/:chapterNum">
<></>
</Route>
<Route path="/manga/:id">
<Manga />
</Route>
<Route path="/library">
<Library />
</Route>
<Route path="/updates">
<Updates />
</Route>
<Route path="/sources">
<Sources />
</Route>
<Route path="/extensions">
<Extensions />
</Route>
<Route path="/browse">
<Browse />
</Route>
</Switch>
</Container>
<Switch> <Switch>
{/* General Routes */}
<Route <Route
exact path="/manga/:mangaId/chapter/:chapterIndex"
path="/" // passing a key re-mounts the reader
render={() => ( // when changing chapters
<Redirect to="/library" /> render={(props: any) => (
<Reader
key={
props.match.params
.chapterIndex
}
/>
)} )}
/> />
<Route path="/settings/about">
<About />
</Route>
<Route path="/settings/categories">
<Categories />
</Route>
<Route path="/settings/backup">
<Backup />
</Route>
<Route path="/settings">
<DarkTheme.Provider
value={darkThemeContext}
>
<Settings />
</DarkTheme.Provider>
</Route>
{/* Manga Routes */}
<Route path="/sources/:sourceId/popular/">
<SourceMangas popular />
</Route>
<Route path="/sources/:sourceId/latest/">
<SourceMangas popular={false} />
</Route>
<Route path="/sources/:sourceId/configure/">
<SourceConfigure />
</Route>
<Route path="/sources/all/search/">
<SearchAll />
</Route>
<Route path="/downloads">
<DownloadQueue />
</Route>
<Route path="/manga/:mangaId/chapter/:chapterNum">
<></>
</Route>
<Route path="/manga/:id">
<Manga />
</Route>
<Route path="/library">
<Library />
</Route>
<Route path="/updates">
<Updates />
</Route>
<Route path="/sources">
<Sources />
</Route>
<Route path="/extensions">
<Extensions />
</Route>
<Route path="/browse">
<Browse />
</Route>
</Switch> </Switch>
</Container> </NavBarContextProvider>
<Switch> </LibraryOptionsContextProvider>
<Route </QueryParamProvider>
path="/manga/:mangaId/chapter/:chapterIndex" </ThemeProvider>
// passing a key re-mounts the reader when changing chapters </StyledEngineProvider>
render={(props: any) => ( </Router>
<Reader </SWRConfig>
key={
props.match.params
.chapterIndex
}
/>
)}
/>
</Switch>
</NavBarContextProvider>
</LibraryOptionsContextProvider>
</QueryParamProvider>
</ThemeProvider>
</StyledEngineProvider>
</Router>
); );
} }

View File

@@ -16,7 +16,9 @@ import React, { useContext, useEffect, useState } from 'react';
import NavbarContext from 'components/context/NavbarContext'; import NavbarContext from 'components/context/NavbarContext';
import client from 'util/client'; import client from 'util/client';
import useLocalStorage from 'util/useLocalStorage'; import useLocalStorage from 'util/useLocalStorage';
import Refresh from '@mui/icons-material/Refresh';
import CategorySelect from './navbar/action/CategorySelect'; import CategorySelect from './navbar/action/CategorySelect';
import LoadingIconButton from './atoms/LoadingIconButton';
const useStyles = (inLibrary: string) => makeStyles((theme: Theme) => ({ const useStyles = (inLibrary: string) => makeStyles((theme: Theme) => ({
root: { root: {
@@ -118,6 +120,8 @@ const useStyles = (inLibrary: string) => makeStyles((theme: Theme) => ({
interface IProps{ interface IProps{
manga: IManga manga: IManga
onRefresh: () => Promise<any>
refreshing: boolean
} }
function getSourceName(source: ISource) { function getSourceName(source: ISource) {
@@ -131,11 +135,9 @@ function getValueOrUnknown(val: string) {
return val || 'UNKNOWN'; return val || 'UNKNOWN';
} }
export default function MangaDetails(props: IProps) { export default function MangaDetails({ manga, onRefresh, refreshing }: IProps) {
const { setAction } = useContext(NavbarContext); const { setAction } = useContext(NavbarContext);
const { manga } = props;
const [inLibrary, setInLibrary] = useState<string>( const [inLibrary, setInLibrary] = useState<string>(
manga.inLibrary ? 'In Library' : 'Add To Library', manga.inLibrary ? 'In Library' : 'Add To Library',
); );
@@ -143,28 +145,32 @@ export default function MangaDetails(props: IProps) {
const [categoryDialogOpen, setCategoryDialogOpen] = useState<boolean>(false); const [categoryDialogOpen, setCategoryDialogOpen] = useState<boolean>(false);
useEffect(() => { useEffect(() => {
if (inLibrary === 'In Library') { setAction(
setAction( <>
<> <LoadingIconButton loading={refreshing} onClick={onRefresh}>
<IconButton <Refresh />
onClick={() => setCategoryDialogOpen(true)} </LoadingIconButton>
aria-label="display more actions" {inLibrary === 'In Library' && (
edge="end" <>
color="inherit" <IconButton
size="large" onClick={() => setCategoryDialogOpen(true)}
> aria-label="display more actions"
<FilterListIcon /> edge="end"
</IconButton> color="inherit"
<CategorySelect size="large"
open={categoryDialogOpen} >
setOpen={setCategoryDialogOpen} <FilterListIcon />
mangaId={manga.id} </IconButton>
/> <CategorySelect
</>, open={categoryDialogOpen}
setOpen={setCategoryDialogOpen}
); mangaId={manga.id}
} else { setAction(<></>); } />
}, [inLibrary, categoryDialogOpen]); </>
)}
</>,
);
}, [inLibrary, categoryDialogOpen, refreshing, onRefresh]);
const [serverAddress] = useLocalStorage<String>('serverBaseURL', ''); const [serverAddress] = useLocalStorage<String>('serverBaseURL', '');
const [useCache] = useLocalStorage<boolean>('useCache', true); const [useCache] = useLocalStorage<boolean>('useCache', true);

View File

@@ -0,0 +1,32 @@
import { CircularProgress, IconButton, IconButtonProps } from '@mui/material';
import React, { useState } from 'react';
interface IProps extends Omit<IconButtonProps, 'onClick'> {
loading?: boolean
onClick: (e: React.MouseEvent<HTMLButtonElement, MouseEvent>) => Promise<any>
}
const LoadingIconButton = ({
onClick, children, loading: iLoading, ...rest
}: IProps) => {
const [sLoading, setLoading] = useState(false);
const loading = sLoading || iLoading;
const handleClick = (e: React.MouseEvent<HTMLButtonElement, MouseEvent>) => {
setLoading(true);
onClick(e).finally(() => setLoading(false));
};
return (
// eslint-disable-next-line react/jsx-props-no-spreading
<IconButton disabled={loading} {...rest} onClick={handleClick}>
{loading ? (<CircularProgress size={24} />) : children}
</IconButton>
);
};
LoadingIconButton.defaultProps = {
loading: false,
};
export default LoadingIconButton;

View File

@@ -5,7 +5,9 @@
* License, v. 2.0. If a copy of the MPL was not distributed with this * 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/. */ * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
import React, { useState, useEffect, useCallback } from 'react'; import React, {
useState, useEffect, useCallback, useMemo,
} from 'react';
import { Box, styled } from '@mui/system'; import { Box, styled } from '@mui/system';
import { Virtuoso } from 'react-virtuoso'; import { Virtuoso } from 'react-virtuoso';
import Typography from '@mui/material/Typography'; import Typography from '@mui/material/Typography';
@@ -19,7 +21,7 @@ import {
filterAndSortChapters, filterAndSortChapters,
} from 'components/chapter/util'; } from 'components/chapter/util';
import ResumeFab from 'components/chapter/ResumeFAB'; import ResumeFab from 'components/chapter/ResumeFAB';
import useFetchChapters from './useFetchChapters'; import useSubscription from 'components/library/useSubscription';
const CustomVirtuoso = styled(Virtuoso)(({ theme }) => ({ const CustomVirtuoso = styled(Virtuoso)(({ theme }) => ({
listStyle: 'none', listStyle: 'none',
@@ -33,20 +35,16 @@ const CustomVirtuoso = styled(Virtuoso)(({ theme }) => ({
}, },
})); }));
const baseWebsocketUrl = JSON.parse(window.localStorage.getItem('serverBaseURL')!).replace('http', 'ws');
const initialQueue = {
status: 'Stopped',
queue: [],
} as IQueue;
interface IProps { interface IProps {
id: string id: string
chaptersData: IChapter[] | undefined
onRefresh: () => void;
} }
export default function ChapterList(props: IProps) { export default function ChapterList({ id, chaptersData, onRefresh }: IProps) {
const { id } = props; const noChaptersFound = chaptersData?.length === 0;
const chapters = useMemo(() => chaptersData ?? [], [chaptersData]);
const [chapters, triggerChaptersUpdate, noChaptersFound] = useFetchChapters(id);
const [firstUnreadChapter, setFirstUnreadChapter] = useState<IChapter>(); const [firstUnreadChapter, setFirstUnreadChapter] = useState<IChapter>();
const [filteredChapters, setFilteredChapters] = useState<IChapter[]>([]); const [filteredChapters, setFilteredChapters] = useState<IChapter[]>([]);
// eslint-disable-next-line max-len // eslint-disable-next-line max-len
@@ -54,31 +52,14 @@ export default function ChapterList(props: IProps) {
chapterOptionsReducer, `${id}filterOptions`, defaultChapterOptions, chapterOptionsReducer, `${id}filterOptions`, defaultChapterOptions,
); );
const [, setWsClient] = useState<WebSocket>(); const queue = useSubscription<IQueue>('/api/v1/downloads').data?.queue;
const [{ queue }, setQueueState] = useState<IQueue>(initialQueue);
useEffect(() => {
const wsc = new WebSocket(`${baseWebsocketUrl}/api/v1/downloads`);
wsc.onmessage = (e) => {
const data = JSON.parse(e.data) as IQueue;
setQueueState(data);
};
setWsClient(wsc);
return () => wsc.close();
}, []);
useEffect(() => {
triggerChaptersUpdate();
}, [queue.length]);
const downloadStatusStringFor = useCallback((chapter: IChapter) => { const downloadStatusStringFor = useCallback((chapter: IChapter) => {
let rtn = ''; let rtn = '';
if (chapter.downloaded) { if (chapter.downloaded) {
rtn = ' • Downloaded'; rtn = ' • Downloaded';
} }
queue.forEach((q) => { queue?.forEach((q) => {
if (chapter.index === q.chapterIndex && chapter.mangaId === q.mangaId) { if (chapter.index === q.chapterIndex && chapter.mangaId === q.mangaId) {
rtn = ` • Downloading (${(q.progress * 100).toFixed(2)}%)`; rtn = ` • Downloading (${(q.progress * 100).toFixed(2)}%)`;
} }
@@ -136,7 +117,7 @@ export default function ChapterList(props: IProps) {
showChapterNumber={options.showChapterNumber} showChapterNumber={options.showChapterNumber}
chapter={filteredChapters[index]} chapter={filteredChapters[index]}
downloadStatusString={downloadStatusStringFor(filteredChapters[index])} downloadStatusString={downloadStatusStringFor(filteredChapters[index])}
triggerChaptersUpdate={triggerChaptersUpdate} triggerChaptersUpdate={onRefresh}
/> />
)} )}
useWindowScroll={window.innerWidth < 900} useWindowScroll={window.innerWidth < 900}

View File

@@ -1,39 +0,0 @@
/*
* 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 { useState, useCallback, useEffect } from 'react';
import client from 'util/client';
export default function useChaptersFetch(id: string): [IChapter[], () => void, boolean] {
const [chapters, setChapters] = useState<IChapter[]>([]);
const [noChaptersFound, setNoChaptersFound] = useState(false);
const [chapterUpdateTriggerer, setChapterUpdateTriggerer] = useState(0);
const [fetchedOnline, setFetchedOnline] = useState(false);
const [fetchedOffline, setFetchedOffline] = useState(false);
const triggerChaptersUpdate = useCallback(() => setChapterUpdateTriggerer((prev) => prev + 1),
[]);
useEffect(() => {
const shouldFetchOnline = fetchedOffline && !fetchedOnline;
client.get(`/api/v1/manga/${id}/chapters?onlineFetch=${shouldFetchOnline}`)
.then((response) => response.data)
.then((data) => {
if (data.length === 0 && fetchedOffline) {
setNoChaptersFound(true);
}
setChapters(data);
})
.then(() => {
if (shouldFetchOnline) {
setFetchedOnline(true);
} else setFetchedOffline(true);
});
}, [fetchedOnline, fetchedOffline, chapterUpdateTriggerer]);
return [chapters, triggerChaptersUpdate, noChaptersFound];
}

View File

@@ -0,0 +1,30 @@
import { useEffect, useState } from 'react';
const baseWebsocketUrl = JSON.parse(window.localStorage.getItem('serverBaseURL')!).replace('http', 'ws');
const useSubscription = <T>(path: string, callback?: (newValue: T) => boolean | void) => {
const [state, setState] = useState<T | undefined>();
useEffect(() => {
const wsc = new WebSocket(`${baseWebsocketUrl}${path}`);
wsc.onmessage = (e) => {
const data = JSON.parse(e.data) as T;
if (callback) {
// If callback is specified, only update state if callback returns true
// This is so that useSubscription can be used without causing rerender
if (callback(data) === true) {
setState(data);
}
} else {
setState(data);
}
};
return () => wsc.close();
}, [path]);
return { data: state };
};
export default useSubscription;

View File

@@ -6,10 +6,10 @@
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */ * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
import { Tab, Tabs } from '@mui/material'; import { Tab, Tabs } from '@mui/material';
import React, { useContext, useEffect, useState } from 'react'; import React, {
useContext, useEffect, useState,
} from 'react';
import NavbarContext from 'components/context/NavbarContext'; import NavbarContext from 'components/context/NavbarContext';
import client from 'util/client';
import cloneObject from 'util/cloneObject';
import EmptyView from 'components/util/EmptyView'; import EmptyView from 'components/util/EmptyView';
import LoadingPlaceholder from 'components/util/LoadingPlaceholder'; import LoadingPlaceholder from 'components/util/LoadingPlaceholder';
import TabPanel from 'components/util/TabPanel'; import TabPanel from 'components/util/TabPanel';
@@ -17,18 +17,25 @@ import LibraryOptions from 'components/library/LibraryOptions';
import LibraryMangaGrid from 'components/library/LibraryMangaGrid'; import LibraryMangaGrid from 'components/library/LibraryMangaGrid';
import AppbarSearch from 'components/util/AppbarSearch'; import AppbarSearch from 'components/util/AppbarSearch';
import { useQueryParam, NumberParam } from 'use-query-params'; import { useQueryParam, NumberParam } from 'use-query-params';
import useSWR from 'swr';
import UpdateChecker from '../components/library/UpdateChecker'; import UpdateChecker from '../components/library/UpdateChecker';
interface IMangaCategory {
category: ICategory
mangas: IManga[]
isFetched: boolean
}
export default function Library() { export default function Library() {
const { data: tabsData, error: tabsError } = useSWR<ICategory[]>('/api/v1/category');
const tabs = tabsData ?? [];
const [tabSearchParam, setTabSearchParam] = useQueryParam('tab', NumberParam);
const activeTab = tabs.find((t) => t.order === tabSearchParam) ?? tabs[0];
const { data: mangaData, error: mangaError } = useSWR<IManga[]>(`/api/v1/category/${activeTab?.id}`, {
isPaused: () => activeTab == null,
});
const mangas = mangaData ?? [];
const { setTitle, setAction } = useContext(NavbarContext); const { setTitle, setAction } = useContext(NavbarContext);
useEffect(() => { useEffect(() => {
setTitle('Library'); setAction( setTitle('Library');
setAction(
<> <>
<AppbarSearch /> <AppbarSearch />
<LibraryOptions /> <LibraryOptions />
@@ -37,64 +44,19 @@ export default function Library() {
); );
}, []); }, []);
const [tabs, setTabs] = useState<IMangaCategory[]>();
const [tabNum, setTabNum] = useState<number>(0);
const [tabSearchParam, setTabSearchParam] = useQueryParam('tab', NumberParam);
// a hack so MangaGrid doesn't stop working. I won't change it in case // a hack so MangaGrid doesn't stop working. I won't change it in case
// if I do manga pagination for library.. // if I do manga pagination for library..
const [lastPageNum, setLastPageNum] = useState<number>(1); const [lastPageNum, setLastPageNum] = useState<number>(1);
const handleTabChange = (newTab: number) => { const handleTabChange = (newTab: number) => {
setTabNum(newTab); setTabSearchParam(newTab === 0 ? undefined : newTab);
setTabSearchParam(newTab);
}; };
useEffect(() => { if (tabsError != null) {
client.get('/api/v1/category') return <EmptyView message="Could not load categories" messageExtra={tabsError?.message ?? tabsError} />;
.then((response) => response.data) }
.then((categories: ICategory[]) => {
const categoryTabs = categories.map((category) => ({
category,
mangas: [] as IManga[],
isFetched: false,
}));
setTabs(categoryTabs);
if (categoryTabs.length > 0) {
if (
tabSearchParam !== undefined
&& tabSearchParam !== null
&& !Number.isNaN(tabSearchParam)
&& categories.some((category) => category.order === Number(tabSearchParam))
) {
handleTabChange(Number(tabSearchParam!));
} else { handleTabChange(categoryTabs[0].category.order); }
}
});
}, []);
// fetch the current tab if (tabsData == null) {
useEffect(() => {
if (tabs !== undefined) {
tabs.forEach((tab, index) => {
if (tab.category.order === tabNum && !tab.isFetched) {
// eslint-disable-next-line @typescript-eslint/no-shadow
client.get(`/api/v1/category/${tab.category.id}`)
.then((response) => response.data)
.then((data: IManga[]) => {
const tabsClone = cloneObject(tabs);
tabsClone[index].mangas = data;
tabsClone[index].isFetched = true;
setTabs(tabsClone);
});
}
});
}
}, [tabs?.length, tabNum]);
if (tabs === undefined) {
return <LoadingPlaceholder />; return <LoadingPlaceholder />;
} }
@@ -102,57 +64,57 @@ export default function Library() {
return <EmptyView message="Your Library is empty" />; return <EmptyView message="Your Library is empty" />;
} }
let toRender; if (tabs.length === 1) {
if (tabs.length > 1) { return (
// eslint-disable-next-line max-len
const tabDefines = tabs.map((tab) => (<Tab label={tab.category.name} value={tab.category.order} />));
const tabBodies = tabs.map((tab) => (
<TabPanel index={tab.category.order} currentIndex={tabNum}>
<LibraryMangaGrid
mangas={tab.mangas}
hasNextPage={false}
lastPageNum={lastPageNum}
setLastPageNum={setLastPageNum}
message="Category is Empty"
isLoading={!tab.isFetched}
/>
</TabPanel>
));
// Visual Hack: 160px is min-width for viewport width of >600
const scrollableTabs = window.innerWidth < tabs.length * 160;
toRender = (
<>
<Tabs
key={tabNum}
value={tabNum}
onChange={(e, newTab) => handleTabChange(newTab)}
indicatorColor="primary"
textColor="primary"
centered={!scrollableTabs}
variant={scrollableTabs ? 'scrollable' : 'fullWidth'}
scrollButtons
allowScrollButtonsMobile
>
{tabDefines}
</Tabs>
{tabBodies}
</>
);
} else {
const mangas = tabs.length === 1 ? tabs[0].mangas : [];
toRender = (
<LibraryMangaGrid <LibraryMangaGrid
mangas={mangas} mangas={mangas}
hasNextPage={false} hasNextPage={false}
lastPageNum={lastPageNum} lastPageNum={lastPageNum}
setLastPageNum={setLastPageNum} setLastPageNum={setLastPageNum}
message="Your Library is empty" message="Your Library is empty"
isLoading={!tabs[0].isFetched} isLoading={activeTab != null && mangaData == null && mangaError == null}
/> />
); );
} }
return toRender; // Visual Hack: 160px is min-width for viewport width of >600
const scrollableTabs = window.innerWidth < tabs.length * 160;
return (
<>
<Tabs
key={activeTab.order}
value={activeTab.order}
onChange={(e, newTab) => handleTabChange(newTab)}
indicatorColor="primary"
textColor="primary"
centered={!scrollableTabs}
variant={scrollableTabs ? 'scrollable' : 'fullWidth'}
scrollButtons
allowScrollButtonsMobile
>
{tabs.map((tab) => (
<Tab key={tab.id} label={tab.name} value={tab.order} />
))}
</Tabs>
{tabs.map((tab) => (
<TabPanel key={tab.order} index={tab.order} currentIndex={activeTab.order}>
{tab === activeTab && (mangaError
? (
<EmptyView message="Could not load manga" messageExtra={mangaError?.message ?? mangaError} />
)
: (
<LibraryMangaGrid
mangas={mangas}
hasNextPage={false}
lastPageNum={lastPageNum}
setLastPageNum={setLastPageNum}
message="Category is Empty"
isLoading={mangaData == null}
/>
))}
</TabPanel>
))}
</>
);
} }

View File

@@ -5,43 +5,70 @@
* License, v. 2.0. If a copy of the MPL was not distributed with this * 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/. */ * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
import React, { useEffect, useState, useContext } from 'react'; import React, {
useCallback, useEffect, useContext, useState, useRef,
} from 'react';
import useSWR from 'swr';
import { Box } from '@mui/system'; import { Box } from '@mui/system';
import MangaDetails from 'components/MangaDetails'; import MangaDetails from 'components/MangaDetails';
import NavbarContext from 'components/context/NavbarContext'; import NavbarContext from 'components/context/NavbarContext';
import client from 'util/client'; import { fetcher } from 'util/client';
import LoadingPlaceholder from 'components/util/LoadingPlaceholder'; import LoadingPlaceholder from 'components/util/LoadingPlaceholder';
import ChapterList from 'components/chapter/ChapterList'; import ChapterList from 'components/chapter/ChapterList';
import { useParams } from 'react-router-dom'; import { useParams } from 'react-router-dom';
const AUTOFETCH_AGE = 60 * 60 * 24; // 24 hours
export default function Manga() { export default function Manga() {
const { setTitle } = useContext(NavbarContext); const { setTitle } = useContext(NavbarContext);
useEffect(() => { setTitle('Manga'); }, []); // delegate setting topbar action to MangaDetails
const { id } = useParams<{ id: string }>(); const { id } = useParams<{ id: string }>();
const autofetchedRef = useRef(false);
const [manga, setManga] = useState<IManga>(); const { data: manga, error, mutate: mutateManga } = useSWR<IManga>(`/api/v1/manga/${id}/?onlineFetch=false`);
const { data: chaptersData, mutate: mutateChapters } = useSWR<IChapter[]>(`/api/v1/manga/${id}/chapters?onlineFetch=false`);
const [fetchingOnline, setFetchingOnline] = useState(false);
const fetchOnline = useCallback(async () => {
setFetchingOnline(true);
await Promise.all([
fetcher(`/api/v1/manga/${id}/?onlineFetch=true`)
.then((res) => mutateManga(res, { revalidate: false })),
fetcher(`/api/v1/manga/${id}/chapters?onlineFetch=true`)
.then((res) => mutateChapters(res, { revalidate: false })),
]);
setFetchingOnline(false);
}, [mutateManga, mutateChapters, id]);
useEffect(() => { useEffect(() => {
if (manga === undefined || !manga.freshData) { // Automatically fetch manga from source if data is older then 24 hours
client.get(`/api/v1/manga/${id}/?onlineFetch=${manga !== undefined}`) // Automatic fetch is done only once, to prevent issues when server does
.then((response) => response.data) // not update age for some reason (ie. error on source side)
.then((data: IManga) => { if (manga == null) return;
setManga(data); if (
setTitle(data.title); manga.inLibrary
}); && (manga.age > AUTOFETCH_AGE || manga.chaptersAge > AUTOFETCH_AGE)
&& autofetchedRef.current === false
) {
autofetchedRef.current = true;
fetchOnline();
} }
}, [manga]); }, [manga]);
useEffect(() => {
setTitle(manga?.title ?? 'Manga');
}, [manga?.title]);
return ( return (
<Box sx={{ display: { md: 'flex' }, overflow: 'hidden' }}> <Box sx={{ display: { md: 'flex' }, overflow: 'hidden' }}>
<LoadingPlaceholder {!manga && !error && <LoadingPlaceholder />}
shouldRender={manga !== undefined} {manga && (
component={MangaDetails} <MangaDetails
componentProps={{ manga }} refreshing={fetchingOnline}
/> manga={manga}
onRefresh={fetchOnline}
<ChapterList id={id} /> />
)}
<ChapterList id={id} chaptersData={chaptersData} onRefresh={() => mutateChapters()} />
</Box> </Box>
); );
} }

3
src/typings.d.ts vendored
View File

@@ -85,6 +85,9 @@ interface IManga {
freshData: boolean freshData: boolean
unreadCount?: number unreadCount?: number
downloadCount?: number downloadCount?: number
age: number
chaptersAge: number
} }
interface IChapter { interface IChapter {

View File

@@ -14,9 +14,11 @@ const { hostname, port, protocol } = window.location;
let inferredPort; let inferredPort;
if (port === '3000') { inferredPort = '4567'; } else { inferredPort = port; } if (port === '3000') { inferredPort = '4567'; } else { inferredPort = port; }
const baseURL = storage.getItem('serverBaseURL', `${protocol}//${hostname}:${inferredPort}`);
const client = axios.create({ const client = axios.create({
// baseURL must not have traling slash // baseURL must not have traling slash
baseURL: storage.getItem('serverBaseURL', `${protocol}//${hostname}:${inferredPort}`), baseURL,
}); });
client.interceptors.request.use((config) => { client.interceptors.request.use((config) => {
@@ -27,3 +29,14 @@ client.interceptors.request.use((config) => {
}); });
export default client; export default client;
export async function fetcher<T = any>(path: string) {
const res = await client.get(path);
if (res.status !== 200) {
throw new Error(res.statusText);
}
if (res.headers['content-type'] !== 'application/json') {
throw new Error('Response is not json');
}
return res.data as T;
}

View File

@@ -11006,6 +11006,11 @@ svgo@^1.0.0, svgo@^1.2.2:
unquote "~1.1.1" unquote "~1.1.1"
util.promisify "~1.0.0" util.promisify "~1.0.0"
swr@^1.3.0:
version "1.3.0"
resolved "https://registry.yarnpkg.com/swr/-/swr-1.3.0.tgz#c6531866a35b4db37b38b72c45a63171faf9f4e8"
integrity sha512-dkghQrOl2ORX9HYrMDtPa7LTVHJjCTeZoB1dqTbnnEDlSvN8JEKpYIYurDfvbQFUUS8Cg8PceFVZNkW0KNNYPw==
symbol-tree@^3.2.4: symbol-tree@^3.2.4:
version "3.2.4" version "3.2.4"
resolved "https://registry.yarnpkg.com/symbol-tree/-/symbol-tree-3.2.4.tgz#430637d248ba77e078883951fb9aa0eed7c63fa2" resolved "https://registry.yarnpkg.com/symbol-tree/-/symbol-tree-3.2.4.tgz#430637d248ba77e078883951fb9aa0eed7c63fa2"