aboutsummaryrefslogtreecommitdiffhomepage
path: root/src/client/atoms/decks.ts
blob: d62227c2c7216d488f079885716a5fd17adb60d6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
import { atomFamily } from "jotai-family";
import { atomWithSuspenseQuery } from "jotai-tanstack-query";
import { getEndOfStudyDayBoundary } from "../../shared/date";
import { CardState, db, type LocalDeck } from "../db";
import { localDeckRepository } from "../db/repositories";
import { ensureBootstrap } from "./sync";

export interface Deck {
	id: string;
	name: string;
	description: string | null;
	defaultNoteTypeId: string | null;
	dueCardCount: number;
	newCardCount: number;
	totalCardCount: number;
	reviewCardCount: number;
	createdAt: string;
	updatedAt: string;
}

async function loadCurrentUserId(): Promise<string | null> {
	const stored = localStorage.getItem("kioku_user");
	if (!stored) return null;
	try {
		const user = JSON.parse(stored) as { id?: string } | null;
		return user?.id ?? null;
	} catch {
		return null;
	}
}

interface DeckCardCounts {
	dueCardCount: number;
	newCardCount: number;
	totalCardCount: number;
	reviewCardCount: number;
}

async function computeDeckCounts(
	deckId: string,
	dueBoundary: Date,
): Promise<DeckCardCounts> {
	const cards = await db.cards.where("deckId").equals(deckId).toArray();
	let due = 0;
	let news = 0;
	let total = 0;
	let review = 0;
	for (const card of cards) {
		if (card.deletedAt !== null) continue;
		total++;
		if (card.due < dueBoundary) due++;
		if (card.state === CardState.New) news++;
		if (card.state === CardState.Review) review++;
	}
	return {
		dueCardCount: due,
		newCardCount: news,
		totalCardCount: total,
		reviewCardCount: review,
	};
}

function localDeckToView(deck: LocalDeck, counts: DeckCardCounts): Deck {
	return {
		id: deck.id,
		name: deck.name,
		description: deck.description,
		defaultNoteTypeId: deck.defaultNoteTypeId,
		dueCardCount: counts.dueCardCount,
		newCardCount: counts.newCardCount,
		totalCardCount: counts.totalCardCount,
		reviewCardCount: counts.reviewCardCount,
		createdAt: deck.createdAt.toISOString(),
		updatedAt: deck.updatedAt.toISOString(),
	};
}

async function loadDecksFromIndexedDb(): Promise<Deck[]> {
	const userId = await loadCurrentUserId();
	if (!userId) return [];
	const decks = await localDeckRepository.findByUserId(userId);
	const boundary = getEndOfStudyDayBoundary(new Date());
	decks.sort((a, b) => a.createdAt.getTime() - b.createdAt.getTime());
	return Promise.all(
		decks.map(async (deck) => {
			const counts = await computeDeckCounts(deck.id, boundary);
			return localDeckToView(deck, counts);
		}),
	);
}

// =====================
// Decks List - Suspense-compatible, IndexedDB-first
// =====================

export const decksAtom = atomWithSuspenseQuery(() => ({
	queryKey: ["decks"],
	queryFn: async (): Promise<Deck[]> => {
		const decks = await loadDecksFromIndexedDb();
		if (decks.length > 0) {
			// Stale-while-revalidate: kick a background pull so the next
			// invalidation reflects upstream changes.
			ensureBootstrap();
			return decks;
		}
		// IndexedDB is empty — wait for the initial pull to populate it
		// before deciding there really are no decks.
		await ensureBootstrap();
		return loadDecksFromIndexedDb();
	},
}));

// =====================
// Single Deck by ID - Suspense-compatible, IndexedDB-first
// =====================

async function loadDeckById(deckId: string): Promise<Deck | null> {
	const deck = await localDeckRepository.findById(deckId);
	if (!deck || deck.deletedAt !== null) return null;
	const boundary = getEndOfStudyDayBoundary(new Date());
	const counts = await computeDeckCounts(deck.id, boundary);
	return localDeckToView(deck, counts);
}

export const deckByIdAtomFamily = atomFamily((deckId: string) =>
	atomWithSuspenseQuery(() => ({
		queryKey: ["decks", deckId],
		queryFn: async (): Promise<Deck> => {
			let deck = await loadDeckById(deckId);
			if (deck) {
				ensureBootstrap();
				return deck;
			}
			await ensureBootstrap();
			deck = await loadDeckById(deckId);
			if (!deck) {
				throw new Error(`Deck not found: ${deckId}`);
			}
			return deck;
		},
	})),
);