'use client'; import React, {useContext, useEffect, useState} from 'react'; import {useParams, useRouter} from '@/lib/navigation'; import {SessionContext, SessionContextProps} from '@/context/SessionContext'; import {LangContext, LangContextProps} from '@/context/LangContext'; import {AlertContext, AlertContextProps} from '@/context/AlertContext'; import {ChapterContext, ChapterContextProps} from '@/context/ChapterContext'; import {apiGet} from '@/lib/api/client'; import {isDesktop} from '@/lib/configs'; import * as tauri from '@/lib/tauri'; import OfflineContext, {OfflineContextType} from '@/context/OfflineContext'; import {BookContext, BookContextProps} from '@/context/BookContext'; import {ChapterProps} from '@/lib/types/chapter'; import {useTranslations} from '@/lib/i18n'; import NoBookHome from '@/components/editor/NoBookHome'; export default function BookPage() { const params: { bookId: string } = useParams<{ bookId: string }>(); const router = useRouter(); const {session}: SessionContextProps = useContext(SessionContext); const {lang}: LangContextProps = useContext(LangContext); const {errorMessage}: AlertContextProps = useContext(AlertContext); const {setChapter}: ChapterContextProps = useContext(ChapterContext); const {book}: BookContextProps = useContext(BookContext); const {isCurrentlyOffline}: OfflineContextType = useContext(OfflineContext); const t = useTranslations(); const [isRedirecting, setIsRedirecting] = useState(true); useEffect((): void => { if (session.accessToken && params.bookId) { redirectToLastChapter().then(); } }, [session.accessToken, params.bookId]); async function redirectToLastChapter(): Promise { try { let response: ChapterProps | null; if (isDesktop && (isCurrentlyOffline() || book?.localBook)) { response = await tauri.getLastChapter(params.bookId); } else { response = await apiGet( 'chapter/last-chapter', session.accessToken, lang, {bookid: params.bookId} ); } if (response) { setChapter(response); router.replace(`/book/${params.bookId}/chapter/${response.chapterId}`); return; } setIsRedirecting(false); } catch (e: unknown) { if (e instanceof Error) { errorMessage(e.message); } else { errorMessage(t('homePage.errors.lastChapterError')); } setIsRedirecting(false); } } if (isRedirecting) { return null; } return ; }