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

@@ -16,7 +16,9 @@ import React, { useContext, useEffect, useState } from 'react';
import NavbarContext from 'components/context/NavbarContext';
import client from 'util/client';
import useLocalStorage from 'util/useLocalStorage';
import Refresh from '@mui/icons-material/Refresh';
import CategorySelect from './navbar/action/CategorySelect';
import LoadingIconButton from './atoms/LoadingIconButton';
const useStyles = (inLibrary: string) => makeStyles((theme: Theme) => ({
root: {
@@ -118,6 +120,8 @@ const useStyles = (inLibrary: string) => makeStyles((theme: Theme) => ({
interface IProps{
manga: IManga
onRefresh: () => Promise<any>
refreshing: boolean
}
function getSourceName(source: ISource) {
@@ -131,11 +135,9 @@ function getValueOrUnknown(val: string) {
return val || 'UNKNOWN';
}
export default function MangaDetails(props: IProps) {
export default function MangaDetails({ manga, onRefresh, refreshing }: IProps) {
const { setAction } = useContext(NavbarContext);
const { manga } = props;
const [inLibrary, setInLibrary] = useState<string>(
manga.inLibrary ? 'In Library' : 'Add To Library',
);
@@ -143,28 +145,32 @@ export default function MangaDetails(props: IProps) {
const [categoryDialogOpen, setCategoryDialogOpen] = useState<boolean>(false);
useEffect(() => {
if (inLibrary === 'In Library') {
setAction(
<>
<IconButton
onClick={() => setCategoryDialogOpen(true)}
aria-label="display more actions"
edge="end"
color="inherit"
size="large"
>
<FilterListIcon />
</IconButton>
<CategorySelect
open={categoryDialogOpen}
setOpen={setCategoryDialogOpen}
mangaId={manga.id}
/>
</>,
);
} else { setAction(<></>); }
}, [inLibrary, categoryDialogOpen]);
setAction(
<>
<LoadingIconButton loading={refreshing} onClick={onRefresh}>
<Refresh />
</LoadingIconButton>
{inLibrary === 'In Library' && (
<>
<IconButton
onClick={() => setCategoryDialogOpen(true)}
aria-label="display more actions"
edge="end"
color="inherit"
size="large"
>
<FilterListIcon />
</IconButton>
<CategorySelect
open={categoryDialogOpen}
setOpen={setCategoryDialogOpen}
mangaId={manga.id}
/>
</>
)}
</>,
);
}, [inLibrary, categoryDialogOpen, refreshing, onRefresh]);
const [serverAddress] = useLocalStorage<String>('serverBaseURL', '');
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
* 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 { Virtuoso } from 'react-virtuoso';
import Typography from '@mui/material/Typography';
@@ -19,7 +21,7 @@ import {
filterAndSortChapters,
} from 'components/chapter/util';
import ResumeFab from 'components/chapter/ResumeFAB';
import useFetchChapters from './useFetchChapters';
import useSubscription from 'components/library/useSubscription';
const CustomVirtuoso = styled(Virtuoso)(({ theme }) => ({
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 {
id: string
chaptersData: IChapter[] | undefined
onRefresh: () => void;
}
export default function ChapterList(props: IProps) {
const { id } = props;
export default function ChapterList({ id, chaptersData, onRefresh }: IProps) {
const noChaptersFound = chaptersData?.length === 0;
const chapters = useMemo(() => chaptersData ?? [], [chaptersData]);
const [chapters, triggerChaptersUpdate, noChaptersFound] = useFetchChapters(id);
const [firstUnreadChapter, setFirstUnreadChapter] = useState<IChapter>();
const [filteredChapters, setFilteredChapters] = useState<IChapter[]>([]);
// eslint-disable-next-line max-len
@@ -54,31 +52,14 @@ export default function ChapterList(props: IProps) {
chapterOptionsReducer, `${id}filterOptions`, defaultChapterOptions,
);
const [, setWsClient] = useState<WebSocket>();
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 queue = useSubscription<IQueue>('/api/v1/downloads').data?.queue;
const downloadStatusStringFor = useCallback((chapter: IChapter) => {
let rtn = '';
if (chapter.downloaded) {
rtn = ' • Downloaded';
}
queue.forEach((q) => {
queue?.forEach((q) => {
if (chapter.index === q.chapterIndex && chapter.mangaId === q.mangaId) {
rtn = ` • Downloading (${(q.progress * 100).toFixed(2)}%)`;
}
@@ -136,7 +117,7 @@ export default function ChapterList(props: IProps) {
showChapterNumber={options.showChapterNumber}
chapter={filteredChapters[index]}
downloadStatusString={downloadStatusStringFor(filteredChapters[index])}
triggerChaptersUpdate={triggerChaptersUpdate}
triggerChaptersUpdate={onRefresh}
/>
)}
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;