Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 0 additions & 11 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

44 changes: 27 additions & 17 deletions src/components/Context/LibraryContext.tsx
Original file line number Diff line number Diff line change
@@ -1,18 +1,17 @@
// src/components/Context/LibraryContext.tsx
import React, {
createContext,
useContext,
useMemo,
useCallback,
useState,
useEffect,
} from 'react';

// Import existing settings hook
import {
useLibrarySettings,
LibrarySettings,
} from '@hooks/persisted/useSettings';
import { NovelInfo } from '@database/types';
import { DBNovelInfo } from '@database/types';
import {
ExtendedCategory,
useFetchCategories,
Expand All @@ -21,9 +20,8 @@ import { useLibraryNovels } from '@hooks/persisted/library/useLibraryNovels';
import { useLibraryActions } from '@hooks/persisted/library/useLibraryActions';
import ServiceManager, { QueuedBackgroundTask } from '@services/ServiceManager';

// Define the shape of the context value
type LibraryContextType = {
library: NovelInfo[];
library: DBNovelInfo[];
categories: ExtendedCategory[];
isLoading: boolean;
settings: LibrarySettings;
Expand All @@ -36,8 +34,7 @@ type LibraryContextType = {
setCategories: React.Dispatch<React.SetStateAction<ExtendedCategory[]>>;
};

const defaultValue = {} as LibraryContextType;
const LibraryContext = createContext<LibraryContextType>(defaultValue);
const LibraryContext = createContext<LibraryContextType | null>(null);

interface LibraryContextProviderProps {
children: React.ReactNode;
Expand All @@ -46,18 +43,23 @@ interface LibraryContextProviderProps {
export function LibraryContextProvider({
children,
}: LibraryContextProviderProps) {
const [searchText, setSearchText] = useState('');
const settings = useLibrarySettings();

const { categories, categoriesLoading, refreshCategories, setCategories } =
useFetchCategories();
const { novels, novelsLoading, refetchNovels, refetchNovel } =
useLibraryNovels({
sortOrder: settings.sortOrder,
filter: settings.filter,
searchText: searchText,
downloadedOnlyMode: settings.downloadedOnlyMode,
});
const {
novels,
novelsLoading,
refetchNovels,
refetchNovel,
searchText,
setSearchText,
clearSearchbar,
} = useLibraryNovels({
sortOrder: settings.sortOrder,
filter: settings.filter,
downloadedOnlyMode: settings.downloadedOnlyMode,
});

const { switchNovelToLibrary } = useLibraryActions({
refreshCategories,
Expand Down Expand Up @@ -89,7 +91,12 @@ export function LibraryContextProvider({
},
[refetchLibrary, refetchNovel],
);
ServiceManager.manager.addCompletionListener(handleQueueChange);
useEffect(() => {
ServiceManager.manager.addCompletionListener(handleQueueChange);
return () => {
ServiceManager.manager.removeCompletionListener(handleQueueChange);
};
}, [handleQueueChange]);

const contextValue = useMemo(
() => ({
Expand All @@ -104,6 +111,7 @@ export function LibraryContextProvider({
setSearchText,
refreshCategories,
setCategories,
clearSearchbar,
}),
[
novels,
Expand All @@ -114,8 +122,10 @@ export function LibraryContextProvider({
refetchLibrary,
novelInLibrary,
switchNovelToLibrary,
setSearchText,
refreshCategories,
setCategories,
clearSearchbar,
],
);

Expand All @@ -128,7 +138,7 @@ export function LibraryContextProvider({

export const useLibraryContext = (): LibraryContextType => {
const context = useContext(LibraryContext);
if (context === defaultValue) {
if (context === null) {
throw new Error(
'useLibraryContext must be used within a LibraryContextProvider',
);
Expand Down
8 changes: 6 additions & 2 deletions src/database/queries/ChapterQueries.ts
Original file line number Diff line number Diff line change
Expand Up @@ -248,9 +248,13 @@ export const getPageChapters = (
);
};

export const getChapterCount = (novelId: number, page: string = '1') =>
export const getChapterCount = (
novelId: number,
page: string = '1',
filter: string = '',
) =>
db.getFirstSync<{ 'COUNT(*)': number }>(
'SELECT COUNT(*) FROM Chapter WHERE novelId = ? AND page = ?',
`SELECT COUNT(*) FROM Chapter WHERE novelId = ? AND page = ? ${filter}`,
novelId,
page,
)?.['COUNT(*)'] ?? 0;
Expand Down
4 changes: 3 additions & 1 deletion src/database/queries/HistoryQueries.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,8 @@ export const deleteChapterHistory = (chapterId: number) =>
db.runAsync('UPDATE Chapter SET readTime = NULL WHERE id = ?', chapterId);

export const deleteAllHistory = async () => {
await db.execAsync('UPDATE Chapter SET readTime = NULL');
await db.execAsync(
'UPDATE Chapter SET readTime = NULL WHERE readTime IS NOT NULL',
);
showToast(getString('historyScreen.deleted'));
};
43 changes: 10 additions & 33 deletions src/database/queries/LibraryQueries.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,18 @@
import { LibraryFilter } from '@screens/library/constants/constants';
import { LibraryNovelInfo, NovelInfo } from '../types';
import { DBNovelInfo, LibraryNovelInfo } from '../types';
import { getAllSync } from '../utils/helpers';

export const getLibraryNovelsFromDb = ({
sortOrder,
filter,
searchText,
searchText = '',
downloadedOnlyMode,
}: {
sortOrder?: string;
filter?: string;
searchText?: string;
downloadedOnlyMode?: boolean;
}): NovelInfo[] => {
}): DBNovelInfo[] => {
let query = 'SELECT * FROM Novel WHERE inLibrary = 1';

if (filter) {
Expand All @@ -23,43 +23,20 @@ export const getLibraryNovelsFromDb = ({
}

if (searchText) {
if (!searchText.startsWith('%')) searchText = `%${searchText}`;
if (!searchText.endsWith('%')) searchText = `${searchText}%`;
query += ' AND name LIKE ? ';
}

if (sortOrder) {
query += ` ORDER BY ${sortOrder} `;
}
return getAllSync<NovelInfo>([query, [searchText ?? '']]);

return getAllSync<DBNovelInfo>([query, [searchText]]);
};

const getLibraryWithCategoryQuery = 'SELECT * FROM Novel WHERE inLibrary = 1';
// `
// SELECT *
// FROM
// (
// SELECT NIL.*, chaptersUnread, chaptersDownloaded, lastReadAt, lastUpdatedAt
// FROM
// (
// SELECT
// Novel.*,
// category,
// categoryId
// FROM
// Novel LEFT JOIN (
// SELECT NovelId, name as category, categoryId FROM (NovelCategory JOIN Category ON NovelCategory.categoryId = Category.id)
// ) as NC ON Novel.id = NC.novelId
// WHERE inLibrary = 1
// ) as NIL
// LEFT JOIN
// (
// SELECT
// SUM(unread) as chaptersUnread, SUM(isDownloaded) as chaptersDownloaded,
// novelId, MAX(readTime) as lastReadAt, MAX(updatedTime) as lastUpdatedAt
// FROM Chapter
// GROUP BY novelId
// ) as C ON NIL.id = C.novelId
// ) WHERE 1 = 1
// `;
const getLibraryWithCategoryQuery =
'SELECT * FROM NovelCategory NC JOIN Novel N on N.id = NC.novelId WHERE 1=1';

export const getLibraryWithCategory = ({
filter,
Expand All @@ -76,7 +53,7 @@ export const getLibraryWithCategory = ({
const preparedArgument: (string | number | null)[] = [];

if (filter) {
// query += ` AND ${filter} `;
query += ` AND ${filter} `;
}
if (downloadedOnlyMode) {
query += ' ' + LibraryFilter.DownloadedOnly;
Expand Down
41 changes: 29 additions & 12 deletions src/hooks/persisted/library/useLibraryNovels.ts
Original file line number Diff line number Diff line change
@@ -1,28 +1,28 @@
// src/hooks/library/useLibraryNovels.ts
import { useCallback, useState } from 'react';
import { useCallback, useMemo, useState } from 'react';
import { useFocusEffect } from '@react-navigation/native';
import { getLibraryNovelsFromDb } from '@database/queries/LibraryQueries';
import { NovelInfo } from '@database/types';
import { DBNovelInfo } from '@database/types';
import {
LibraryFilter,
LibrarySortOrder,
} from '../../../screens/library/constants/constants';
import { useSearch } from '@hooks';

interface UseLibraryNovelsOptions {
sortOrder?: LibrarySortOrder;
filter?: LibraryFilter;
searchText: string;
downloadedOnlyMode?: boolean;
}

export const useLibraryNovels = ({
sortOrder,
filter,
searchText,
downloadedOnlyMode = false,
}: UseLibraryNovelsOptions) => {
const [novels, setNovels] = useState<NovelInfo[]>([]);
const [novels, setNovels] = useState<DBNovelInfo[]>([]);
const [novelsLoading, setNovelsLoading] = useState(true);
const { searchText, setSearchText, clearSearchbar } = useSearch();

const fetchNovels = useCallback(async () => {
setNovelsLoading(true);
Expand All @@ -48,13 +48,16 @@ export const useLibraryNovels = ({
const fetchedNovels = await getLibraryNovelsFromDb({
filter: `id = ${novelId}`,
});

setNovels(prevNovels => {
const novelIndex = prevNovels.findIndex(novel => novel?.id === novelId);

if (novelIndex !== -1) {
prevNovels[novelIndex] = fetchedNovels[0];
}
return prevNovels;

// create a new array, so the state is updated
return [...prevNovels];
});
} catch (error) {
// eslint-disable-next-line no-console
Expand All @@ -70,10 +73,24 @@ export const useLibraryNovels = ({
}, [fetchNovels]),
);

return {
novels,
novelsLoading,
refetchNovels: fetchNovels,
refetchNovel: fetchNovel,
};
return useMemo(
() => ({
novels,
novelsLoading,
refetchNovels: fetchNovels,
refetchNovel: fetchNovel,
searchText,
setSearchText,
clearSearchbar,
}),
[
novels,
novelsLoading,
fetchNovels,
fetchNovel,
searchText,
setSearchText,
clearSearchbar,
],
);
};
6 changes: 3 additions & 3 deletions src/hooks/persisted/useHistory.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,9 +37,9 @@ const useHistory = () => {
.catch((err: Error) => setError(err.message))
.finally(() => setIsLoading(false));

const clearAllHistory = () => {
deleteAllHistory();
getHistory();
const clearAllHistory = async () => {
setHistory([]);
await deleteAllHistory();
};

const removeChapterFromHistory = async (chapterId: number) => {
Expand Down
Loading