Compare commits
2 Commits
26b620de2f
...
3745f1f316
| Author | SHA1 | Date | |
|---|---|---|---|
| 3745f1f316 | |||
| 0c6425f0ff |
@ -1,9 +1,12 @@
|
||||
"use client";
|
||||
|
||||
import { useState, useEffect, useRef, useCallback } from "react";
|
||||
import { useState, useEffect, useRef, useCallback, useMemo } from "react";
|
||||
import Link from "next/link";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { writeLastReadChapter } from "@/components/ReadingProgressButton";
|
||||
import {
|
||||
readProgress,
|
||||
writeProgress,
|
||||
} from "@/components/ReadingProgressButton";
|
||||
|
||||
type ChapterMeta = {
|
||||
id: number;
|
||||
@ -48,12 +51,30 @@ export function PageReader({
|
||||
const [pages, setPages] = useState<LoadedPage[]>([]);
|
||||
const [currentChapterNum, setCurrentChapterNum] =
|
||||
useState(startChapterNumber);
|
||||
const [currentPageNum, setCurrentPageNum] = useState(() => {
|
||||
if (typeof window === "undefined") return 1;
|
||||
const p = readProgress(mangaSlug);
|
||||
if (p && p.chapter === startChapterNumber && p.page > 1) return p.page;
|
||||
return 1;
|
||||
});
|
||||
|
||||
const hiddenByScrollRef = useRef(false);
|
||||
const fetchChapterIdxRef = useRef(
|
||||
chapters.findIndex((c) => c.number === startChapterNumber)
|
||||
);
|
||||
// Initialize offset from saved progress so the first fetch starts AT the
|
||||
// user's last-read page — previous pages are skipped entirely
|
||||
const offsetRef = useRef(0);
|
||||
const initialPageRef = useRef(1);
|
||||
const offsetInitedRef = useRef(false);
|
||||
if (!offsetInitedRef.current && typeof window !== "undefined") {
|
||||
offsetInitedRef.current = true;
|
||||
const p = readProgress(mangaSlug);
|
||||
if (p && p.chapter === startChapterNumber && p.page > 1) {
|
||||
offsetRef.current = p.page - 1;
|
||||
initialPageRef.current = p.page;
|
||||
}
|
||||
}
|
||||
const loadingRef = useRef(false);
|
||||
const doneRef = useRef(false);
|
||||
// Count of pages already loaded — tracked via ref so fetchBatch stays stable
|
||||
@ -63,6 +84,13 @@ export function PageReader({
|
||||
const observerRef = useRef<IntersectionObserver | null>(null);
|
||||
const pageRefsRef = useRef<Map<number, HTMLDivElement>>(new Map());
|
||||
|
||||
// Reverse-fetch cursor: the offset of the first loaded page of the
|
||||
// starting chapter. Used to prepend previous pages when the user scrolls
|
||||
// up from a resumed mid-chapter position.
|
||||
const prependOffsetRef = useRef(offsetRef.current);
|
||||
const prependLoadingRef = useRef(false);
|
||||
const prependExhaustedRef = useRef(offsetRef.current === 0);
|
||||
|
||||
const advanceChapterOrFinish = useCallback(() => {
|
||||
if (fetchChapterIdxRef.current + 1 < chapters.length) {
|
||||
fetchChapterIdxRef.current += 1;
|
||||
@ -72,6 +100,71 @@ export function PageReader({
|
||||
}
|
||||
}, [chapters.length]);
|
||||
|
||||
const startChapter = useMemo(
|
||||
() => chapters.find((c) => c.number === startChapterNumber),
|
||||
[chapters, startChapterNumber]
|
||||
);
|
||||
|
||||
const prependBatch = useCallback(async () => {
|
||||
if (
|
||||
prependLoadingRef.current ||
|
||||
prependExhaustedRef.current ||
|
||||
!startChapter
|
||||
)
|
||||
return;
|
||||
const currentOffset = prependOffsetRef.current;
|
||||
const newOffset = Math.max(0, currentOffset - BATCH_SIZE);
|
||||
const limit = currentOffset - newOffset;
|
||||
if (limit <= 0) {
|
||||
prependExhaustedRef.current = true;
|
||||
return;
|
||||
}
|
||||
prependLoadingRef.current = true;
|
||||
const beforeHeight = document.documentElement.scrollHeight;
|
||||
try {
|
||||
const res = await fetch(
|
||||
`/api/pages?chapterId=${startChapter.id}&offset=${newOffset}&limit=${limit}`
|
||||
);
|
||||
const batch: RawPage[] = await res.json();
|
||||
if (batch.length === 0) {
|
||||
prependExhaustedRef.current = true;
|
||||
return;
|
||||
}
|
||||
prependOffsetRef.current = newOffset;
|
||||
if (newOffset === 0) prependExhaustedRef.current = true;
|
||||
|
||||
// Shift forward-fetch trigger indices + total count since every
|
||||
// already-loaded page has moved right by batch.length
|
||||
const shift = batch.length;
|
||||
const shifted = new Set<number>();
|
||||
for (const t of triggerIndicesRef.current) shifted.add(t + shift);
|
||||
triggerIndicesRef.current = shifted;
|
||||
loadedCountRef.current += shift;
|
||||
|
||||
setPages((prev) => [
|
||||
...batch.map((p) => ({
|
||||
chapterNumber: startChapter.number,
|
||||
pageNumber: p.number,
|
||||
imageUrl: p.imageUrl,
|
||||
})),
|
||||
...prev,
|
||||
]);
|
||||
|
||||
// aspect-[3/4] on the prepended <img>s reserves height before their
|
||||
// bytes arrive, so scrollHeight is accurate immediately after React
|
||||
// commits. One scrollBy keeps the previously-visible page anchored.
|
||||
requestAnimationFrame(() => {
|
||||
const afterHeight = document.documentElement.scrollHeight;
|
||||
const delta = afterHeight - beforeHeight;
|
||||
if (delta > 0) window.scrollBy({ top: delta });
|
||||
});
|
||||
} catch {
|
||||
// ignore — user can scroll-up again to retry
|
||||
} finally {
|
||||
prependLoadingRef.current = false;
|
||||
}
|
||||
}, [startChapter]);
|
||||
|
||||
const fetchBatch = useCallback(async () => {
|
||||
if (loadingRef.current || doneRef.current) return;
|
||||
const chapter = chapters[fetchChapterIdxRef.current];
|
||||
@ -232,14 +325,29 @@ export function PageReader({
|
||||
hiddenByScrollRef.current = true;
|
||||
setShowUI(false);
|
||||
}
|
||||
let current = startChapterNumber;
|
||||
// Trigger backward prepend when user approaches the top — fire early
|
||||
// so the DOM/pics are already spawned by the time the user scrolls there
|
||||
if (
|
||||
y < 2500 &&
|
||||
!prependLoadingRef.current &&
|
||||
!prependExhaustedRef.current
|
||||
) {
|
||||
prependBatch();
|
||||
}
|
||||
// Nothing loaded yet — don't overwrite the resumed-page state
|
||||
if (pages.length === 0) return;
|
||||
let chapter = pages[0].chapterNumber;
|
||||
let page = pages[0].pageNumber;
|
||||
for (let i = 0; i < pages.length; i++) {
|
||||
const el = pageRefsRef.current.get(i);
|
||||
if (!el) continue;
|
||||
if (el.offsetTop <= y + 80) current = pages[i].chapterNumber;
|
||||
else break;
|
||||
if (el.offsetTop <= y + 80) {
|
||||
chapter = pages[i].chapterNumber;
|
||||
page = pages[i].pageNumber;
|
||||
} else break;
|
||||
}
|
||||
setCurrentChapterNum(current);
|
||||
setCurrentChapterNum(chapter);
|
||||
setCurrentPageNum(page);
|
||||
};
|
||||
const onScroll = () => {
|
||||
if (rafId) return;
|
||||
@ -250,12 +358,17 @@ export function PageReader({
|
||||
window.removeEventListener("scroll", onScroll);
|
||||
if (rafId) cancelAnimationFrame(rafId);
|
||||
};
|
||||
}, [pages, startChapterNumber]);
|
||||
}, [pages, startChapterNumber, prependBatch]);
|
||||
|
||||
// Persist reading progress whenever the visible chapter changes
|
||||
// Persist progress as user scrolls. offsetRef has been pre-seeded above
|
||||
// so the first fetched page IS the resumed page — no scroll restoration
|
||||
// needed.
|
||||
useEffect(() => {
|
||||
writeLastReadChapter(mangaSlug, currentChapterNum);
|
||||
}, [mangaSlug, currentChapterNum]);
|
||||
writeProgress(mangaSlug, {
|
||||
chapter: currentChapterNum,
|
||||
page: currentPageNum,
|
||||
});
|
||||
}, [mangaSlug, currentChapterNum, currentPageNum]);
|
||||
|
||||
const currentChapter =
|
||||
chapters.find((c) => c.number === currentChapterNum) ??
|
||||
@ -345,7 +458,7 @@ export function PageReader({
|
||||
<img
|
||||
src={page.imageUrl}
|
||||
alt={`Page ${page.pageNumber}`}
|
||||
className="w-full h-auto block align-bottom -mb-px [-webkit-touch-callout:none]"
|
||||
className="w-full h-auto block align-bottom -mb-px aspect-[3/4] [-webkit-touch-callout:none]"
|
||||
draggable={false}
|
||||
/>
|
||||
</div>
|
||||
|
||||
@ -13,34 +13,59 @@ type Props = {
|
||||
chapters: ChapterLite[];
|
||||
};
|
||||
|
||||
export type ReadingProgress = {
|
||||
chapter: number;
|
||||
page: number;
|
||||
};
|
||||
|
||||
function storageKey(slug: string) {
|
||||
return `sunnymh:last-read:${slug}`;
|
||||
}
|
||||
|
||||
export function readLastReadChapter(slug: string): number | null {
|
||||
export function readProgress(slug: string): ReadingProgress | null {
|
||||
if (typeof window === "undefined") return null;
|
||||
const raw = window.localStorage.getItem(storageKey(slug));
|
||||
if (!raw) return null;
|
||||
// New format: JSON { chapter, page }
|
||||
if (raw.startsWith("{")) {
|
||||
try {
|
||||
const parsed = JSON.parse(raw) as ReadingProgress;
|
||||
if (
|
||||
typeof parsed.chapter === "number" &&
|
||||
typeof parsed.page === "number" &&
|
||||
parsed.chapter > 0 &&
|
||||
parsed.page > 0
|
||||
) {
|
||||
return parsed;
|
||||
}
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
// Legacy format: bare chapter number
|
||||
const n = Number(raw);
|
||||
return Number.isFinite(n) && n > 0 ? n : null;
|
||||
return Number.isFinite(n) && n > 0 ? { chapter: n, page: 1 } : null;
|
||||
}
|
||||
|
||||
export function writeLastReadChapter(slug: string, chapter: number) {
|
||||
export function writeProgress(slug: string, progress: ReadingProgress) {
|
||||
if (typeof window === "undefined") return;
|
||||
window.localStorage.setItem(storageKey(slug), String(chapter));
|
||||
window.localStorage.setItem(storageKey(slug), JSON.stringify(progress));
|
||||
}
|
||||
|
||||
export function ReadingProgressButton({ mangaSlug, chapters }: Props) {
|
||||
const [lastRead, setLastRead] = useState<number | null>(null);
|
||||
const [progress, setProgress] = useState<ReadingProgress | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
setLastRead(readLastReadChapter(mangaSlug));
|
||||
setProgress(readProgress(mangaSlug));
|
||||
}, [mangaSlug]);
|
||||
|
||||
if (chapters.length === 0) return null;
|
||||
const first = chapters[0];
|
||||
const resumeChapter =
|
||||
lastRead !== null ? chapters.find((c) => c.number === lastRead) : null;
|
||||
progress !== null
|
||||
? chapters.find((c) => c.number === progress.chapter)
|
||||
: null;
|
||||
const target = resumeChapter ?? first;
|
||||
|
||||
return (
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user