fix inifity flip
This commit is contained in:
@@ -1,4 +1,4 @@
|
||||
import { type FC, useRef, useCallback, useState } from 'react';
|
||||
import { type FC, useRef, useCallback, useState, useEffect } from 'react';
|
||||
import HTMLFlipBook from 'react-pageflip';
|
||||
import { type PageData } from '../types';
|
||||
import BookPage from './BookPage';
|
||||
@@ -30,18 +30,41 @@ const BookViewer: FC<BookViewerProps> = ({ pages }) => {
|
||||
const bookRef = useRef<FlipBookInstance | null>(null);
|
||||
const [currentPage, setCurrentPage] = useState(0);
|
||||
|
||||
// اطمینان از اینکه currentPage همیشه در محدوده معتبر است
|
||||
useEffect(() => {
|
||||
if (currentPage < 0) {
|
||||
setCurrentPage(0);
|
||||
} else if (currentPage >= pages.length) {
|
||||
setCurrentPage(pages.length - 1);
|
||||
}
|
||||
}, [currentPage, pages.length]);
|
||||
|
||||
const handlePageFlip = useCallback((e: FlipEvent) => {
|
||||
const pageNum = e.data;
|
||||
// react-pageflip شماره صفحه را به صورت 0-based برمیگرداند
|
||||
// اما باید مطمئن شویم که در محدوده معتبر است
|
||||
let pageNum = e.data;
|
||||
|
||||
// اگر pageNum منفی است یا بزرگتر از تعداد صفحات، آن را محدود میکنیم
|
||||
if (pageNum < 0) {
|
||||
pageNum = 0;
|
||||
} else if (pageNum >= pages.length) {
|
||||
pageNum = pages.length - 1;
|
||||
}
|
||||
|
||||
setCurrentPage(pageNum);
|
||||
}, []);
|
||||
}, [pages.length]);
|
||||
|
||||
const goToNextPage = useCallback(() => {
|
||||
if (currentPage < pages.length - 1) {
|
||||
bookRef.current?.pageFlip()?.flipNext();
|
||||
}, []);
|
||||
}
|
||||
}, [currentPage, pages.length]);
|
||||
|
||||
const goToPrevPage = useCallback(() => {
|
||||
if (currentPage > 0) {
|
||||
bookRef.current?.pageFlip()?.flipPrev();
|
||||
}, []);
|
||||
}
|
||||
}, [currentPage]);
|
||||
|
||||
return (
|
||||
<div className="flex flex-col items-center gap-4 md:gap-6 w-full h-full" dir="rtl">
|
||||
@@ -106,7 +129,7 @@ const BookViewer: FC<BookViewerProps> = ({ pages }) => {
|
||||
{/* شماره صفحه */}
|
||||
<div className="flex items-center gap-2 min-w-[100px] md:min-w-[120px] justify-center">
|
||||
<span className="text-xs md:text-sm text-gray-600">
|
||||
صفحه {currentPage + 1} از {pages.length}
|
||||
صفحه {Math.min(currentPage + 1, pages.length)} از {pages.length}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
|
||||
Reference in New Issue
Block a user