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

444 lines
16 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
2021-01-26 23:32:12 +03:30
* 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/.
*/
2021-01-26 23:32:12 +03:30
2021-09-09 17:51:22 +04:30
import CircularProgress from '@mui/material/CircularProgress';
import { useCallback, useContext, useEffect, useMemo, useRef, useState } from 'react';
import { useLocation, useNavigate, useParams } from 'react-router-dom';
import { Box } from '@mui/material';
import { useTranslation } from 'react-i18next';
import { AllowedMetadataValueTypes, ChapterOffset, IReaderSettings, ReaderType, TChapter, TManga } from '@/typings';
2023-10-28 00:32:02 +02:00
import { requestManager } from '@/lib/requests/RequestManager.ts';
import {
checkAndHandleMissingStoredReaderSettings,
getReaderSettingsFor,
useDefaultReaderSettings,
} from '@/util/readerSettings';
import { requestUpdateMangaMetadata } from '@/util/metadata';
2023-10-28 00:32:02 +02:00
import { HorizontalPager } from '@/components/reader/pager/HorizontalPager';
import { PageNumber } from '@/components/reader/PageNumber';
import { PagedPager } from '@/components/reader/pager/PagedPager';
import { DoublePagedPager } from '@/components/reader/pager/DoublePagedPager';
import { VerticalPager } from '@/components/reader/pager/VerticalPager';
import { ReaderNavBar } from '@/components/navbar/ReaderNavBar';
import { makeToast } from '@/components/util/Toast';
import { NavBarContext } from '@/components/context/NavbarContext.tsx';
import { useDebounce } from '@/util/useDebounce.ts';
import { UpdateChapterPatchInput } from '@/lib/graphql/generated/graphql.ts';
import { useMetadataServerSettings } from '@/util/metadataServerSettings.ts';
import { defaultPromiseErrorHandler } from '@/util/defaultPromiseErrorHandler.ts';
import { Chapters } from '@/lib/data/Chapters.ts';
2021-05-15 23:22:37 +04:30
const getReaderComponent = (readerType: ReaderType) => {
switch (readerType) {
case 'ContinuesVertical':
case 'Webtoon':
return VerticalPager;
2021-05-15 23:22:37 +04:30
break;
case 'SingleVertical':
case 'SingleRTL':
case 'SingleLTR':
return PagedPager;
break;
case 'DoubleVertical':
case 'DoubleRTL':
case 'DoubleLTR':
return DoublePagedPager;
2021-05-15 23:22:37 +04:30
break;
case 'ContinuesHorizontalLTR':
case 'ContinuesHorizontalRTL':
return HorizontalPager;
2021-05-15 23:22:37 +04:30
default:
return VerticalPager;
2021-05-15 23:22:37 +04:30
break;
}
};
const range = (n: number) => Array.from({ length: n }, (value, key) => key);
const initialChapter = {
pageCount: -1,
sourceOrder: -1,
chapterCount: 0,
lastPageRead: 0,
name: 'Loading...',
2023-10-15 16:03:08 +02:00
} as unknown as TChapter;
2021-01-22 17:00:33 +03:30
2023-10-28 00:32:02 +02:00
export function Reader() {
const { t } = useTranslation();
const navigate = useNavigate();
const location = useLocation();
2021-03-09 16:44:09 +03:30
const { chapterIndex, mangaId } = useParams<{ chapterIndex: string; mangaId: string }>();
2023-09-08 00:44:01 +02:00
const initialManga = useMemo(
() =>
({
id: +mangaId,
title: '',
thumbnailUrl: '',
genre: [],
inLibraryAt: 0,
lastReadAt: 0,
chapters: { totalCount: 0 },
2023-10-15 16:03:08 +02:00
}) as unknown as TManga,
2023-09-08 00:44:01 +02:00
[mangaId],
);
const { data, loading: isMangaLoading } = requestManager.useGetManga(mangaId);
2023-10-15 16:03:08 +02:00
const loadedChapter = useRef<TChapter | null>(null);
const isChapterLoaded =
Number(mangaId) === loadedChapter.current?.manga.id &&
Number(chapterIndex) === loadedChapter.current?.sourceOrder &&
loadedChapter.current?.pageCount !== -1;
2023-10-15 16:03:08 +02:00
const manga = data?.manga ?? initialManga;
const { data: chapterData, loading: isChapterLoading } = requestManager.useGetMangaChapter(mangaId, chapterIndex);
const arePagesUpdatedRef = useRef(false);
const {
settings: { downloadAheadLimit },
} = useMetadataServerSettings();
const isDownloadAheadEnabled = !!downloadAheadLimit;
const getLoadedChapter = () => {
const isAChapterLoaded = loadedChapter.current;
const isSameAsLoadedChapter = isAChapterLoaded && isChapterLoaded;
if (isSameAsLoadedChapter) {
const didPageCountChange =
chapterData?.chapter && loadedChapter.current?.pageCount !== chapterData.chapter.pageCount;
return didPageCountChange ? chapterData!.chapter : loadedChapter.current;
}
arePagesUpdatedRef.current = false;
if (chapterData?.chapter) {
2023-10-15 16:03:08 +02:00
return chapterData.chapter;
}
return null;
};
loadedChapter.current = getLoadedChapter();
const chapter = loadedChapter.current ?? initialChapter;
const [fetchPages] = requestManager.useGetChapterPagesFetch(chapter.id);
useEffect(() => {
const shouldFetchPages = !isChapterLoading && !chapter.isDownloaded;
if (shouldFetchPages) {
fetchPages().then(() => {
arePagesUpdatedRef.current = true;
});
} else {
arePagesUpdatedRef.current = true;
}
}, [chapter.id]);
const isLoading = isChapterLoading || !arePagesUpdatedRef.current;
const [wasLastPageReadSet, setWasLastPageReadSet] = useState(false);
2021-03-19 14:52:20 +03:30
const [curPage, setCurPage] = useState<number>(0);
const isLastPage = curPage === chapter.pageCount - 1;
const curPageDebounced = useDebounce(curPage, isLastPage ? 0 : 1000);
const [pageToScrollTo, setPageToScrollTo] = useState<number | undefined>(undefined);
2023-10-28 00:32:02 +02:00
const { setOverride, setTitle } = useContext(NavBarContext);
const [retrievingNextChapter, setRetrievingNextChapter] = useState(false);
const { data: mangaChaptersData } = requestManager.useGetMangaChapters(mangaId, { nextFetchPolicy: 'standby' });
const mangaChapters = mangaChaptersData?.chapters.nodes;
const { settings: defaultSettings, loading: areDefaultSettingsLoading } = useDefaultReaderSettings();
const [settings, setSettings] = useState(getReaderSettingsFor(manga, defaultSettings));
const { settings: metadataSettings } = useMetadataServerSettings();
const prevChapters = useMemo(
() =>
Chapters.getNextChapters(chapter, mangaChapters ?? [], {
offset: ChapterOffset.PREV,
skipDupe: settings.skipDupChapters,
}),
[chapter, mangaChapters, settings.skipDupChapters],
);
const nextChapters = useMemo(
() => Chapters.getNextChapters(chapter, mangaChapters ?? [], { skipDupe: settings.skipDupChapters }),
[chapter, mangaChapters, settings.skipDupChapters],
);
const prevChapter = useMemo(
() =>
Chapters.getNextChapter(chapter, mangaChapters ?? [], {
offset: ChapterOffset.PREV,
skipDupe: settings.skipDupChapters,
}),
[chapter, mangaChapters, settings.skipDupChapters],
);
const nextChapter = useMemo(
() =>
Chapters.getNextChapter(chapter, mangaChapters ?? [], {
skipDupe: settings.skipDupChapters,
}),
[chapter, mangaChapters, settings.skipDupChapters],
);
const updateChapter = (patch: UpdateChapterPatchInput) => {
if (chapter === initialChapter) {
return;
}
const getChapterIdToDelete = () => {
const isAutoDeletionEnabled = !!patch.isRead && !!metadataSettings.deleteChaptersWhileReading;
if (!isAutoDeletionEnabled || !mangaChapters) {
return -1;
}
const chapterToDelete = [chapter, ...prevChapters][metadataSettings.deleteChaptersWhileReading - 1];
if (!chapterToDelete) {
return -1;
}
// chapter has to exist in the cache since the reader fetches all chapters of the manga
const chapterToDeleteUpToDateData = Chapters.getFromCache<TChapter>(chapterToDelete.id)!;
const shouldDeleteChapter =
chapterToDeleteUpToDateData.isRead &&
Chapters.isAutoDeletable(chapterToDeleteUpToDateData, metadataSettings.deleteChaptersWithBookmark);
if (!shouldDeleteChapter) {
return -1;
}
return chapterToDelete.id;
};
const downloadAhead = () => {
const currentChapter = Chapters.getFromCache<TChapter>(chapter.id);
const inDownloadRange = (patch.lastPageRead ?? 0) / chapter.pageCount > 0.25;
const shouldCheckDownloadAhead =
isDownloadAheadEnabled && chapter.manga.inLibrary && !!currentChapter?.isDownloaded && inDownloadRange;
if (shouldCheckDownloadAhead) {
const nextChapterUpToDate = nextChapter ? Chapters.getFromCache<TChapter>(nextChapter.id) : null;
if (!nextChapterUpToDate?.isDownloaded) {
return;
}
const nextChaptersUpToDate = Chapters.getNonRead(nextChapters).map(
// the chapters have to be in the cache since the reader fetches the whole chapter list of the manga
(mangaChapter) => Chapters.getFromCache<TChapter>(mangaChapter.id)!,
);
const chapterIdsToDownload = nextChaptersUpToDate
// "settingsData" can't be undefined since this would not get executed otherwise
.slice(-downloadAheadLimit)
.filter((mangaChapter) => !mangaChapter.isDownloaded)
.map((mangaChapter) => mangaChapter.id)
.filter((id) => !Chapters.isDownloading(id));
if (!chapterIdsToDownload.length) {
return;
}
Chapters.download(chapterIdsToDownload!).catch(
defaultPromiseErrorHandler('Reader::updateChapter: shouldDownloadAhead'),
);
}
};
downloadAhead();
requestManager
.updateChapter(chapter.id, {
...patch,
chapterIdToDelete: getChapterIdToDelete(),
})
.response.catch();
};
const setSettingValue = (key: keyof IReaderSettings, value: AllowedMetadataValueTypes) => {
Save reader settings per manga in Meta (#216) * [#213] Add missing "meta" property - IManga - IMangaCard (optional) - IChapter - ICategory * [#213] Add util functions for handling metadata - global server - manga - chapter - category * [#213] Use "ReaderSettings" from the manga metadata - get ReaderSettings from manga metadata - remove unnecessary check "make sure settings has all the keys" in case the stored settings in the metadata are outdated they will be filled with default values * [#213] Reload manga only in case "mangaId" changed In case the chapter is still from the same manga, a reload is unnecessary * [#213] Only update the changed reader setting Otherwise the app has to send patch requests to the server for every setting even if it didn't change * [#213] Hide "openButton" on first render in case "navBar" is shown The "openButton" was always set to be visible event in case the navBar was shown on the first render * [#213] Open the "ReaderNavBar" if needed after receiving new settings Otherwise, the drawer won't open in case the "navBar" was hidden on the first render since the default state in that case was set to false * [#213] Update "ReaderSettings" after receiving the manga response Otherwise, the default settings aren't getting removed * [#213] Hide/Show "OpenButton" when opening/closing the drawer Otherwise, the button stays hidden until it gets updated due to scrolling * [#213] Keep "ReaderNavBar" state when opening prev/next chapter In case the navBar wasn't sticky but opened, it got closed when the prev/next chapter got opened * [#213] Prevent "ReaderNavBar" from closing when changing "staticNav" setting
2023-01-06 17:15:29 +01:00
setSettings({ ...settings, [key]: value });
requestUpdateMangaMetadata(manga, [[key, value]]).catch(() =>
makeToast(t('reader.settings.error.label.failed_to_save_settings'), 'warning'),
);
Save reader settings per manga in Meta (#216) * [#213] Add missing "meta" property - IManga - IMangaCard (optional) - IChapter - ICategory * [#213] Add util functions for handling metadata - global server - manga - chapter - category * [#213] Use "ReaderSettings" from the manga metadata - get ReaderSettings from manga metadata - remove unnecessary check "make sure settings has all the keys" in case the stored settings in the metadata are outdated they will be filled with default values * [#213] Reload manga only in case "mangaId" changed In case the chapter is still from the same manga, a reload is unnecessary * [#213] Only update the changed reader setting Otherwise the app has to send patch requests to the server for every setting even if it didn't change * [#213] Hide "openButton" on first render in case "navBar" is shown The "openButton" was always set to be visible event in case the navBar was shown on the first render * [#213] Open the "ReaderNavBar" if needed after receiving new settings Otherwise, the drawer won't open in case the "navBar" was hidden on the first render since the default state in that case was set to false * [#213] Update "ReaderSettings" after receiving the manga response Otherwise, the default settings aren't getting removed * [#213] Hide/Show "OpenButton" when opening/closing the drawer Otherwise, the button stays hidden until it gets updated due to scrolling * [#213] Keep "ReaderNavBar" state when opening prev/next chapter In case the navBar wasn't sticky but opened, it got closed when the prev/next chapter got opened * [#213] Prevent "ReaderNavBar" from closing when changing "staticNav" setting
2023-01-06 17:15:29 +01:00
};
const openNextChapter = useCallback(
(offset: ChapterOffset) => {
const isOpenNextChapter = offset === ChapterOffset.NEXT;
const chapterToOpen = isOpenNextChapter ? nextChapter : prevChapter;
if (!chapterToOpen) {
makeToast(
t(
isOpenNextChapter
? 'reader.error.label.next_chapter_does_not_exist'
: 'reader.error.label.prev_chapter_does_not_exist',
),
'error',
);
return;
}
setRetrievingNextChapter(true);
setCurPage(0);
navigate(`/manga/${manga.id}/chapter/${chapterToOpen.sourceOrder}`, {
replace: true,
state: location.state,
});
setRetrievingNextChapter(false);
},
[manga.id, prevChapter?.id, nextChapter?.id],
);
useEffect(() => {
if (isLoading || !chapter) {
setCurPage(0);
return;
}
setWasLastPageReadSet(true);
if (chapter.lastPageRead === chapter.pageCount - 1) {
// last page, also probably read = true, we will load the first page.
setCurPage(0);
} else setCurPage(chapter.lastPageRead);
}, [chapter, isLoading]);
useEffect(() => {
if (!manga?.title || chapter.name === t('global.label.loading')) {
setTitle(t('reader.title'));
} else {
setTitle(`${manga.title}: ${chapter.name}`);
}
}, [t, manga, chapter]);
useEffect(() => {
if (!areDefaultSettingsLoading && !isMangaLoading) {
checkAndHandleMissingStoredReaderSettings(manga, 'manga', defaultSettings).catch(
defaultPromiseErrorHandler('Reader::checkAndHandleMissingStoredReaderSettings'),
);
setSettings(getReaderSettingsFor(manga, defaultSettings));
}
}, [areDefaultSettingsLoading, isMangaLoading]);
Save reader settings per manga in Meta (#216) * [#213] Add missing "meta" property - IManga - IMangaCard (optional) - IChapter - ICategory * [#213] Add util functions for handling metadata - global server - manga - chapter - category * [#213] Use "ReaderSettings" from the manga metadata - get ReaderSettings from manga metadata - remove unnecessary check "make sure settings has all the keys" in case the stored settings in the metadata are outdated they will be filled with default values * [#213] Reload manga only in case "mangaId" changed In case the chapter is still from the same manga, a reload is unnecessary * [#213] Only update the changed reader setting Otherwise the app has to send patch requests to the server for every setting even if it didn't change * [#213] Hide "openButton" on first render in case "navBar" is shown The "openButton" was always set to be visible event in case the navBar was shown on the first render * [#213] Open the "ReaderNavBar" if needed after receiving new settings Otherwise, the drawer won't open in case the "navBar" was hidden on the first render since the default state in that case was set to false * [#213] Update "ReaderSettings" after receiving the manga response Otherwise, the default settings aren't getting removed * [#213] Hide/Show "OpenButton" when opening/closing the drawer Otherwise, the button stays hidden until it gets updated due to scrolling * [#213] Keep "ReaderNavBar" state when opening prev/next chapter In case the navBar wasn't sticky but opened, it got closed when the prev/next chapter got opened * [#213] Prevent "ReaderNavBar" from closing when changing "staticNav" setting
2023-01-06 17:15:29 +01:00
useEffect(() => {
// set the custom navbar
setOverride({
status: true,
value: (
<ReaderNavBar
settings={settings}
setSettingValue={setSettingValue}
manga={manga}
chapter={chapter}
curPage={curPage}
scrollToPage={setPageToScrollTo}
openNextChapter={openNextChapter}
retrievingNextChapter={retrievingNextChapter}
/>
),
});
2021-03-18 21:46:24 +03:30
// clean up for when we leave the reader
return () => setOverride({ status: false, value: <div /> });
}, [manga, chapter, settings, curPage, chapterIndex, retrievingNextChapter]);
2021-03-18 21:46:24 +03:30
2021-05-18 02:26:45 +04:30
useEffect(() => {
if (!wasLastPageReadSet) {
return;
}
if (chapter === initialChapter) {
return;
}
// do not mutate the chapter, this will cause the page to jump around due to always scrolling to the last read page
const updateLastPageRead = curPageDebounced !== -1;
const updateIsRead = curPageDebounced === chapter.pageCount - 1;
const shouldUpdateChapter = updateLastPageRead || updateIsRead;
if (!shouldUpdateChapter) {
return;
2021-05-18 02:26:45 +04:30
}
updateChapter({
lastPageRead: updateLastPageRead ? curPageDebounced : undefined,
isRead: updateIsRead ? true : undefined,
});
}, [curPageDebounced, isDownloadAheadEnabled]);
2021-05-18 02:26:45 +04:30
const loadNextChapter = useCallback(() => {
updateChapter({
lastPageRead: chapter.pageCount - 1,
isRead: true,
});
openNextChapter(ChapterOffset.NEXT);
}, [chapter.pageCount, openNextChapter]);
const loadPrevChapter = useCallback(() => {
openNextChapter(ChapterOffset.PREV);
}, [openNextChapter]);
if (isLoading) {
return (
<Box
sx={{
height: '100vh',
width: '100vw',
display: 'grid',
placeItems: 'center',
}}
>
<CircularProgress thickness={5} />
</Box>
);
}
2021-05-15 17:18:57 +04:30
const pages = range(chapter.pageCount).map((index) => ({
index,
src: requestManager.getChapterPageUrl(mangaId, chapterIndex, index),
2021-05-15 17:18:57 +04:30
}));
2021-05-15 23:22:37 +04:30
const ReaderComponent = getReaderComponent(settings.readerType);
// last page, also probably read = true, we will load the first page.
const initialPage = pageToScrollTo ?? (chapter.lastPageRead === chapter.pageCount - 1 ? 0 : chapter.lastPageRead);
2021-01-20 01:05:24 +03:30
return (
<Box
sx={{
Fix reader width (#567) * Fix reader width The margin: auto on the Box container for the image was preventing 100% width to actually mean 100%. Now that 100% is actually possible, I think fitPageToWindow makes more sense as a default. Additionally, since the image can fill 100% of the page, it can cover the ReaderNavBar, so set the z-index of the ReaderNavBar so it's rendered on top of the image and clickable. Signed-off-by: Chance Zibolski <chance.zibolski@gmail.com> * Support configuring reader width for DoublePage readers Signed-off-by: Chance Zibolski <chance.zibolski@gmail.com> * Fix single page of DoublePageReader not being able to take up full width In case the parent container is flex row, the container does not automatically take up 100% of the available width, thus, the page also was not able to take up 100% of the width * Fix applying reader width to double pages The set reader width can't be applied to each page of the double pages because otherwise it will already take up 100% of the available width with the setting only being at 50%. Instead, the set width has to be divided by 2, so that both pages take up the set reader width * Prevent double page spinner from being larger than 100% of the available width * Update width styling of the page spinner * Always center pages in the middle of the screen * Take up full height fitting page to window height --------- Signed-off-by: Chance Zibolski <chance.zibolski@gmail.com> Co-authored-by: schroda <50052685+schroda@users.noreply.github.com>
2024-01-26 11:51:08 -08:00
display: 'flex',
flexDirection: 'column',
alignContent: 'center',
2024-02-21 23:39:12 +01:00
alignItems: 'center',
Fix reader width (#567) * Fix reader width The margin: auto on the Box container for the image was preventing 100% width to actually mean 100%. Now that 100% is actually possible, I think fitPageToWindow makes more sense as a default. Additionally, since the image can fill 100% of the page, it can cover the ReaderNavBar, so set the z-index of the ReaderNavBar so it's rendered on top of the image and clickable. Signed-off-by: Chance Zibolski <chance.zibolski@gmail.com> * Support configuring reader width for DoublePage readers Signed-off-by: Chance Zibolski <chance.zibolski@gmail.com> * Fix single page of DoublePageReader not being able to take up full width In case the parent container is flex row, the container does not automatically take up 100% of the available width, thus, the page also was not able to take up 100% of the width * Fix applying reader width to double pages The set reader width can't be applied to each page of the double pages because otherwise it will already take up 100% of the available width with the setting only being at 50%. Instead, the set width has to be divided by 2, so that both pages take up the set reader width * Prevent double page spinner from being larger than 100% of the available width * Update width styling of the page spinner * Always center pages in the middle of the screen * Take up full height fitting page to window height --------- Signed-off-by: Chance Zibolski <chance.zibolski@gmail.com> Co-authored-by: schroda <50052685+schroda@users.noreply.github.com>
2024-01-26 11:51:08 -08:00
justifyContent: 'center',
2024-01-26 23:59:12 +01:00
minWidth: settings.staticNav
? 'calc((100vw - (100vw - 100%)) - 300px)'
: 'calc(100vw - (100vw - 100%))', // 100vw = width excluding scrollbar; 100% = width including scrollbar
Fix reader width (#567) * Fix reader width The margin: auto on the Box container for the image was preventing 100% width to actually mean 100%. Now that 100% is actually possible, I think fitPageToWindow makes more sense as a default. Additionally, since the image can fill 100% of the page, it can cover the ReaderNavBar, so set the z-index of the ReaderNavBar so it's rendered on top of the image and clickable. Signed-off-by: Chance Zibolski <chance.zibolski@gmail.com> * Support configuring reader width for DoublePage readers Signed-off-by: Chance Zibolski <chance.zibolski@gmail.com> * Fix single page of DoublePageReader not being able to take up full width In case the parent container is flex row, the container does not automatically take up 100% of the available width, thus, the page also was not able to take up 100% of the width * Fix applying reader width to double pages The set reader width can't be applied to each page of the double pages because otherwise it will already take up 100% of the available width with the setting only being at 50%. Instead, the set width has to be divided by 2, so that both pages take up the set reader width * Prevent double page spinner from being larger than 100% of the available width * Update width styling of the page spinner * Always center pages in the middle of the screen * Take up full height fitting page to window height --------- Signed-off-by: Chance Zibolski <chance.zibolski@gmail.com> Co-authored-by: schroda <50052685+schroda@users.noreply.github.com>
2024-01-26 11:51:08 -08:00
minHeight: '100vh',
marginLeft: settings.staticNav ? '300px' : 'unset',
}}
>
<PageNumber settings={settings} curPage={curPage} pageCount={chapter.pageCount} />
<Box sx={{ alignSelf: 'stretch' }}>
<ReaderComponent
key={chapter.id}
pages={pages}
pageCount={chapter.pageCount}
setCurPage={setCurPage}
initialPage={initialPage}
curPage={curPage}
settings={settings}
manga={manga}
chapter={chapter}
nextChapter={loadNextChapter}
prevChapter={loadPrevChapter}
/>
</Box>
2021-12-04 10:29:36 +03:30
</Box>
2021-01-20 01:05:24 +03:30
);
}