Files
suwayomi-material-you-webui/src/modules/reader/services/ReaderControls.ts

445 lines
18 KiB
TypeScript
Raw Normal View History

2024-11-03 03:09:00 +01:00
/*
* 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/.
*/
2024-11-06 13:00:36 +01:00
import { MutableRefObject, useCallback, useMemo } from 'react';
import { Direction, useTheme } from '@mui/material/styles';
2024-11-03 03:09:00 +01:00
import { userReaderStatePagesContext } from '@/modules/reader/contexts/state/ReaderStatePagesContext.tsx';
2024-12-07 03:43:18 +01:00
import { getNextIndexFromPage, getNextPageIndex, getPage } from '@/modules/reader/utils/ReaderProgressBar.utils.tsx';
2024-11-03 03:09:00 +01:00
import { getOptionForDirection } from '@/theme.tsx';
import { ReaderService } from '@/modules/reader/services/ReaderService.ts';
import { useReaderStateChaptersContext } from '@/modules/reader/contexts/state/ReaderStateChaptersContext.tsx';
2024-12-03 18:00:46 +01:00
import {
PageInViewportType,
ReaderResumeMode,
ReaderTransitionPageMode,
2024-12-03 18:00:46 +01:00
ReadingDirection,
ReadingMode,
} from '@/modules/reader/types/Reader.types.ts';
2024-11-03 03:09:00 +01:00
import { ScrollDirection, ScrollOffset } from '@/modules/core/Core.types.ts';
import {
ReaderScrollAmount,
READING_DIRECTION_TO_THEME_DIRECTION,
} from '@/modules/reader/constants/ReaderSettings.constants.tsx';
2024-12-07 03:43:18 +01:00
import { isEndOfPageInViewport, isPageInViewport } from '@/modules/reader/utils/ReaderPager.utils.tsx';
2024-11-06 13:00:36 +01:00
import { useReaderOverlayContext } from '@/modules/reader/contexts/ReaderOverlayContext.tsx';
import { useReaderTapZoneContext } from '@/modules/reader/contexts/ReaderTapZoneContext.tsx';
import { TapZoneRegionType } from '@/modules/reader/types/TapZoneLayout.types.ts';
import { ReaderTapZoneService } from '@/modules/reader/services/ReaderTapZoneService.ts';
import { isContinuousReadingMode } from '@/modules/reader/utils/ReaderSettings.utils.tsx';
2024-12-07 03:43:18 +01:00
import { getReaderChapterFromCache } from '@/modules/reader/utils/Reader.utils.ts';
import { Chapters } from '@/modules/chapter/services/Chapters.ts';
import { DirectionOffset } from '@/Base.types.ts';
import { useMetadataServerSettings } from '@/modules/settings/services/ServerSettingsMetadata.ts';
2024-11-03 03:09:00 +01:00
const getScrollDirectionInvert = (
scrollDirection: ScrollDirection,
scrollOffset: ScrollOffset,
themeDirection: Direction,
): 1 | -1 => {
if (scrollDirection === ScrollDirection.X) {
if (scrollOffset === ScrollOffset.BACKWARD) {
if (themeDirection === 'ltr') {
return -1;
}
return 1;
}
if (scrollOffset === ScrollOffset.FORWARD) {
if (themeDirection === 'ltr') {
return 1;
}
return -1;
}
}
2024-11-03 03:09:00 +01:00
// handle ScrollDirection.XY the same as ScrollDirection.Y
if (scrollOffset === ScrollOffset.BACKWARD) {
return -1;
}
return 1;
2024-11-03 03:09:00 +01:00
};
export class ReaderControls {
2024-12-07 03:43:18 +01:00
private static updateCurrentPageTimeout: NodeJS.Timeout;
2024-11-03 03:09:00 +01:00
static scroll(
offset: ScrollOffset,
direction: ScrollDirection,
readingMode: ReadingMode,
2024-11-03 03:09:00 +01:00
readingDirection: ReadingDirection,
themeDirection: Direction,
2024-11-03 03:09:00 +01:00
element: HTMLElement,
2024-12-03 18:00:46 +01:00
openChapter: ReturnType<(typeof ReaderControls)['useOpenChapter']>,
2024-11-03 03:09:00 +01:00
scrollAmountPercentage: number = ReaderScrollAmount.LARGE,
): void {
if (!element) {
return;
}
const themeDirectionOfReadingDirection = READING_DIRECTION_TO_THEME_DIRECTION[readingDirection];
const areReadingDirectionsEqual = themeDirection === themeDirectionOfReadingDirection;
const isContinuousReadingModeActive = isContinuousReadingMode(readingMode);
2024-12-03 18:00:46 +01:00
const isAtStartY = element.scrollTop === 0;
const isAtEndY =
Math.floor(element.scrollTop) === element.scrollHeight - element.clientHeight ||
Math.ceil(element.scrollTop) === element.scrollHeight - element.clientHeight;
const isAtStartX = element.scrollLeft === 0;
const isAtEndX =
Math.floor(Math.abs(element.scrollLeft)) === element.scrollWidth - element.clientWidth ||
Math.ceil(Math.abs(element.scrollLeft)) === element.scrollWidth - element.clientWidth;
const isAtStartXForDirection = areReadingDirectionsEqual ? isAtStartX : isAtEndX;
const isAtEndXForDirection = areReadingDirectionsEqual ? isAtEndX : isAtStartX;
2024-12-03 18:00:46 +01:00
2024-11-03 03:09:00 +01:00
const scrollAmount = scrollAmountPercentage / 100;
const scrollDirection = getScrollDirectionInvert(direction, offset, themeDirectionOfReadingDirection);
2024-11-03 03:09:00 +01:00
const getNewScrollPosition = (currentPos: number, elementSize: number) =>
currentPos + elementSize * scrollAmount * scrollDirection;
switch (direction) {
case ScrollDirection.X:
if (isAtStartXForDirection && offset === ScrollOffset.BACKWARD && isContinuousReadingModeActive) {
openChapter('previous', 'ltr');
2024-12-03 18:00:46 +01:00
return;
}
if (isAtEndXForDirection && offset === ScrollOffset.FORWARD && isContinuousReadingModeActive) {
openChapter('next', 'ltr');
2024-12-03 18:00:46 +01:00
return;
}
2024-11-03 03:09:00 +01:00
element.scroll({
left: getNewScrollPosition(element.scrollLeft, element.clientWidth),
behavior: 'smooth',
});
break;
case ScrollDirection.Y:
if (isAtStartY && offset === ScrollOffset.BACKWARD && isContinuousReadingModeActive) {
openChapter('previous', 'ltr');
2024-12-03 18:00:46 +01:00
return;
}
if (isAtEndY && offset === ScrollOffset.FORWARD && isContinuousReadingModeActive) {
openChapter('next', 'ltr');
2024-12-03 18:00:46 +01:00
return;
}
2024-11-03 03:09:00 +01:00
element.scroll({
top: getNewScrollPosition(element.scrollTop, element.clientHeight),
behavior: 'smooth',
});
break;
default:
throw new Error(`Unexpected "ScrollDirection" (${direction})`);
}
}
static useOpenChapter(): (offset: 'previous' | 'next', forceDirection?: Direction) => void {
2024-12-03 18:00:46 +01:00
const { readingDirection, readingMode } = ReaderService.useSettings();
2024-11-03 03:09:00 +01:00
const { previousChapter, nextChapter } = useReaderStateChaptersContext();
const direction = READING_DIRECTION_TO_THEME_DIRECTION[readingDirection.value];
2024-11-03 03:09:00 +01:00
const openPreviousChapter = ReaderService.useNavigateToChapter(previousChapter, ReaderResumeMode.END);
const openNextChapter = ReaderService.useNavigateToChapter(nextChapter, ReaderResumeMode.START);
2024-11-03 03:09:00 +01:00
return useCallback(
(offset, forceDirection = direction) => {
2024-11-03 03:09:00 +01:00
switch (offset) {
case 'previous':
getOptionForDirection(openPreviousChapter, openNextChapter, forceDirection)();
2024-11-03 03:09:00 +01:00
break;
case 'next':
getOptionForDirection(openNextChapter, openPreviousChapter, forceDirection)();
2024-11-03 03:09:00 +01:00
break;
default:
throw new Error(`Unexpected "offset" (${offset})`);
}
},
2024-12-03 18:00:46 +01:00
[direction, openPreviousChapter, openNextChapter, readingMode.value],
2024-11-03 03:09:00 +01:00
);
}
2024-12-03 18:00:46 +01:00
static useOpenPage(): (page: number | 'previous' | 'next', forceDirection?: Direction) => void {
const { currentPageIndex, setPageToScrollToIndex, pages, transitionPageMode, setTransitionPageMode } =
userReaderStatePagesContext();
const { previousChapter, nextChapter } = useReaderStateChaptersContext();
const { readingDirection, readingMode } = ReaderService.useSettings();
const openChapter = ReaderControls.useOpenChapter();
2024-11-03 03:09:00 +01:00
const currentPage = useMemo(() => getPage(currentPageIndex, pages), [currentPageIndex, pages]);
const previousPageIndex = useMemo(
() => getNextPageIndex('previous', currentPage.pagesIndex, pages),
[currentPage, pages],
);
const nextPageIndex = useMemo(
() => getNextPageIndex('next', currentPage.pagesIndex, pages),
[currentPage, pages],
);
2024-12-07 03:43:18 +01:00
const indexOfLastPage = getNextIndexFromPage(pages[pages.length - 1]);
const direction = READING_DIRECTION_TO_THEME_DIRECTION[readingDirection.value];
2024-11-03 03:09:00 +01:00
2024-12-03 18:00:46 +01:00
const isFirstPage = currentPageIndex === 0;
2024-12-07 03:43:18 +01:00
const isLastPage = currentPageIndex === indexOfLastPage;
2024-12-03 18:00:46 +01:00
const isATransitionPageVisible = transitionPageMode !== ReaderTransitionPageMode.NONE;
const isContinuousReadingModeActive = isContinuousReadingMode(readingMode.value);
2024-11-03 03:09:00 +01:00
return useCallback(
2024-12-03 18:00:46 +01:00
(page, forceDirection = direction) => {
const convertedPage = getOptionForDirection(
page,
page === 'previous' ? 'next' : 'previous',
forceDirection,
);
const shouldOpenPreviousChapter =
isFirstPage && isATransitionPageVisible && convertedPage === 'previous' && !!previousChapter;
if (shouldOpenPreviousChapter) {
openChapter('previous');
return;
}
const shouldOpenNextChapter =
isLastPage && isATransitionPageVisible && convertedPage === 'next' && !!nextChapter;
if (shouldOpenNextChapter) {
openChapter('next');
return;
}
const hideTransitionPage = () => setTransitionPageMode(ReaderTransitionPageMode.NONE);
if (typeof page === 'number') {
setPageToScrollToIndex(page);
hideTransitionPage();
return;
}
const needToHideTransitionPage = isATransitionPageVisible && !isContinuousReadingModeActive;
switch (convertedPage) {
2024-11-03 03:09:00 +01:00
case 'previous':
2024-12-03 18:00:46 +01:00
if (isFirstPage) {
setTransitionPageMode(ReaderTransitionPageMode.PREVIOUS);
return;
}
if (needToHideTransitionPage) {
hideTransitionPage();
return;
}
setPageToScrollToIndex(previousPageIndex);
2024-11-03 03:09:00 +01:00
break;
case 'next':
2024-12-03 18:00:46 +01:00
if (isLastPage) {
setTransitionPageMode(ReaderTransitionPageMode.NEXT);
return;
}
if (needToHideTransitionPage) {
hideTransitionPage();
return;
}
setPageToScrollToIndex(nextPageIndex);
2024-11-03 03:09:00 +01:00
break;
default:
2024-12-03 18:00:46 +01:00
throw new Error(`Unexpected "offset" (${page})`);
2024-11-03 03:09:00 +01:00
}
},
2024-12-03 18:00:46 +01:00
[
direction,
previousPageIndex,
nextPageIndex,
2024-12-07 03:43:18 +01:00
indexOfLastPage,
2024-12-03 18:00:46 +01:00
isATransitionPageVisible,
isContinuousReadingModeActive,
isFirstPage,
isLastPage,
openChapter,
!!previousChapter,
!!nextChapter,
],
2024-11-03 03:09:00 +01:00
);
}
2024-11-06 13:00:36 +01:00
2024-12-07 03:43:18 +01:00
static useUpdateCurrentPageIndex(): (
pageIndex: number,
debounceChapterUpdate?: boolean,
endReached?: boolean,
) => void {
const { currentPageIndex, setCurrentPageIndex } = userReaderStatePagesContext();
const { initialChapter, currentChapter, nextChapter, mangaChapters } = useReaderStateChaptersContext();
const updateChapter = ReaderService.useUpdateChapter();
const { shouldSkipDupChapters } = ReaderService.useSettings();
const {
settings: { downloadAheadLimit },
} = useMetadataServerSettings();
const nextChapters = useMemo(() => {
if (!initialChapter || !currentChapter) {
return [];
}
return Chapters.getNextChapters(currentChapter, mangaChapters, {
offset: DirectionOffset.NEXT,
skipDupe: shouldSkipDupChapters,
skipDupeChapter: initialChapter,
});
}, [initialChapter?.id, currentChapter?.id, mangaChapters, shouldSkipDupChapters]);
return useCallback(
(pageIndex, debounceChapterUpdate = true, endReached = false) => {
setCurrentPageIndex(pageIndex);
if (!currentChapter) {
return;
}
const hasPageIndexChanged = pageIndex !== currentPageIndex;
if (!hasPageIndexChanged) {
return;
}
ReaderService.downloadAhead(currentChapter, nextChapter, nextChapters, pageIndex, downloadAheadLimit);
const handleCurrentPageIndexChange = () => {
const currentChapterUpToDate = getReaderChapterFromCache(currentChapter.id);
if (!currentChapterUpToDate) {
return;
}
const hasLastPageReadChanged = pageIndex !== currentChapterUpToDate.lastPageRead;
const isLasPage = endReached || pageIndex === currentChapterUpToDate.pageCount - 1;
const shouldUpdateChapter = hasLastPageReadChanged || isLasPage;
if (!shouldUpdateChapter) {
return;
}
updateChapter({
lastPageRead: hasLastPageReadChanged ? pageIndex : undefined,
isRead: isLasPage ? true : undefined,
});
};
clearTimeout(this.updateCurrentPageTimeout);
if (debounceChapterUpdate) {
this.updateCurrentPageTimeout = setTimeout(handleCurrentPageIndexChange, 1000);
return;
}
handleCurrentPageIndexChange();
},
[currentChapter?.id, nextChapter?.id, nextChapters, currentPageIndex, downloadAheadLimit],
);
}
2024-11-06 13:00:36 +01:00
static updateCurrentPageOnScroll(
imageRefs: MutableRefObject<(HTMLElement | null)[]>,
2024-12-07 03:43:18 +01:00
lastPageIndex: number,
updateCurrentPageIndex: ReturnType<typeof ReaderControls.useUpdateCurrentPageIndex>,
2024-11-06 13:00:36 +01:00
type: PageInViewportType,
2024-12-07 03:43:18 +01:00
readingDirection: ReadingDirection,
2024-11-06 13:00:36 +01:00
) {
const firstVisibleImageIndex = imageRefs.current.findIndex((image) => image && isPageInViewport(image, type));
2024-12-07 03:43:18 +01:00
const lastPage = imageRefs.current?.[imageRefs.current.length - 1];
const isEndReached = lastPage && isEndOfPageInViewport(lastPage, type, readingDirection);
// handle cases where the last page is too small to ever be the "firstVisibleImageIndex"
if (isEndReached) {
updateCurrentPageIndex(lastPageIndex, false);
return;
}
2024-11-06 13:00:36 +01:00
2024-12-07 03:43:18 +01:00
if (firstVisibleImageIndex !== -1) {
updateCurrentPageIndex(firstVisibleImageIndex, firstVisibleImageIndex !== lastPageIndex);
2024-11-06 13:00:36 +01:00
}
}
static useHandleClick(
scrollElement: HTMLElement | null,
): (event: React.MouseEvent<HTMLDivElement, MouseEvent>) => void {
const { direction: themeDirection } = useTheme();
2024-11-06 13:00:36 +01:00
const { setIsVisible: setIsOverlayVisible } = useReaderOverlayContext();
const { currentPageIndex, pages } = userReaderStatePagesContext();
const { setShowPreview } = useReaderTapZoneContext();
const { readingMode, readingDirection, isStaticNav } = ReaderService.useSettings();
const openPage = ReaderControls.useOpenPage();
2024-12-03 18:00:46 +01:00
const openChapter = ReaderControls.useOpenChapter();
2024-11-06 13:00:36 +01:00
return useCallback(
(e) => {
if (!scrollElement) {
return;
}
const rect = e.currentTarget.getBoundingClientRect();
const rectRelativeX = e.clientX - rect.left;
const rectRelativeY = e.clientY - rect.top;
const action = ReaderTapZoneService.getAction(rectRelativeX, rectRelativeY);
setShowPreview(false);
const isContinuousReadingModeActive = isContinuousReadingMode(readingMode.value);
const scrollDirection =
readingMode.value === ReadingMode.CONTINUOUS_HORIZONTAL ? ScrollDirection.X : ScrollDirection.Y;
switch (action) {
case TapZoneRegionType.MENU:
setIsOverlayVisible((isVisible) => isStaticNav || !isVisible);
break;
case TapZoneRegionType.PREVIOUS:
if (isContinuousReadingModeActive) {
2024-12-03 18:00:46 +01:00
this.scroll(
ScrollOffset.BACKWARD,
scrollDirection,
readingMode.value,
2024-12-03 18:00:46 +01:00
readingDirection.value,
themeDirection,
2024-12-03 18:00:46 +01:00
scrollElement,
openChapter,
);
2024-11-06 13:00:36 +01:00
} else {
openPage('previous', 'ltr');
2024-11-06 13:00:36 +01:00
}
break;
case TapZoneRegionType.NEXT:
if (isContinuousReadingModeActive) {
2024-12-03 18:00:46 +01:00
this.scroll(
ScrollOffset.FORWARD,
scrollDirection,
readingMode.value,
2024-12-03 18:00:46 +01:00
readingDirection.value,
themeDirection,
2024-12-03 18:00:46 +01:00
scrollElement,
openChapter,
);
2024-11-06 13:00:36 +01:00
} else {
openPage('next', 'ltr');
2024-11-06 13:00:36 +01:00
}
break;
default:
throw new Error(`Unexpected "TapZoneRegionType" (${action})`);
}
},
[
scrollElement,
currentPageIndex,
pages,
readingMode.value,
openPage,
readingDirection.value,
openChapter,
themeDirection,
],
2024-11-06 13:00:36 +01:00
);
}
2024-11-03 03:09:00 +01:00
}