feat: local store read progress for later sync

This commit is contained in:
Julien Froidefond
2025-03-01 11:37:34 +01:00
parent 13492cea84
commit a3d0094cec
11 changed files with 93 additions and 43 deletions

View File

@@ -4,6 +4,7 @@ import { getErrorMessage } from "@/utils/errors";
import { LibraryService } from "@/lib/services/library.service";
import { HomeService } from "@/lib/services/home.service";
import { SeriesService } from "@/lib/services/series.service";
import { revalidatePath } from "next/cache";
export async function POST(
request: Request,
@@ -13,13 +14,17 @@ export async function POST(
const { libraryId, seriesId } = params;
await HomeService.invalidateHomeCache();
revalidatePath("/");
if (libraryId) {
await LibraryService.invalidateLibrarySeriesCache(libraryId);
revalidatePath(`/library/${libraryId}`);
}
if (seriesId) {
await SeriesService.invalidateSeriesBooksCache(seriesId);
await SeriesService.invalidateSeriesCache(seriesId);
revalidatePath(`/series/${seriesId}`);
}
return NextResponse.json({ message: "🧹 Cache vidé avec succès" });

View File

@@ -4,6 +4,8 @@ import { ChevronLeft, ChevronRight } from "lucide-react";
import { useRef, useState } from "react";
import { Cover } from "@/components/ui/cover";
import { useRouter } from "next/navigation";
import { ClientOfflineBookService } from "@/lib/services/client-offlinebook.service";
import { KomgaBook } from "@/types/komga";
interface BaseItem {
id: string;
@@ -18,12 +20,12 @@ interface OptimizedSeries extends BaseItem {
}
interface OptimizedBook extends BaseItem {
readProgress:{
page: number
}
readProgress: {
page: number;
};
media: {
pagesCount: number;
}
};
metadata: {
title: string;
number?: string;
@@ -124,19 +126,27 @@ function MediaCard({ item, onClick }: MediaCardProps) {
onClick={onClick}
className="flex-shrink-0 w-[200px] relative flex flex-col rounded-lg border bg-card text-card-foreground shadow-sm hover:bg-accent hover:text-accent-foreground transition-colors overflow-hidden cursor-pointer"
>
{/* Image de couverture */}
<div className="relative aspect-[2/3] bg-muted">
<Cover
type={isSeries ? "series" : "book"}
id={item.id}
alt={`Couverture de ${title}`}
quality={100}
readBooks={isSeries ? item.booksReadCount : undefined}
totalBooks={isSeries ? item.booksCount : undefined}
isCompleted={isSeries ? item.booksCount === item.booksReadCount : undefined}
currentPage={isSeries ? undefined : item.readProgress?.page}
totalPages={isSeries ? undefined : item.media?.pagesCount}
/>
{isSeries ? (
<Cover
type={isSeries ? "series" : "book"}
id={item.id}
alt={`Couverture de ${title}`}
quality={100}
readBooks={item.booksReadCount}
totalBooks={item.booksCount}
isCompleted={item.booksCount === item.booksReadCount}
/>
) : (
<Cover
type="book"
id={item.id}
alt={`Couverture de ${title}`}
quality={100}
currentPage={ClientOfflineBookService.getCurrentPage(item as KomgaBook)}
totalPages={item.media?.pagesCount}
/>
)}
{/* Overlay avec les informations au survol */}
<div className="absolute inset-0 bg-black/60 opacity-0 hover:opacity-100 transition-opacity duration-200 flex flex-col justify-end p-3">
<h3 className="font-medium text-sm text-white line-clamp-2">{title}</h3>

View File

@@ -3,6 +3,7 @@
import { KomgaBook } from "@/types/komga";
import { BookReader } from "./BookReader";
import { useRouter } from "next/navigation";
import { ClientOfflineBookService } from "@/lib/services/client-offlinebook.service";
interface ClientBookWrapperProps {
book: KomgaBook;
@@ -12,10 +13,11 @@ interface ClientBookWrapperProps {
export function ClientBookWrapper({ book, pages }: ClientBookWrapperProps) {
const router = useRouter();
const handleCloseReader = () => {
const handleCloseReader = (currentPage: number) => {
fetch(`/api/komga/cache/clear/${book.libraryId}/${book.seriesId}`, {
method: "POST",
});
ClientOfflineBookService.setCurrentPage(book, currentPage);
router.back();
};

View File

@@ -101,7 +101,7 @@ export const ControlButtons = ({
<button
onClick={(e) => {
e.stopPropagation();
onClose();
onClose(currentPage);
}}
className={cn(
"absolute top-4 right-4 p-2 rounded-full bg-background/50 hover:bg-background/80 transition-all duration-300 z-30",

View File

@@ -1,11 +1,12 @@
import { useState, useCallback, useEffect, useRef } from "react";
import { KomgaBook } from "@/types/komga";
import { ClientOfflineBookService } from "@/lib/services/client-offlinebook.service";
interface UsePageNavigationProps {
book: KomgaBook;
pages: number[];
isDoublePage: boolean;
onClose?: () => void;
onClose?: (currentPage: number) => void;
direction: "ltr" | "rtl";
}
@@ -16,7 +17,7 @@ export const usePageNavigation = ({
onClose,
direction,
}: UsePageNavigationProps) => {
const [currentPage, setCurrentPage] = useState(book.readProgress?.page || 1);
const [currentPage, setCurrentPage] = useState(ClientOfflineBookService.getCurrentPage(book));
const [isLoading, setIsLoading] = useState(true);
const [secondPageLoading, setSecondPageLoading] = useState(true);
const [zoomLevel, setZoomLevel] = useState(1);
@@ -37,6 +38,7 @@ export const usePageNavigation = ({
const syncReadProgress = useCallback(
async (page: number) => {
try {
ClientOfflineBookService.setCurrentPage(book, page);
const completed = page === pages.length;
await fetch(`/api/komga/books/${book.id}/read-progress`, {
method: "PATCH",
@@ -239,7 +241,7 @@ export const usePageNavigation = ({
}
} else if (e.key === "Escape" && onClose) {
e.preventDefault();
onClose();
onClose(currentPage);
}
};
@@ -269,6 +271,7 @@ export const usePageNavigation = ({
if (timeoutRef.current) {
clearTimeout(timeoutRef.current);
syncReadProgress(currentPageRef.current);
ClientOfflineBookService.removeCurrentPage(book);
}
};
}, [syncReadProgress]);

View File

@@ -12,7 +12,7 @@ export interface PageCache {
export interface BookReaderProps {
book: KomgaBook;
pages: number[];
onClose?: () => void;
onClose?: (currentPage: number) => void;
}
export interface ThumbnailProps {
@@ -39,7 +39,7 @@ export interface ControlButtonsProps {
onPreviousPage: () => void;
onNextPage: () => void;
onPageChange: (page: number) => void;
onClose?: () => void;
onClose?: (currentPage: number) => void;
currentPage: number;
totalPages: number;
isDoublePage: boolean;

View File

@@ -8,6 +8,7 @@ import { MarkAsUnreadButton } from "@/components/ui/mark-as-unread-button";
import { BookOfflineButton } from "@/components/ui/book-offline-button";
import { useState, useEffect } from "react";
import { useTranslate } from "@/hooks/useTranslate";
import { ClientOfflineBookService } from "@/lib/services/client-offlinebook.service";
interface BookGridProps {
books: KomgaBook[];
@@ -31,10 +32,12 @@ const getReadingStatusInfo = (book: KomgaBook, t: (key: string, options?: any) =
};
}
if (book.readProgress.page > 0) {
const currentPage = ClientOfflineBookService.getCurrentPage(book);
if (currentPage > 0) {
return {
label: t("books.status.progress", {
current: book.readProgress.page,
current: currentPage,
total: book.media.pagesCount,
}),
className: "bg-blue-500/10 text-blue-500",
@@ -102,7 +105,8 @@ export function BookGrid({ books, onBookClick }: BookGridProps) {
{localBooks.map((book) => {
const statusInfo = getReadingStatusInfo(book, t);
const isRead = book.readProgress?.completed || false;
const currentPage = book.readProgress?.page || 0;
const hasReadProgress = book.readProgress !== null;
const currentPage = ClientOfflineBookService.getCurrentPage(book);
return (
<div
@@ -138,10 +142,9 @@ export function BookGrid({ books, onBookClick }: BookGridProps) {
className="bg-white/90 hover:bg-white text-black shadow-sm"
/>
)}
{isRead && (
{hasReadProgress && (
<MarkAsUnreadButton
bookId={book.id}
isRead={isRead}
onSuccess={() => handleMarkAsUnread(book.id)}
className="bg-white/90 hover:bg-white text-black shadow-sm"
/>

View File

@@ -44,7 +44,7 @@ export function Cover(props: CoverProps) {
} = props;
const imageUrl = getImageUrl(type, id);
const showProgress = () => {
if (type === "book") {
const { currentPage, totalPages } = props;
@@ -52,7 +52,7 @@ export function Cover(props: CoverProps) {
<ProgressBar progress={currentPage} total={totalPages} type="book" />
) : null;
}
if (type === "series") {
const { readBooks, totalBooks } = props;
return readBooks && totalBooks && readBooks > 0 && !isCompleted ? (

View File

@@ -1,8 +1,9 @@
"use client";
import { CheckCircle2 } from "lucide-react";
import { BookCheck } from "lucide-react";
import { Button } from "./button";
import { useToast } from "./use-toast";
import { ClientOfflineBookService } from "@/lib/services/client-offlinebook.service";
interface MarkAsReadButtonProps {
bookId: string;
@@ -24,6 +25,7 @@ export function MarkAsReadButton({
const handleMarkAsRead = async (e: React.MouseEvent) => {
e.stopPropagation(); // Empêcher la propagation au parent
try {
ClientOfflineBookService.removeCurrentPageById(bookId);
const response = await fetch(`/api/komga/books/${bookId}/read-progress`, {
method: "PATCH",
headers: {
@@ -60,7 +62,7 @@ export function MarkAsReadButton({
disabled={isRead}
aria-label="Marquer comme lu"
>
<CheckCircle2 className="h-5 w-5" />
<BookCheck className="h-5 w-5" />
</Button>
);
}

View File

@@ -1,27 +1,22 @@
"use client";
import { XCircle } from "lucide-react";
import { BookX } from "lucide-react";
import { Button } from "./button";
import { useToast } from "./use-toast";
import { ClientOfflineBookService } from "@/lib/services/client-offlinebook.service";
interface MarkAsUnreadButtonProps {
bookId: string;
isRead: boolean;
onSuccess?: () => void;
className?: string;
}
export function MarkAsUnreadButton({
bookId,
isRead = false,
onSuccess,
className,
}: MarkAsUnreadButtonProps) {
export function MarkAsUnreadButton({ bookId, onSuccess, className }: MarkAsUnreadButtonProps) {
const { toast } = useToast();
const handleMarkAsUnread = async (e: React.MouseEvent) => {
e.stopPropagation(); // Empêcher la propagation au parent
try {
ClientOfflineBookService.removeCurrentPageById(bookId);
const response = await fetch(`/api/komga/books/${bookId}/read-progress`, {
method: "DELETE",
});
@@ -51,10 +46,9 @@ export function MarkAsUnreadButton({
size="icon"
onClick={handleMarkAsUnread}
className={`h-8 w-8 p-0 rounded-br-lg rounded-tl-lg ${className}`}
disabled={!isRead}
aria-label="Marquer comme non lu"
>
<XCircle className="h-5 w-5" />
<BookX className="h-5 w-5" />
</Button>
);
}

View File

@@ -0,0 +1,31 @@
import { KomgaBook } from "@/types/komga";
export class ClientOfflineBookService {
static setCurrentPage(book: KomgaBook, page: number) {
localStorage.setItem(`${book.id}-page`, page.toString());
}
static getCurrentPage(book: KomgaBook) {
const readProgressPage = book.readProgress?.page || 0;
if (typeof localStorage !== "undefined") {
const cPageLS = localStorage.getItem(`${book.id}-page`) || "0";
const currentPage = parseInt(cPageLS);
if (currentPage < readProgressPage) {
return readProgressPage;
}
return currentPage;
} else {
return readProgressPage;
}
}
static removeCurrentPage(book: KomgaBook) {
localStorage.removeItem(`${book.id}-page`);
}
static removeCurrentPageById(bookId: string) {
localStorage.removeItem(`${bookId}-page`);
}
}