@ginhotaru282/reader 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (81) hide show
  1. package/.dockerignore +5 -0
  2. package/.gitattributes +2 -0
  3. package/Dockerfile +26 -0
  4. package/README.md +36 -0
  5. package/eslint.config.mjs +18 -0
  6. package/next.config.ts +8 -0
  7. package/package.json +31 -0
  8. package/postcss.config.mjs +7 -0
  9. package/public/file.svg +1 -0
  10. package/public/globe.svg +1 -0
  11. package/public/window.svg +1 -0
  12. package/scripts/obfuscate-build.mjs +77 -0
  13. package/src/app/(reader)/[id]/page.tsx +40 -0
  14. package/src/app/(reader)/layout.tsx +38 -0
  15. package/src/app/api/bookmark/[id]/toggle/route.ts +41 -0
  16. package/src/app/api/chapter/[id]/audio/route.ts +37 -0
  17. package/src/app/api/chapter/[id]/audio-status/route.ts +36 -0
  18. package/src/app/api/chapter/[id]/unlock/route.ts +49 -0
  19. package/src/app/api/comment/story/[id]/route.ts +48 -0
  20. package/src/app/api/reading-progress/[storyId]/route.ts +26 -0
  21. package/src/app/api/reading-progress/sync/route.ts +38 -0
  22. package/src/app/api/story/[id]/combo-unlock/route.ts +47 -0
  23. package/src/app/globals.css +26 -0
  24. package/src/app/icon.png +0 -0
  25. package/src/app/layout.tsx +35 -0
  26. package/src/app/page.tsx +3 -0
  27. package/src/assets/fonts/Lora-Variable.ttf +0 -0
  28. package/src/assets/fonts/PlusJakartaSans-Variable.ttf +0 -0
  29. package/src/components/ssr/Skeleton/index.module.css +22 -0
  30. package/src/components/ssr/Skeleton/index.tsx +38 -0
  31. package/src/modules/reader/ReaderView.tsx +48 -0
  32. package/src/modules/reader/api/backend-data.ts +231 -0
  33. package/src/modules/reader/api/client-audio-api.ts +33 -0
  34. package/src/modules/reader/api/client-bookmark-api.ts +21 -0
  35. package/src/modules/reader/api/client-comment-api.ts +31 -0
  36. package/src/modules/reader/api/client-progress-api.ts +36 -0
  37. package/src/modules/reader/api/client-purchase-api.ts +64 -0
  38. package/src/modules/reader/api/get-reader-page-data.ts +48 -0
  39. package/src/modules/reader/api/types.ts +47 -0
  40. package/src/modules/reader/components/AudioPlayerBar.tsx +299 -0
  41. package/src/modules/reader/components/AutoScrollDrawer.tsx +58 -0
  42. package/src/modules/reader/components/ChapterBottomNav.tsx +16 -0
  43. package/src/modules/reader/components/ChapterContent.tsx +43 -0
  44. package/src/modules/reader/components/ChapterListDrawer.tsx +84 -0
  45. package/src/modules/reader/components/ChapterNav.tsx +20 -0
  46. package/src/modules/reader/components/ChapterSelect.tsx +24 -0
  47. package/src/modules/reader/components/ChapterWatermark.tsx +53 -0
  48. package/src/modules/reader/components/CommentSection.tsx +156 -0
  49. package/src/modules/reader/components/LockedChapterGate.tsx +37 -0
  50. package/src/modules/reader/components/MobileDock.tsx +62 -0
  51. package/src/modules/reader/components/NavButton.tsx +22 -0
  52. package/src/modules/reader/components/ReaderBreadcrumbs.tsx +20 -0
  53. package/src/modules/reader/components/ReaderChrome.tsx +206 -0
  54. package/src/modules/reader/components/ReaderToolbar.tsx +52 -0
  55. package/src/modules/reader/components/ReaderTopbar.tsx +31 -0
  56. package/src/modules/reader/components/SettingsPanel.tsx +158 -0
  57. package/src/modules/reader/components/Toast.tsx +15 -0
  58. package/src/modules/reader/constants/index.ts +22 -0
  59. package/src/modules/reader/hooks/useAudioPlayer.ts +633 -0
  60. package/src/modules/reader/hooks/useAutoScroll.ts +31 -0
  61. package/src/modules/reader/hooks/useBookmark.ts +32 -0
  62. package/src/modules/reader/hooks/useComments.ts +86 -0
  63. package/src/modules/reader/hooks/useContentProtection.ts +81 -0
  64. package/src/modules/reader/hooks/useDrawers.ts +27 -0
  65. package/src/modules/reader/hooks/useFullscreen.ts +24 -0
  66. package/src/modules/reader/hooks/usePrefs.ts +66 -0
  67. package/src/modules/reader/hooks/useReaderView.ts +190 -0
  68. package/src/modules/reader/hooks/useReadingProgress.ts +95 -0
  69. package/src/modules/reader/hooks/useScrollVisibility.ts +44 -0
  70. package/src/modules/reader/hooks/useToast.ts +19 -0
  71. package/src/modules/reader/hooks/useUnlock.ts +59 -0
  72. package/src/modules/reader/styles/reader.module.css +1986 -0
  73. package/src/modules/reader/types.ts +145 -0
  74. package/src/modules/reader/utils/affiliate.ts +43 -0
  75. package/src/modules/reader/utils/chapter-label.ts +8 -0
  76. package/src/modules/reader/utils/format-date.ts +10 -0
  77. package/src/modules/reader/utils/obfuscate-content.ts +70 -0
  78. package/src/modules/reader/utils/silent-wav.ts +33 -0
  79. package/src/modules/reader/utils/tiktok-tts.ts +251 -0
  80. package/src/modules/reader/utils/word-svg.ts +132 -0
  81. package/tsconfig.json +34 -0
@@ -0,0 +1,633 @@
1
+ "use client";
2
+
3
+ import { useCallback, useEffect, useRef, useState } from "react";
4
+ import { requestChapterAudio, getChapterAudioStatus } from "../api/client-audio-api";
5
+ import { generateTikTokTTS, TIKTOK_VOICES } from "../utils/tiktok-tts";
6
+ import { createSilentWav } from "../utils/silent-wav";
7
+
8
+ export type StudioAudioStatus = "idle" | "loading" | "generating" | "done" | "failed" | "error";
9
+
10
+ const DEFAULT_VOICE = "BV074_streaming";
11
+ const CONTINUOUS_PLAY_KEY = "reader_continuous_play";
12
+ const PLAYBACK_RATE_KEY = "reader_playback_rate";
13
+ const AUTOPLAY_NEXT_KEY = "reader_audio_autoplay_next";
14
+
15
+ // Ported from frontend/src/pages/ReaderPage.jsx's audio block: two audio
16
+ // elements are used in a double-buffer so the next TikTok-voiced paragraph
17
+ // can be pre-decoded while the current one is still playing, avoiding a gap
18
+ // between paragraphs. The "Studio" voice only ever uses audioRef1.
19
+ export function useAudioPlayer(
20
+ chapterId: string,
21
+ paragraphs: string[],
22
+ hasNext: boolean,
23
+ navigateToNextChapter: () => void
24
+ ) {
25
+ const [playerOpen, setPlayerOpen] = useState(false);
26
+ const [selectedVoice, setSelectedVoiceState] = useState(DEFAULT_VOICE);
27
+
28
+ // Studio (server-generated) voice state
29
+ const [audioStatus, setAudioStatus] = useState<StudioAudioStatus>("idle");
30
+ const [audioError, setAudioError] = useState<string | null>(null);
31
+ const [studioAudioUrl, setStudioAudioUrl] = useState<string | null>(null);
32
+ const studioCancelledRef = useRef(false);
33
+
34
+ // Shared playback state
35
+ const [isPlaying, setIsPlaying] = useState(false);
36
+ const [currentTime, setCurrentTime] = useState(0);
37
+ const [duration, setDuration] = useState(0);
38
+ const [volume, setVolume] = useState(1);
39
+ const [isMuted, setIsMuted] = useState(false);
40
+ const [playbackRate, setPlaybackRate] = useState(1.0);
41
+
42
+ // TikTok paragraph-by-paragraph state
43
+ const [currentParagraphIndex, setCurrentParagraphIndex] = useState(0);
44
+ const [isGeneratingParagraph, setIsGeneratingParagraph] = useState(false);
45
+ const [localProgress, setLocalProgress] = useState<number | null>(null);
46
+ // Mirrors paragraphUrlsRef's cache for whichever key is currently loaded
47
+ // into the active element — read during render (e.g. isPlayerDisabled), so
48
+ // it has to be state, not a ref read at render time.
49
+ const [loadedCacheKey, setLoadedCacheKey] = useState<string | null>(null);
50
+
51
+ const audioRef1 = useRef<HTMLAudioElement | null>(null);
52
+ const audioRef2 = useRef<HTMLAudioElement | null>(null);
53
+ const activeAudioRef = useRef<1 | 2>(1);
54
+ // Which paragraph index is currently loaded into each buffer slot — lets
55
+ // handleAudioEnded tell whether the preloaded (inactive) element already
56
+ // holds the *next* paragraph, so it can flip buffers instantly instead of
57
+ // waiting on a fresh TTS fetch.
58
+ const bufferParagraphIndexRef = useRef<Record<1 | 2, number | null>>({ 1: null, 2: null });
59
+ const currentParagraphIndexRef = useRef(0);
60
+ const paragraphUrlsRef = useRef<Record<string, string | undefined>>({});
61
+ const paragraphPromisesRef = useRef<Record<string, Promise<string | null> | undefined>>({});
62
+ const prefetchInProgressRef = useRef<Set<string>>(new Set());
63
+ const paragraphAbortControllersRef = useRef<Record<number, AbortController>>({});
64
+
65
+ const [continuousPlay, setContinuousPlay] = useState(false);
66
+ const isFirstContinuousPlayWriteRef = useRef(true);
67
+ useEffect(() => {
68
+ // One-time sync from localStorage after mount, same rationale as
69
+ // usePrefs.ts: the initial render must match the server (false) to avoid
70
+ // a hydration mismatch, so the persisted value can only apply client-side.
71
+ try {
72
+ // eslint-disable-next-line react-hooks/set-state-in-effect
73
+ setContinuousPlay(localStorage.getItem(CONTINUOUS_PLAY_KEY) === "true");
74
+ } catch {
75
+ // ignore
76
+ }
77
+ }, []);
78
+ useEffect(() => {
79
+ if (isFirstContinuousPlayWriteRef.current) {
80
+ isFirstContinuousPlayWriteRef.current = false;
81
+ return;
82
+ }
83
+ try {
84
+ localStorage.setItem(CONTINUOUS_PLAY_KEY, String(continuousPlay));
85
+ } catch {
86
+ // ignore
87
+ }
88
+ }, [continuousPlay]);
89
+
90
+ const isFirstPlaybackRateWriteRef = useRef(true);
91
+ useEffect(() => {
92
+ // Same SSR-safe restore-after-mount rationale as continuousPlay above.
93
+ try {
94
+ const saved = localStorage.getItem(PLAYBACK_RATE_KEY);
95
+ if (saved) {
96
+ const parsed = parseFloat(saved);
97
+ // eslint-disable-next-line react-hooks/set-state-in-effect
98
+ if (!Number.isNaN(parsed)) setPlaybackRate(parsed);
99
+ }
100
+ } catch {
101
+ // ignore
102
+ }
103
+ }, []);
104
+ useEffect(() => {
105
+ // Same first-write-skip guard as continuousPlay above — avoids clobbering
106
+ // the just-restored value with the pre-restore default in the same pass.
107
+ if (isFirstPlaybackRateWriteRef.current) {
108
+ isFirstPlaybackRateWriteRef.current = false;
109
+ return;
110
+ }
111
+ try {
112
+ localStorage.setItem(PLAYBACK_RATE_KEY, String(playbackRate));
113
+ } catch {
114
+ // ignore
115
+ }
116
+ }, [playbackRate]);
117
+
118
+ useEffect(() => {
119
+ currentParagraphIndexRef.current = currentParagraphIndex;
120
+ }, [currentParagraphIndex]);
121
+
122
+ // ── Studio voice: request + poll ──────────────────────────────────────
123
+ const requestStudioAudio = useCallback(async () => {
124
+ if (audioStatus === "loading" || audioStatus === "generating" || audioStatus === "done") return;
125
+ setAudioStatus("loading");
126
+ setAudioError(null);
127
+ studioCancelledRef.current = false;
128
+
129
+ try {
130
+ const res = await requestChapterAudio(chapterId);
131
+ if (!res.success || !res.data) {
132
+ if (!studioCancelledRef.current) {
133
+ setAudioStatus("error");
134
+ setAudioError(res.message || "Không thể kết nối server");
135
+ }
136
+ return;
137
+ }
138
+
139
+ if (res.data.status === "done" && res.data.audioUrl) {
140
+ if (!studioCancelledRef.current) {
141
+ setStudioAudioUrl(res.data.audioUrl);
142
+ setAudioStatus("done");
143
+ }
144
+ return;
145
+ }
146
+
147
+ if (!studioCancelledRef.current) setAudioStatus("generating");
148
+
149
+ const MAX_ATTEMPTS = 20; // 20 * 3s = 60s timeout
150
+ const INTERVAL_MS = 3000;
151
+ for (let i = 0; i < MAX_ATTEMPTS; i++) {
152
+ if (studioCancelledRef.current) return;
153
+ await new Promise((r) => setTimeout(r, INTERVAL_MS));
154
+ if (studioCancelledRef.current) return;
155
+
156
+ try {
157
+ const poll = await getChapterAudioStatus(chapterId);
158
+ if (poll.data?.status === "done" && poll.data.audioUrl) {
159
+ if (!studioCancelledRef.current) {
160
+ setStudioAudioUrl(poll.data.audioUrl);
161
+ setAudioStatus("done");
162
+ }
163
+ return;
164
+ }
165
+ if (poll.data?.status === "failed") {
166
+ if (!studioCancelledRef.current) {
167
+ setAudioStatus("failed");
168
+ setAudioError(poll.data.error || "Tạo audio thất bại");
169
+ }
170
+ return;
171
+ }
172
+ } catch {
173
+ // Network error, ignore and continue polling
174
+ }
175
+ }
176
+
177
+ if (!studioCancelledRef.current) {
178
+ setAudioStatus("failed");
179
+ setAudioError("Tạo audio quá lâu, vui lòng thử lại");
180
+ }
181
+ } catch {
182
+ if (!studioCancelledRef.current) {
183
+ setAudioStatus("error");
184
+ setAudioError("Không thể kết nối server");
185
+ }
186
+ }
187
+ }, [audioStatus, chapterId]);
188
+
189
+ // ── TikTok voice: per-paragraph fetch with cache + in-flight dedupe ────
190
+ const getParagraphAudioUrl = useCallback(
191
+ async (idx: number, voice: string): Promise<string | null> => {
192
+ const cacheKey = `${idx}_${voice}`;
193
+ if (paragraphUrlsRef.current[cacheKey]) return paragraphUrlsRef.current[cacheKey];
194
+ if (paragraphPromisesRef.current[cacheKey]) return paragraphPromisesRef.current[cacheKey];
195
+
196
+ if (paragraphAbortControllersRef.current[idx]) {
197
+ paragraphAbortControllersRef.current[idx].abort();
198
+ }
199
+ const controller = new AbortController();
200
+ paragraphAbortControllersRef.current[idx] = controller;
201
+
202
+ const promise = (async () => {
203
+ try {
204
+ const text = paragraphs[idx];
205
+ if (!text) return null;
206
+
207
+ const hasSpeakableText = /[a-zA-Z0-9\p{L}\p{N}]/u.test(text);
208
+ const blob = hasSpeakableText
209
+ ? await generateTikTokTTS(text, voice, controller.signal)
210
+ : createSilentWav(1.2);
211
+
212
+ const url = URL.createObjectURL(blob);
213
+ paragraphUrlsRef.current[cacheKey] = url;
214
+ return url;
215
+ } catch (err) {
216
+ if ((err as Error).message === "Aborted") return null;
217
+ throw err;
218
+ } finally {
219
+ delete paragraphAbortControllersRef.current[idx];
220
+ delete paragraphPromisesRef.current[cacheKey];
221
+ }
222
+ })();
223
+
224
+ paragraphPromisesRef.current[cacheKey] = promise;
225
+ return promise;
226
+ },
227
+ [paragraphs]
228
+ );
229
+
230
+ const getAudioElements = useCallback(() => {
231
+ const activeSlot = activeAudioRef.current;
232
+ const inactiveSlot: 1 | 2 = activeSlot === 1 ? 2 : 1;
233
+ const active = activeSlot === 1 ? audioRef1.current : audioRef2.current;
234
+ const inactive = inactiveSlot === 1 ? audioRef1.current : audioRef2.current;
235
+ return { active, inactive, activeSlot, inactiveSlot };
236
+ }, []);
237
+
238
+ const preloadNextParagraph = useCallback(
239
+ async (idx: number, voice: string) => {
240
+ if (idx >= paragraphs.length) return;
241
+ const { inactive, inactiveSlot } = getAudioElements();
242
+ if (!inactive) return;
243
+ try {
244
+ const url = await getParagraphAudioUrl(idx, voice);
245
+ if (url && inactive) {
246
+ inactive.playbackRate = playbackRate;
247
+ inactive.volume = volume;
248
+ inactive.muted = isMuted;
249
+ if (inactive.src !== url) inactive.src = url;
250
+ inactive.load();
251
+ bufferParagraphIndexRef.current[inactiveSlot] = idx;
252
+ }
253
+ } catch {
254
+ // ignore preload failures — playback will retry on demand
255
+ }
256
+ },
257
+ [paragraphs.length, getParagraphAudioUrl, getAudioElements, playbackRate, volume, isMuted]
258
+ );
259
+
260
+ const prefetchNextParagraphs = useCallback(
261
+ (startIndex: number, voice: string) => {
262
+ const end = Math.min(startIndex + 5, paragraphs.length - 1);
263
+ for (let i = startIndex + 1; i <= end; i++) {
264
+ const cacheKey = `${i}_${voice}`;
265
+ if (paragraphUrlsRef.current[cacheKey] || prefetchInProgressRef.current.has(cacheKey)) continue;
266
+ prefetchInProgressRef.current.add(cacheKey);
267
+ (async (idx: number) => {
268
+ try {
269
+ await getParagraphAudioUrl(idx, voice);
270
+ } catch {
271
+ // ignore prefetch failures
272
+ } finally {
273
+ prefetchInProgressRef.current.delete(cacheKey);
274
+ }
275
+ })(i);
276
+ }
277
+ },
278
+ [paragraphs.length, getParagraphAudioUrl]
279
+ );
280
+
281
+ const playParagraph = useCallback(
282
+ async (idx: number, startPlaying = true) => {
283
+ if (idx < 0 || idx >= paragraphs.length) {
284
+ setIsPlaying(false);
285
+ return;
286
+ }
287
+
288
+ setCurrentParagraphIndex(idx);
289
+ setCurrentTime(0);
290
+ setDuration(0);
291
+
292
+ const activeVoice = selectedVoice;
293
+ const cacheKey = `${idx}_${activeVoice}`;
294
+ const cachedUrl = paragraphUrlsRef.current[cacheKey];
295
+
296
+ if (audioRef1.current) audioRef1.current.pause();
297
+ if (audioRef2.current) audioRef2.current.pause();
298
+
299
+ const applyToElement = (el: HTMLAudioElement, slot: 1 | 2, url: string) => {
300
+ if (el.src !== url) el.src = url;
301
+ el.playbackRate = playbackRate;
302
+ el.volume = volume;
303
+ el.muted = isMuted;
304
+ bufferParagraphIndexRef.current[slot] = idx;
305
+ setLoadedCacheKey(cacheKey);
306
+ if (startPlaying) {
307
+ el.play().catch(() => {});
308
+ setIsPlaying(true);
309
+ } else {
310
+ el.pause();
311
+ setIsPlaying(false);
312
+ }
313
+ };
314
+
315
+ if (cachedUrl) {
316
+ const { active, activeSlot } = getAudioElements();
317
+ if (active) applyToElement(active, activeSlot, cachedUrl);
318
+ preloadNextParagraph(idx + 1, activeVoice);
319
+ prefetchNextParagraphs(idx, activeVoice);
320
+ return;
321
+ }
322
+
323
+ setIsGeneratingParagraph(true);
324
+ try {
325
+ const url = await getParagraphAudioUrl(idx, activeVoice);
326
+ if (url) {
327
+ if (audioRef1.current) audioRef1.current.pause();
328
+ if (audioRef2.current) audioRef2.current.pause();
329
+ const { active, activeSlot } = getAudioElements();
330
+ if (active) applyToElement(active, activeSlot, url);
331
+ preloadNextParagraph(idx + 1, activeVoice);
332
+ prefetchNextParagraphs(idx, activeVoice);
333
+ }
334
+ } finally {
335
+ setIsGeneratingParagraph(false);
336
+ }
337
+ },
338
+ [
339
+ paragraphs.length,
340
+ selectedVoice,
341
+ playbackRate,
342
+ volume,
343
+ isMuted,
344
+ getParagraphAudioUrl,
345
+ preloadNextParagraph,
346
+ prefetchNextParagraphs,
347
+ getAudioElements,
348
+ ]
349
+ );
350
+
351
+ const handlePrevParagraph = useCallback(() => {
352
+ if (currentParagraphIndex > 0) playParagraph(currentParagraphIndex - 1, isPlaying);
353
+ }, [currentParagraphIndex, playParagraph, isPlaying]);
354
+
355
+ const handleNextParagraph = useCallback(() => {
356
+ if (currentParagraphIndex < paragraphs.length - 1) playParagraph(currentParagraphIndex + 1, isPlaying);
357
+ }, [currentParagraphIndex, paragraphs.length, playParagraph, isPlaying]);
358
+
359
+ const handleAudioEnded = useCallback(() => {
360
+ if (selectedVoice === "server") {
361
+ setIsPlaying(false);
362
+ return;
363
+ }
364
+
365
+ const nextIdx = currentParagraphIndex + 1;
366
+ if (nextIdx < paragraphs.length) {
367
+ const { inactive, inactiveSlot } = getAudioElements();
368
+ const isPreloaded = inactive && bufferParagraphIndexRef.current[inactiveSlot] === nextIdx;
369
+
370
+ if (isPreloaded && inactive) {
371
+ activeAudioRef.current = inactiveSlot;
372
+ setCurrentParagraphIndex(nextIdx);
373
+ setCurrentTime(0);
374
+ setDuration(inactive.duration || 0);
375
+ setLoadedCacheKey(`${nextIdx}_${selectedVoice}`);
376
+ inactive.playbackRate = playbackRate;
377
+ inactive.volume = volume;
378
+ inactive.muted = isMuted;
379
+ inactive.play().catch(() => {});
380
+ setIsPlaying(true);
381
+ preloadNextParagraph(nextIdx + 1, selectedVoice);
382
+ prefetchNextParagraphs(nextIdx, selectedVoice);
383
+ } else {
384
+ playParagraph(nextIdx, true);
385
+ }
386
+ } else if (continuousPlay && hasNext) {
387
+ try {
388
+ sessionStorage.setItem(AUTOPLAY_NEXT_KEY, "1");
389
+ } catch {
390
+ // ignore
391
+ }
392
+ navigateToNextChapter();
393
+ } else {
394
+ setIsPlaying(false);
395
+ }
396
+ }, [
397
+ selectedVoice,
398
+ currentParagraphIndex,
399
+ paragraphs.length,
400
+ playParagraph,
401
+ preloadNextParagraph,
402
+ prefetchNextParagraphs,
403
+ playbackRate,
404
+ volume,
405
+ isMuted,
406
+ getAudioElements,
407
+ continuousPlay,
408
+ hasNext,
409
+ navigateToNextChapter,
410
+ ]);
411
+
412
+ const jumpToProgress = useCallback(
413
+ (val: number) => {
414
+ const targetIdx = Math.min(paragraphs.length - 1, Math.max(0, Math.floor(val)));
415
+ setLocalProgress(null);
416
+ playParagraph(targetIdx, isPlaying);
417
+ },
418
+ [paragraphs.length, playParagraph, isPlaying]
419
+ );
420
+
421
+ const isBufferCurrent = useCallback(
422
+ (id: 1 | 2) => selectedVoice === "server" || bufferParagraphIndexRef.current[id] === currentParagraphIndexRef.current,
423
+ [selectedVoice]
424
+ );
425
+
426
+ const handleTimeUpdate = useCallback(
427
+ (id: 1 | 2) => {
428
+ if (activeAudioRef.current !== id) return;
429
+ const audio = id === 1 ? audioRef1.current : audioRef2.current;
430
+ if (audio && isBufferCurrent(id)) setCurrentTime(audio.currentTime || 0);
431
+ },
432
+ [isBufferCurrent]
433
+ );
434
+
435
+ const handleLoadedMetadata = useCallback(
436
+ (id: 1 | 2) => {
437
+ if (activeAudioRef.current !== id) return;
438
+ const audio = id === 1 ? audioRef1.current : audioRef2.current;
439
+ if (audio && isBufferCurrent(id)) setDuration(audio.duration || 0);
440
+ },
441
+ [isBufferCurrent]
442
+ );
443
+
444
+ const handleEnded = useCallback(
445
+ (id: 1 | 2) => {
446
+ if (activeAudioRef.current === id) handleAudioEnded();
447
+ },
448
+ [handleAudioEnded]
449
+ );
450
+
451
+ const handlePlay = useCallback((id: 1 | 2) => {
452
+ if (activeAudioRef.current === id) setIsPlaying(true);
453
+ }, []);
454
+
455
+ const handlePause = useCallback((id: 1 | 2) => {
456
+ if (activeAudioRef.current === id) setIsPlaying(false);
457
+ }, []);
458
+
459
+ const togglePlay = useCallback(() => {
460
+ if (selectedVoice === "server") {
461
+ const audio = audioRef1.current;
462
+ if (!audio) return;
463
+ if (isPlaying) {
464
+ audio.pause();
465
+ } else {
466
+ audio.play().catch(() => {});
467
+ }
468
+ return;
469
+ }
470
+
471
+ const { active } = getAudioElements();
472
+ if (isPlaying) {
473
+ if (active) active.pause();
474
+ setIsPlaying(false);
475
+ } else {
476
+ playParagraph(currentParagraphIndex, true);
477
+ }
478
+ }, [isPlaying, selectedVoice, currentParagraphIndex, playParagraph, getAudioElements]);
479
+
480
+ const handleVoiceChange = useCallback(
481
+ async (newVoice: string) => {
482
+ if (newVoice === selectedVoice) return;
483
+
484
+ const wasPlaying = isPlaying;
485
+ audioRef1.current?.pause();
486
+ audioRef2.current?.pause();
487
+ setIsPlaying(false);
488
+ setSelectedVoiceState(newVoice);
489
+
490
+ if (newVoice === "server") {
491
+ await requestStudioAudio();
492
+ } else {
493
+ await playParagraph(currentParagraphIndex, wasPlaying);
494
+ }
495
+ },
496
+ [selectedVoice, isPlaying, currentParagraphIndex, playParagraph, requestStudioAudio]
497
+ );
498
+
499
+ const openPlayer = useCallback(() => {
500
+ setPlayerOpen(true);
501
+ if (selectedVoice === "server") {
502
+ if (audioStatus === "idle") requestStudioAudio();
503
+ } else if (!paragraphUrlsRef.current[`${currentParagraphIndex}_${selectedVoice}`]) {
504
+ playParagraph(currentParagraphIndex, false).catch(() => {});
505
+ }
506
+ }, [selectedVoice, audioStatus, requestStudioAudio, currentParagraphIndex, playParagraph]);
507
+
508
+ // Push the fetched Studio URL onto the single audio element that voice uses
509
+ useEffect(() => {
510
+ if (selectedVoice !== "server" || !audioRef1.current) return;
511
+ audioRef1.current.src = studioAudioUrl ?? "";
512
+ }, [studioAudioUrl, selectedVoice]);
513
+
514
+ // Sync volume/mute/speed to whichever elements exist
515
+ useEffect(() => {
516
+ if (audioRef1.current) {
517
+ audioRef1.current.volume = volume;
518
+ audioRef1.current.muted = isMuted;
519
+ audioRef1.current.playbackRate = playbackRate;
520
+ }
521
+ if (audioRef2.current) {
522
+ audioRef2.current.volume = volume;
523
+ audioRef2.current.muted = isMuted;
524
+ audioRef2.current.playbackRate = playbackRate;
525
+ }
526
+ }, [volume, isMuted, playbackRate]);
527
+
528
+ // Pre-fetch the first few paragraphs once the chapter's text is available
529
+ useEffect(() => {
530
+ if (paragraphs.length > 0) prefetchNextParagraphs(-1, selectedVoice);
531
+ // eslint-disable-next-line react-hooks/exhaustive-deps -- only re-run on voice/paragraph-set change
532
+ }, [selectedVoice, paragraphs]);
533
+
534
+ // Continuous play: resume automatically if the previous chapter navigated
535
+ // here specifically to keep playing (ReaderView remounts fresh per chapter,
536
+ // so this flag is how the "next chapter" carries the intent across).
537
+ useEffect(() => {
538
+ let shouldAutoPlay = false;
539
+ try {
540
+ shouldAutoPlay = sessionStorage.getItem(AUTOPLAY_NEXT_KEY) === "1";
541
+ if (shouldAutoPlay) sessionStorage.removeItem(AUTOPLAY_NEXT_KEY);
542
+ } catch {
543
+ // ignore
544
+ }
545
+ if (shouldAutoPlay && paragraphs.length > 0) {
546
+ // eslint-disable-next-line react-hooks/set-state-in-effect -- one-time resume gated on a sessionStorage flag set by the previous chapter, not a value derivable during render
547
+ setPlayerOpen(true);
548
+ playParagraph(0, true).catch(() => {});
549
+ }
550
+ // eslint-disable-next-line react-hooks/exhaustive-deps -- run once per chapter mount
551
+ }, []);
552
+
553
+ // Cleanup on chapter change / unmount: revoke object URLs, abort in-flight
554
+ // TTS requests, and cancel any active Studio polling.
555
+ useEffect(() => {
556
+ return () => {
557
+ studioCancelledRef.current = true;
558
+ Object.values(paragraphAbortControllersRef.current).forEach((c) => {
559
+ try {
560
+ c.abort();
561
+ } catch {
562
+ // ignore
563
+ }
564
+ });
565
+ paragraphAbortControllersRef.current = {};
566
+ Object.values(paragraphUrlsRef.current).forEach((url) => {
567
+ if (!url) return;
568
+ try {
569
+ URL.revokeObjectURL(url);
570
+ } catch {
571
+ // ignore
572
+ }
573
+ });
574
+ paragraphUrlsRef.current = {};
575
+ paragraphPromisesRef.current = {};
576
+ // Plain in-memory Set, not a DOM-node ref — safe to read '.current' here.
577
+ // eslint-disable-next-line react-hooks/exhaustive-deps
578
+ prefetchInProgressRef.current.clear();
579
+ };
580
+ }, [chapterId]);
581
+
582
+ const isPlayerDisabled =
583
+ selectedVoice === "server"
584
+ ? audioStatus !== "done"
585
+ : loadedCacheKey !== `${currentParagraphIndex}_${selectedVoice}` || isGeneratingParagraph;
586
+
587
+ // Mirrors frontend's toolbarBtnAudioDone/dockAudioFabDone condition — lets
588
+ // the toolbar button highlight green once audio for this chapter is ready.
589
+ const isAudioReady = selectedVoice === "server" ? audioStatus === "done" : paragraphs.length > 0;
590
+
591
+ return {
592
+ playerOpen,
593
+ setPlayerOpen,
594
+ openPlayer,
595
+ isAudioReady,
596
+ selectedVoice,
597
+ handleVoiceChange,
598
+ voices: TIKTOK_VOICES,
599
+ audioStatus,
600
+ audioError,
601
+ studioAudioUrl,
602
+ requestStudioAudio,
603
+ isPlaying,
604
+ currentTime,
605
+ duration,
606
+ volume,
607
+ setVolume,
608
+ isMuted,
609
+ setIsMuted,
610
+ playbackRate,
611
+ setPlaybackRate,
612
+ currentParagraphIndex,
613
+ paragraphCount: paragraphs.length,
614
+ isGeneratingParagraph,
615
+ localProgress,
616
+ setLocalProgress,
617
+ continuousPlay,
618
+ setContinuousPlay,
619
+ isPlayerDisabled,
620
+ audioRef1,
621
+ audioRef2,
622
+ playParagraph,
623
+ togglePlay,
624
+ handlePrevParagraph,
625
+ handleNextParagraph,
626
+ jumpToProgress,
627
+ handleTimeUpdate,
628
+ handleLoadedMetadata,
629
+ handleEnded,
630
+ handlePlay,
631
+ handlePause,
632
+ };
633
+ }
@@ -0,0 +1,31 @@
1
+ "use client";
2
+
3
+ import { useCallback, useEffect, useRef, useState } from "react";
4
+
5
+ export function useAutoScroll() {
6
+ const [isAutoScrolling, setIsAutoScrolling] = useState(false);
7
+ const [scrollSpeed, setScrollSpeed] = useState(1);
8
+ const autoScrollTimer = useRef<number | null>(null);
9
+
10
+ const startAutoScroll = useCallback(() => {
11
+ if (autoScrollTimer.current) return;
12
+ setIsAutoScrolling(true);
13
+ const step = () => {
14
+ window.scrollBy(0, scrollSpeed * 0.75);
15
+ autoScrollTimer.current = window.requestAnimationFrame(step);
16
+ };
17
+ autoScrollTimer.current = window.requestAnimationFrame(step);
18
+ }, [scrollSpeed]);
19
+
20
+ const stopAutoScroll = useCallback(() => {
21
+ if (autoScrollTimer.current) {
22
+ cancelAnimationFrame(autoScrollTimer.current);
23
+ autoScrollTimer.current = null;
24
+ }
25
+ setIsAutoScrolling(false);
26
+ }, []);
27
+
28
+ useEffect(() => stopAutoScroll, [stopAutoScroll]);
29
+
30
+ return { isAutoScrolling, scrollSpeed, setScrollSpeed, startAutoScroll, stopAutoScroll };
31
+ }
@@ -0,0 +1,32 @@
1
+ "use client";
2
+
3
+ import { useCallback, useState } from "react";
4
+ import { toggleBookmark as toggleBookmarkApi } from "../api/client-bookmark-api";
5
+ import type { ToastType } from "./useToast";
6
+
7
+ export function useBookmark(
8
+ storyId: string,
9
+ initialIsBookmarked: boolean,
10
+ showToast: (text: string, type?: ToastType) => void
11
+ ) {
12
+ const [isBookmarked, setIsBookmarked] = useState(initialIsBookmarked);
13
+
14
+ const toggleBookmark = useCallback(async () => {
15
+ const res = await toggleBookmarkApi(storyId);
16
+
17
+ if (res.message === "unauthorized") {
18
+ showToast("Vui lòng đăng nhập để theo dõi truyện.", "error");
19
+ window.location.href = "/dang-nhap";
20
+ return;
21
+ }
22
+ if (!res.success) {
23
+ showToast(res.message || "Có lỗi xảy ra.", "error");
24
+ return;
25
+ }
26
+
27
+ setIsBookmarked(res.isBookmarked);
28
+ showToast(res.isBookmarked ? "Đã thêm vào tủ truyện" : "Đã bỏ theo dõi", "success");
29
+ }, [storyId, showToast]);
30
+
31
+ return { isBookmarked, toggleBookmark };
32
+ }