fix: book transcript browser navigation

This commit is contained in:
gosangam
2026-06-17 18:00:13 +05:30
parent bc1798b31b
commit 071eb4d58a
@@ -2,6 +2,7 @@
import { useState, useMemo, useRef } from "react";
import Link from "next/link";
import { usePathname, useSearchParams } from "next/navigation";
import { Card, CardContent } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { buttonVariants } from "@/components/ui/button";
@@ -384,9 +385,18 @@ export function TranscriptionBookBrowser({
const flat = useMemo(() => flattenChapters(sections), [sections]);
const [activeKeyRaw, setActiveKey] = useState<string>(
flat.length > 0 ? flat[0].chapter.key : "",
);
// The active chapter lives in the URL (?chapter=<key>) so it's bookmarkable
// and survives back-navigation: opening a lecture then pressing Back returns
// to the chapter you were on rather than resetting to the first one. We seed
// local state from the URL on mount and keep the URL in sync on selection.
const pathname = usePathname();
const searchParams = useSearchParams();
const [activeKeyRaw, setActiveKey] = useState<string>(() => {
const fromUrl = searchParams.get("chapter");
if (fromUrl && flat.find((f) => f.chapter.key === fromUrl)) return fromUrl;
return flat.length > 0 ? flat[0].chapter.key : "";
});
// Derive a safe active chapter key (the data could change underneath us).
const activeKey = useMemo(() => {
@@ -399,6 +409,11 @@ export function TranscriptionBookBrowser({
const handleSelect = (key: string) => {
setActiveKey(key);
// Reflect the choice in the URL without a new history entry (so Back leaves
// the page rather than cycling chapters) or a server round-trip.
const params = new URLSearchParams(Array.from(searchParams.entries()));
params.set("chapter", key);
window.history.replaceState(null, "", `${pathname}?${params.toString()}`);
contentRef.current?.scrollIntoView({ behavior: "smooth", block: "start" });
};