Verticall scroll navigation and fix (#200)

* Remove scroll tracking from Page component

* Replace initial scrolling trigger with initialPage prop to be more clear on when to scroll to inital page

* Add current page tracking back to HorizontalPager

* Memoize prevChapter and nextChapter functions

* Rewrite navigation in vertical pager to scroll by screen percentage instead of whole pages, refactor code

* Handle last pages explicitly to fix issue with small last pages
This commit is contained in:
Valter Martinek
2022-11-24 21:05:05 +01:00
committed by GitHub
parent 31a3679e06
commit 7aa4d2f3de
7 changed files with 172 additions and 134 deletions

View File

@@ -5,7 +5,7 @@
* 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, useRef } from 'react'; import React, { useRef } from 'react';
import SpinnerImage from 'components/util/SpinnerImage'; import SpinnerImage from 'components/util/SpinnerImage';
import useLocalStorage from 'util/useLocalStorage'; import useLocalStorage from 'util/useLocalStorage';
import Box from '@mui/system/Box'; import Box from '@mui/system/Box';
@@ -57,52 +57,18 @@ interface IProps {
src: string src: string
index: number index: number
onImageLoad: () => void onImageLoad: () => void
setCurPage: React.Dispatch<React.SetStateAction<number>>
settings: IReaderSettings settings: IReaderSettings
} }
const Page = React.forwardRef((props: IProps, ref: any) => { const Page = React.forwardRef((props: IProps, ref: any) => {
const { const {
src, index, onImageLoad, setCurPage, settings, src, index, onImageLoad, settings,
} = props; } = props;
const [useCache] = useLocalStorage<boolean>('useCache', true); const [useCache] = useLocalStorage<boolean>('useCache', true);
const imgRef = useRef<HTMLImageElement>(null); const imgRef = useRef<HTMLImageElement>(null);
const handleVerticalScroll = () => {
if (imgRef.current) {
const rect = imgRef.current.getBoundingClientRect();
if (rect.y < 0 && rect.y + rect.height > 0) {
setCurPage(index);
}
}
};
const handleHorizontalScroll = () => {
if (imgRef.current) {
const rect = imgRef.current.getBoundingClientRect();
if (rect.left <= window.innerWidth / 2 && rect.right > window.innerWidth / 2) {
setCurPage(index);
}
}
};
useEffect(() => {
switch (settings.readerType) {
case 'Webtoon':
case 'ContinuesVertical':
window.addEventListener('scroll', handleVerticalScroll);
return () => window.removeEventListener('scroll', handleVerticalScroll);
case 'ContinuesHorizontalLTR':
case 'ContinuesHorizontalRTL':
window.addEventListener('scroll', handleHorizontalScroll);
return () => window.removeEventListener('scroll', handleHorizontalScroll);
default:
return () => {};
}
}, [handleVerticalScroll]);
const imgStyle = imageStyle(settings); const imgStyle = imageStyle(settings);
return ( return (

View File

@@ -65,7 +65,6 @@ export default function DoublePagedPager(props: IReaderProps) {
index={curPage} index={curPage}
src={(pagesDisplayed.current === 1) ? pages[curPage].src : ''} src={(pagesDisplayed.current === 1) ? pages[curPage].src : ''}
onImageLoad={() => {}} onImageLoad={() => {}}
setCurPage={setCurPage}
settings={settings} settings={settings}
/>, />,
document.getElementById('display'), document.getElementById('display'),

View File

@@ -9,11 +9,26 @@ import React, { useEffect, useRef } from 'react';
import { Box } from '@mui/system'; import { Box } from '@mui/system';
import Page from '../Page'; import Page from '../Page';
const findCurrentPageIndex = (wrapper: HTMLDivElement): number => {
for (let i = 0; i < wrapper.children.length; i++) {
const child = wrapper.children.item(i);
if (child) {
const { left, right } = child.getBoundingClientRect();
if (left <= window.innerWidth / 2 && right > window.innerWidth / 2) return i;
}
}
return -1;
};
const isAtEnd = () => window.innerWidth + window.scrollX >= document.body.scrollWidth;
const isAtStart = () => window.scrollX <= 0;
export default function HorizontalPager(props: IReaderProps) { export default function HorizontalPager(props: IReaderProps) {
const { const {
pages, curPage, settings, setCurPage, prevChapter, nextChapter, pages, curPage, initialPage, settings, setCurPage, prevChapter, nextChapter,
} = props; } = props;
const currentPageRef = useRef(initialPage);
const selfRef = useRef<HTMLDivElement>(null); const selfRef = useRef<HTMLDivElement>(null);
const pagesRef = useRef<HTMLDivElement[]>([]); const pagesRef = useRef<HTMLDivElement[]>([]);
@@ -87,9 +102,12 @@ export default function HorizontalPager(props: IReaderProps) {
}; };
useEffect(() => { useEffect(() => {
// scroll last read page into view after first mount // Delay scrolling to next cycle
pagesRef.current[curPage]?.scrollIntoView({ inline: 'center' }); setTimeout(() => {
}, [pagesRef.current.length]); // scroll last read page into view when initialPage changes
pagesRef.current[initialPage]?.scrollIntoView({ inline: 'center' });
}, 0);
}, [initialPage]);
useEffect(() => { useEffect(() => {
selfRef.current?.addEventListener('mousedown', dragControl); selfRef.current?.addEventListener('mousedown', dragControl);
@@ -113,6 +131,30 @@ export default function HorizontalPager(props: IReaderProps) {
}; };
}, [selfRef, curPage]); }, [selfRef, curPage]);
useEffect(() => {
const handleScroll = () => {
if (!selfRef.current) return;
// Update current page in parent
const currentPage = findCurrentPageIndex(selfRef.current);
if (currentPage !== currentPageRef.current) {
currentPageRef.current = currentPage;
setCurPage(currentPage);
}
// Special case if scroll is moved all the way to the edge
// This handles cases when last page is show, but is smaller then
// window, in which case it would never get marked as read.
// See https://github.com/Suwayomi/Tachidesk-WebUI/issues/14 for more info
if (settings.readerType === 'ContinuesHorizontalLTR' ? isAtEnd() : isAtStart()) {
currentPageRef.current = pages.length - 1;
setCurPage(currentPageRef.current);
}
};
window.addEventListener('scroll', handleScroll);
return () => window.removeEventListener('scroll', handleScroll);
}, [settings.readerType]);
return ( return (
<Box <Box
ref={selfRef} ref={selfRef}
@@ -134,7 +176,6 @@ export default function HorizontalPager(props: IReaderProps) {
index={page.index} index={page.index}
src={page.src} src={page.src}
onImageLoad={() => {}} onImageLoad={() => {}}
setCurPage={setCurPage}
settings={settings} settings={settings}
ref={(e:HTMLDivElement) => { pagesRef.current[page.index] = e; }} ref={(e:HTMLDivElement) => { pagesRef.current[page.index] = e; }}
/> />

View File

@@ -105,7 +105,6 @@ export default function PagedReader(props: IReaderProps) {
index={curPage} index={curPage}
onImageLoad={() => {}} onImageLoad={() => {}}
src={pages[curPage].src} src={pages[curPage].src}
setCurPage={setCurPage}
settings={settings} settings={settings}
/> />
</Box> </Box>

View File

@@ -5,92 +5,116 @@
* 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, useRef } from 'react'; import React, { useCallback, useEffect, useRef } from 'react';
import { Box } from '@mui/system'; import { Box } from '@mui/system';
import Page from '../Page'; import Page from '../Page';
export default function VerticalReader(props: IReaderProps) { const findCurrentPageIndex = (wrapper: HTMLDivElement): number => {
for (let i = 0; i < wrapper.children.length; i++) {
const child = wrapper.children.item(i);
if (child) {
const { top, bottom } = child.getBoundingClientRect();
if (top <= window.innerHeight && bottom > 1) return i;
}
}
return -1;
};
// TODO: make configurable?
const SCROLL_OFFSET = 0.95;
const SCROLL_BEHAVIOR: ScrollBehavior = 'smooth';
const isAtBottom = () => window.innerHeight + window.scrollY >= document.body.offsetHeight;
const isAtTop = () => window.scrollY <= 0;
export default function VerticalPager(props: IReaderProps) {
const { const {
pages, settings, setCurPage, curPage, nextChapter, prevChapter, pages, settings, setCurPage, initialPage, nextChapter, prevChapter,
} = props; } = props;
const currentPageRef = useRef(initialPage);
const selfRef = useRef<HTMLDivElement>(null); const selfRef = useRef<HTMLDivElement>(null);
const pagesRef = useRef<HTMLDivElement[]>([]); const pagesRef = useRef<HTMLDivElement[]>([]);
useEffect(() => { useEffect(() => {
pagesRef.current = pagesRef.current.slice(0, pages.length); const handleScroll = () => {
}, [pages.length]); if (!selfRef.current) return;
function nextPage() { if (isAtBottom()) {
if (curPage < pages.length - 1) { // If scroll is moved all the way to the bottom
pagesRef.current[curPage + 1]?.scrollIntoView(); // This handles cases when last page is show, but is smaller then
setCurPage((page) => page + 1); // window, in which case it would never get marked as read.
} else if (settings.loadNextonEnding) { // See https://github.com/Suwayomi/Tachidesk-WebUI/issues/14 for more info
nextChapter(); currentPageRef.current = pages.length - 1;
} setCurPage(currentPageRef.current);
}
function prevPage() { // Go to next chapter if configured to and at bottom
if (curPage > 0) { if (settings.loadNextonEnding) {
const rect = pagesRef.current[curPage].getBoundingClientRect(); nextChapter();
if (rect.y < 0 && rect.y + rect.height > 0) { }
pagesRef.current[curPage]?.scrollIntoView();
} else { } else {
pagesRef.current[curPage - 1]?.scrollIntoView(); // Update current page in parent
setCurPage(curPage - 1); const currentPage = findCurrentPageIndex(selfRef.current);
if (currentPage !== currentPageRef.current) {
currentPageRef.current = currentPage;
setCurPage(currentPage);
}
} }
} else if (curPage === 0) {
prevChapter();
}
}
function keyboardControl(e:KeyboardEvent) {
switch (e.code) {
case 'Space':
e.preventDefault();
nextPage();
break;
case 'ArrowRight':
nextPage();
break;
case 'ArrowLeft':
prevPage();
break;
default:
break;
}
}
function clickControl(e:MouseEvent) {
if (e.clientX > window.innerWidth / 2) {
nextPage();
} else {
prevPage();
}
}
const handleLoadNextonEnding = () => {
if ((window.innerHeight + window.scrollY) >= document.body.offsetHeight) {
nextChapter();
}
};
useEffect(() => {
if (settings.loadNextonEnding) { document.addEventListener('scroll', handleLoadNextonEnding); }
document.addEventListener('keydown', keyboardControl, false);
selfRef.current?.addEventListener('click', clickControl);
return () => {
document.removeEventListener('scroll', handleLoadNextonEnding);
document.removeEventListener('keydown', keyboardControl);
selfRef.current?.removeEventListener('click', clickControl);
}; };
}, [selfRef, curPage]);
window.addEventListener('scroll', handleScroll);
return () => {
window.removeEventListener('scroll', handleScroll);
};
}, [settings.loadNextonEnding]);
const go = useCallback((direction: 'up' | 'down') => {
if (direction === 'down' && isAtBottom()) {
nextChapter();
return;
}
if (direction === 'up' && isAtTop()) {
prevChapter();
return;
}
window.scroll({
top: window.scrollY + (window.innerHeight * SCROLL_OFFSET) * (direction === 'up' ? -1 : 1),
behavior: SCROLL_BEHAVIOR,
});
}, [nextChapter, prevChapter]);
useEffect(() => { useEffect(() => {
// scroll last read page into view after first mount const handleKeyboard = (e:KeyboardEvent) => {
pagesRef.current[curPage].scrollIntoView(); switch (e.code) {
}, [pagesRef.current.length]); case 'Space':
case 'ArrowRight':
e.preventDefault();
go('down');
break;
case 'ArrowLeft':
e.preventDefault();
go('up');
break;
default:
break;
}
};
document.addEventListener('keydown', handleKeyboard, false);
return () => {
document.removeEventListener('keydown', handleKeyboard);
};
}, []);
useEffect(() => {
// Delay scrolling to next cycle
setTimeout(() => {
// scroll last read page into view when initialPage changes
pagesRef.current[initialPage]?.scrollIntoView();
}, 0);
}, [initialPage]);
return ( return (
<Box <Box
@@ -102,6 +126,7 @@ export default function VerticalReader(props: IReaderProps) {
margin: '0 auto', margin: '0 auto',
width: '100%', width: '100%',
}} }}
onClick={(e) => go(e.clientX > window.innerWidth / 2 ? 'down' : 'up')}
> >
{ {
pages.map((page) => ( pages.map((page) => (
@@ -110,7 +135,6 @@ export default function VerticalReader(props: IReaderProps) {
index={page.index} index={page.index}
src={page.src} src={page.src}
onImageLoad={() => {}} onImageLoad={() => {}}
setCurPage={setCurPage}
settings={settings} settings={settings}
ref={(e:HTMLDivElement) => { pagesRef.current[page.index] = e; }} ref={(e:HTMLDivElement) => { pagesRef.current[page.index] = e; }}
/> />

View File

@@ -6,7 +6,9 @@
* 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 CircularProgress from '@mui/material/CircularProgress'; import CircularProgress from '@mui/material/CircularProgress';
import React, { useContext, useEffect, useState } from 'react'; import React, {
useCallback, useContext, useEffect, useState,
} from 'react';
import { useHistory, useParams } from 'react-router-dom'; import { useHistory, useParams } from 'react-router-dom';
import HorizontalPager from 'components/reader/pager/HorizontalPager'; import HorizontalPager from 'components/reader/pager/HorizontalPager';
import PageNumber from 'components/reader/PageNumber'; import PageNumber from 'components/reader/PageNumber';
@@ -50,6 +52,7 @@ const initialChapter = () => ({
pageCount: -1, pageCount: -1,
index: -1, index: -1,
chapterCount: 0, chapterCount: 0,
lastPageRead: 0,
name: 'Loading...', name: 'Loading...',
}); });
@@ -62,7 +65,7 @@ export default function Reader() {
const { chapterIndex, mangaId } = useParams<{ chapterIndex: string, mangaId: string }>(); const { chapterIndex, mangaId } = useParams<{ chapterIndex: string, mangaId: string }>();
const [manga, setManga] = useState<IMangaCard | IManga>({ id: +mangaId, title: '', thumbnailUrl: '' }); const [manga, setManga] = useState<IMangaCard | IManga>({ id: +mangaId, title: '', thumbnailUrl: '' });
const [chapter, setChapter] = useState<IChapter | IPartialChpter>(initialChapter()); const [chapter, setChapter] = useState<IChapter | IPartialChapter>(initialChapter());
const [curPage, setCurPage] = useState<number>(0); const [curPage, setCurPage] = useState<number>(0);
const { setOverride, setTitle } = useContext(NavbarContext); const { setOverride, setTitle } = useContext(NavbarContext);
@@ -138,6 +141,23 @@ export default function Reader() {
} }
}, [curPage]); }, [curPage]);
const nextChapter = useCallback(() => {
if (chapter.index < chapter.chapterCount) {
const formData = new FormData();
formData.append('lastPageRead', `${chapter.pageCount - 1}`);
formData.append('read', 'true');
client.patch(`/api/v1/manga/${manga.id}/chapter/${chapter.index}`, formData);
history.replace({ pathname: `/manga/${manga.id}/chapter/${chapter.index + 1}`, state: history.location.state });
}
}, [chapter.index, chapter.chapterCount, chapter.pageCount, manga.id]);
const prevChapter = useCallback(() => {
if (chapter.index > 1) {
history.replace({ pathname: `/manga/${manga.id}/chapter/${chapter.index - 1}`, state: history.location.state });
}
}, [chapter.index, manga.id]);
// return spinner while chpater data is loading // return spinner while chpater data is loading
if (chapter.pageCount === -1) { if (chapter.pageCount === -1) {
return ( return (
@@ -150,23 +170,6 @@ export default function Reader() {
); );
} }
const nextChapter = () => {
if (chapter.index < chapter.chapterCount) {
const formData = new FormData();
formData.append('lastPageRead', `${chapter.pageCount - 1}`);
formData.append('read', 'true');
client.patch(`/api/v1/manga/${manga.id}/chapter/${chapter.index}`, formData);
history.replace({ pathname: `/manga/${manga.id}/chapter/${chapter.index + 1}`, state: history.location.state });
}
};
const prevChapter = () => {
if (chapter.index > 1) {
history.replace({ pathname: `/manga/${manga.id}/chapter/${chapter.index - 1}`, state: history.location.state });
}
};
const pages = range(chapter.pageCount).map((index) => ({ const pages = range(chapter.pageCount).map((index) => ({
index, index,
src: `${serverAddress}/api/v1/manga/${mangaId}/chapter/${chapterIndex}/page/${index}`, src: `${serverAddress}/api/v1/manga/${mangaId}/chapter/${chapterIndex}/page/${index}`,
@@ -174,6 +177,9 @@ export default function Reader() {
const ReaderComponent = getReaderComponent(settings.readerType); const ReaderComponent = getReaderComponent(settings.readerType);
// last page, also probably read = true, we will load the first page.
const initialPage = (chapter.lastPageRead === chapter.pageCount - 1) ? 0 : chapter.lastPageRead;
return ( return (
<Box sx={{ width: settings.staticNav ? 'calc(100vw - 300px)' : '100vw' }}> <Box sx={{ width: settings.staticNav ? 'calc(100vw - 300px)' : '100vw' }}>
<PageNumber <PageNumber
@@ -185,6 +191,7 @@ export default function Reader() {
pages={pages} pages={pages}
pageCount={chapter.pageCount} pageCount={chapter.pageCount}
setCurPage={setCurPage} setCurPage={setCurPage}
initialPage={initialPage}
curPage={curPage} curPage={curPage}
settings={settings} settings={settings}
manga={manga} manga={manga}

6
src/typings.d.ts vendored
View File

@@ -114,10 +114,11 @@ interface IMangaChapter {
chapter: IChapter chapter: IChapter
} }
interface IPartialChpter { interface IPartialChapter {
pageCount: number pageCount: number
index: number index: number
chapterCount: number chapterCount: number
lastPageRead: number
} }
interface ICategory { interface ICategory {
@@ -161,9 +162,10 @@ interface IReaderProps {
pageCount: number pageCount: number
setCurPage: React.Dispatch<React.SetStateAction<number>> setCurPage: React.Dispatch<React.SetStateAction<number>>
curPage: number curPage: number
initialPage: number
settings: IReaderSettings settings: IReaderSettings
manga: IMangaCard | IManga manga: IMangaCard | IManga
chapter: IChapter | IPartialChpter chapter: IChapter | IPartialChapter
nextChapter: () => void nextChapter: () => void
prevChapter: () => void prevChapter: () => void
} }