fix: book transcript browser navigation
This commit is contained in:
@@ -2,6 +2,7 @@
|
|||||||
|
|
||||||
import { useState, useMemo, useRef } from "react";
|
import { useState, useMemo, useRef } from "react";
|
||||||
import Link from "next/link";
|
import Link from "next/link";
|
||||||
|
import { usePathname, useSearchParams } from "next/navigation";
|
||||||
import { Card, CardContent } from "@/components/ui/card";
|
import { Card, CardContent } from "@/components/ui/card";
|
||||||
import { Badge } from "@/components/ui/badge";
|
import { Badge } from "@/components/ui/badge";
|
||||||
import { buttonVariants } from "@/components/ui/button";
|
import { buttonVariants } from "@/components/ui/button";
|
||||||
@@ -384,9 +385,18 @@ export function TranscriptionBookBrowser({
|
|||||||
|
|
||||||
const flat = useMemo(() => flattenChapters(sections), [sections]);
|
const flat = useMemo(() => flattenChapters(sections), [sections]);
|
||||||
|
|
||||||
const [activeKeyRaw, setActiveKey] = useState<string>(
|
// The active chapter lives in the URL (?chapter=<key>) so it's bookmarkable
|
||||||
flat.length > 0 ? flat[0].chapter.key : "",
|
// 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).
|
// Derive a safe active chapter key (the data could change underneath us).
|
||||||
const activeKey = useMemo(() => {
|
const activeKey = useMemo(() => {
|
||||||
@@ -399,6 +409,11 @@ export function TranscriptionBookBrowser({
|
|||||||
|
|
||||||
const handleSelect = (key: string) => {
|
const handleSelect = (key: string) => {
|
||||||
setActiveKey(key);
|
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" });
|
contentRef.current?.scrollIntoView({ behavior: "smooth", block: "start" });
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user