Fix ebook /read links to /book/read and add compat redirects.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
eric 2026-09-28 18:54:03 -05:00
parent 6cae715727
commit 0fc608ea26
19 changed files with 89 additions and 25 deletions

9
app/read/[slug]/page.tsx Normal file
View File

@ -0,0 +1,9 @@
import { redirect } from "next/navigation";
type Props = { params: Promise<{ slug: string }> };
/** Compat: /read/[slug] → /book/read#slug (hash preserved by browser on redirect when possible) */
export default async function ReadSlugCompatRedirect({ params }: Props) {
const { slug } = await params;
redirect(`/book/read#${slug}`);
}

6
app/read/page.tsx Normal file
View File

@ -0,0 +1,6 @@
import { redirect } from "next/navigation";
/** Compat: old ebook URLs lived at /read — now mounted under /book/read */
export default function ReadCompatRedirect() {
redirect("/book/read");
}

View File

@ -47,7 +47,7 @@ export function BookEnd({ book }: { book: Book }) {
const first = book.chapters[0]?.slug; const first = book.chapters[0]?.slug;
if (first) { if (first) {
document.getElementById(first)?.scrollIntoView({ behavior: 'smooth' }); document.getElementById(first)?.scrollIntoView({ behavior: 'smooth' });
history.replaceState(null, '', `/read#${first}`); history.replaceState(null, '', `/book/read#${first}`);
} }
}} }}
> >

View File

@ -9,7 +9,7 @@ import { useT } from '@ebook/components/LocaleProvider';
function jumpToHit(slug: string, query: string) { function jumpToHit(slug: string, query: string) {
const section = document.getElementById(slug); const section = document.getElementById(slug);
section?.scrollIntoView({ behavior: 'smooth', block: 'start' }); section?.scrollIntoView({ behavior: 'smooth', block: 'start' });
history.replaceState(null, '', `/read#${slug}`); history.replaceState(null, '', `/book/read#${slug}`);
window.setTimeout(() => { window.setTimeout(() => {
const root = document.getElementById(slug); const root = document.getElementById(slug);

View File

@ -8,7 +8,7 @@ import type { Book } from '@ebook/lib/book-types';
function scrollToChapterSlug(slug: string) { function scrollToChapterSlug(slug: string) {
document.getElementById(slug)?.scrollIntoView({ behavior: 'smooth', block: 'start' }); document.getElementById(slug)?.scrollIntoView({ behavior: 'smooth', block: 'start' });
history.replaceState(null, '', `/read#${slug}`); history.replaceState(null, '', `/book/read#${slug}`);
} }
export function ChapterMenu({ export function ChapterMenu({
@ -24,7 +24,7 @@ export function ChapterMenu({
const [mounted, setMounted] = useState(false); const [mounted, setMounted] = useState(false);
const [filter, setFilter] = useState(''); const [filter, setFilter] = useState('');
const pathname = usePathname(); const pathname = usePathname();
const isScroll = scrollMode || pathname === '/read'; const isScroll = scrollMode || pathname === '/book/read';
useEffect(() => setMounted(true), []); useEffect(() => setMounted(true), []);
@ -98,10 +98,10 @@ export function ChapterMenu({
chapter.title.toLowerCase().includes(filter.trim().toLowerCase()) chapter.title.toLowerCase().includes(filter.trim().toLowerCase())
) )
.map(({ chapter, i }) => { .map(({ chapter, i }) => {
const href = isScroll ? `/read#${chapter.slug}` : `/read/${chapter.slug}`; const href = isScroll ? `/book/read#${chapter.slug}` : `/book/read/${chapter.slug}`;
const active = isScroll const active = isScroll
? activeSlug === chapter.slug ? activeSlug === chapter.slug
: pathname === `/read/${chapter.slug}`; : pathname === `/book/read/${chapter.slug}`;
if (isScroll) { if (isScroll) {
return ( return (

View File

@ -18,7 +18,7 @@ export function ChapterNav({
<div className="flex items-stretch justify-between gap-6"> <div className="flex items-stretch justify-between gap-6">
{prev ? ( {prev ? (
<Link <Link
href={`/read/${prev.slug}`} href={`/book/read/${prev.slug}`}
className="glass-panel group flex min-w-0 flex-1 flex-col gap-1 rounded-[1.5rem] px-5 py-4 text-left transition hover:-translate-y-0.5" className="glass-panel group flex min-w-0 flex-1 flex-col gap-1 rounded-[1.5rem] px-5 py-4 text-left transition hover:-translate-y-0.5"
> >
<span className="text-xs text-[var(--book-muted)]">{t('reader.prevChapter')}</span> <span className="text-xs text-[var(--book-muted)]">{t('reader.prevChapter')}</span>
@ -32,7 +32,7 @@ export function ChapterNav({
{next ? ( {next ? (
<Link <Link
href={`/read/${next.slug}`} href={`/book/read/${next.slug}`}
className="glass-panel group flex min-w-0 flex-1 flex-col gap-1 rounded-[1.5rem] px-5 py-4 text-right transition hover:-translate-y-0.5" className="glass-panel group flex min-w-0 flex-1 flex-col gap-1 rounded-[1.5rem] px-5 py-4 text-right transition hover:-translate-y-0.5"
> >
<span className="text-xs text-[var(--book-muted)]">{t('reader.nextChapter')}</span> <span className="text-xs text-[var(--book-muted)]">{t('reader.nextChapter')}</span>

View File

@ -21,7 +21,7 @@ function scrollToId(id: string) {
function scrollToChapterSlug(slug: string) { function scrollToChapterSlug(slug: string) {
scrollToId(slug); scrollToId(slug);
history.replaceState(null, '', `/read#${slug}`); history.replaceState(null, '', `/book/read#${slug}`);
} }
function ChapterNavList({ function ChapterNavList({
@ -115,7 +115,7 @@ function ChapterNavList({
<span style={{ width: 22, flexShrink: 0 }} aria-hidden /> <span style={{ width: 22, flexShrink: 0 }} aria-hidden />
)} )}
<a <a
href={`/read#${chapter.slug}`} href={`/book/read#${chapter.slug}`}
onClick={(e) => { onClick={(e) => {
e.preventDefault(); e.preventDefault();
scrollToChapterSlug(chapter.slug); scrollToChapterSlug(chapter.slug);

View File

@ -30,7 +30,7 @@ export function ContinueReading({
const readCount = progress?.readChapters.length ?? 0; const readCount = progress?.readChapters.length ?? 0;
const percent = calcBookProgress(readCount, book.chapters.length); const percent = calcBookProgress(readCount, book.chapters.length);
const continueSlug = progress?.slug; const continueSlug = progress?.slug;
const continueHref = continueSlug ? `/read#${continueSlug}` : '/read'; const continueHref = continueSlug ? `/book/read#${continueSlug}` : '/book/read';
const continueChapter = continueSlug const continueChapter = continueSlug
? book.chapters.find((c) => c.slug === continueSlug) ? book.chapters.find((c) => c.slug === continueSlug)

View File

@ -28,7 +28,7 @@ export function CoverChapterGrid({
return ( return (
<Link <Link
key={ch.slug} key={ch.slug}
href={`/read#${ch.slug}`} href={`/book/read#${ch.slug}`}
className={`viral-chapter-card ${isRead ? 'is-read' : ''}`} className={`viral-chapter-card ${isRead ? 'is-read' : ''}`}
> >
<span className="viral-chapter-num">{String(i + 1).padStart(2, '0')}</span> <span className="viral-chapter-num">{String(i + 1).padStart(2, '0')}</span>

View File

@ -36,7 +36,7 @@ export function ViralSharePrompt({ book }: { book: Book }) {
const [show, setShow] = useState(false); const [show, setShow] = useState(false);
const hashtags = book.viralTags.slice(0, 3).map((t) => `#${t}`).join(' '); const hashtags = book.viralTags.slice(0, 3).map((t) => `#${t}`).join(' ');
const text = `${t('cover.readingNow', { title: book.title })} 📖\n${book.tagline}\n\n${hashtags}`; const text = `${t('cover.readingNow', { title: book.title })} 📖\n${book.tagline}\n\n${hashtags}`;
const url = buildShareUrl('/read', 'viral_prompt'); const url = buildShareUrl('/book/read', 'viral_prompt');
useEffect(() => { useEffect(() => {
const onScroll = () => { const onScroll = () => {

View File

@ -55,13 +55,13 @@ function CopyHeadingLink({ id }: { id: string }) {
aria-label={t('reader.copyLink')} aria-label={t('reader.copyLink')}
onClick={async (e) => { onClick={async (e) => {
e.preventDefault(); e.preventDefault();
const url = `${window.location.origin}/read#${id}`; const url = `${window.location.origin}/book/read#${id}`;
try { try {
await navigator.clipboard.writeText(url); await navigator.clipboard.writeText(url);
} catch { } catch {
/* ignore */ /* ignore */
} }
history.replaceState(null, '', `/read#${id}`); history.replaceState(null, '', `/book/read#${id}`);
setOk(true); setOk(true);
window.setTimeout(() => setOk(false), 1200); window.setTimeout(() => setOk(false), 1200);
}} }}

View File

@ -15,14 +15,14 @@ export function MobileChapterBar({
return ( return (
<nav className="mobile-chapter-bar" aria-label="章节快捷导航"> <nav className="mobile-chapter-bar" aria-label="章节快捷导航">
{prev ? ( {prev ? (
<Link href={`/read/${prev.slug}`} className="mobile-chapter-btn"> <Link href={`/book/read/${prev.slug}`} className="mobile-chapter-btn">
← {prev.title} ← {prev.title}
</Link> </Link>
) : ( ) : (
<span /> <span />
)} )}
{next ? ( {next ? (
<Link href={`/read/${next.slug}`} className="mobile-chapter-btn is-next"> <Link href={`/book/read/${next.slug}`} className="mobile-chapter-btn is-next">
{next.title} → {next.title} →
</Link> </Link>
) : ( ) : (

View File

@ -14,7 +14,7 @@ function isTypingTarget(target: EventTarget | null) {
function scrollToChapter(slug: string) { function scrollToChapter(slug: string) {
document.getElementById(slug)?.scrollIntoView({ behavior: 'smooth', block: 'start' }); document.getElementById(slug)?.scrollIntoView({ behavior: 'smooth', block: 'start' });
history.replaceState(null, '', `/read#${slug}`); history.replaceState(null, '', `/book/read#${slug}`);
} }
export function ReaderShortcuts({ export function ReaderShortcuts({

View File

@ -63,7 +63,7 @@ export function ScrollReadingTracker({
trackEvent('chapter_view', { slug: activeSlug, index }); trackEvent('chapter_view', { slug: activeSlug, index });
if (window.location.hash !== `#${activeSlug}`) { if (window.location.hash !== `#${activeSlug}`) {
history.replaceState(null, '', `/read#${activeSlug}`); history.replaceState(null, '', `/book/read#${activeSlug}`);
} }
} }
}, },

View File

@ -109,7 +109,7 @@ export function SelectionShare({ book, slug }: { book: Book; slug: string }) {
<button <button
type="button" type="button"
onClick={() => { onClick={() => {
shareToX(quote, getPageUrl('/read')); shareToX(quote, getPageUrl('/book/read'));
setPop(null); setPop(null);
}} }}
> >

View File

@ -35,7 +35,7 @@ export function ShareQuoteCard({
<button type="button" onClick={copy}> <button type="button" onClick={copy}>
{copied ? t('reader.copied') : t('reader.copyQuote')} {copied ? t('reader.copied') : t('reader.copyQuote')}
</button> </button>
<ShareToX text={text} url={getPageUrl('/read')} label={t('common.share')} compact /> <ShareToX text={text} url={getPageUrl('/book/read')} label={t('common.share')} compact />
</div> </div>
</figure> </figure>
); );

View File

@ -38,10 +38,10 @@ export function buildChapterMetadata(slug: string, locale: Locale = 'zh'): Metad
const chapter = getChapter(slug, locale); const chapter = getChapter(slug, locale);
if (!chapter) return buildBookMetadata(locale); if (!chapter) return buildBookMetadata(locale);
const url = `${getSiteUrl()}/read#${slug}`; const url = `${getSiteUrl()}/book/read#${slug}`;
const title = `${chapter.emoji} ${chapter.title} · ${book.title}`; const title = `${chapter.emoji} ${chapter.title} · ${book.title}`;
const description = chapter.hook; const description = chapter.hook;
const ogImage = `${getSiteUrl()}/read/opengraph-image`; const ogImage = `${getSiteUrl()}/book/read/opengraph-image`;
return { return {
title, title,

View File

@ -12,7 +12,7 @@ export function getBookShareText(book: Pick<Book, 'title' | 'tagline' | 'viralTa
} }
export function getChapterShareUrl(slug: string) { export function getChapterShareUrl(slug: string) {
return buildShareUrl(`/read#${slug}`, 'chapter'); return buildShareUrl(`/book/read#${slug}`, 'chapter');
} }
export function getBookShareUrl() { export function getBookShareUrl() {
@ -20,5 +20,5 @@ export function getBookShareUrl() {
} }
export function getReadShareUrl() { export function getReadShareUrl() {
return buildShareUrl('/read', 'reader'); return buildShareUrl('/book/read', 'reader');
} }

View File

@ -0,0 +1,49 @@
#!/usr/bin/env python3
"""Prefix leftover /read paths in ebook to /book/read (avoid double prefix)."""
from __future__ import annotations
import pathlib
import re
ROOT = pathlib.Path(__file__).resolve().parents[1]
TARGETS = [
ROOT / "apps" / "ebook" / "src",
ROOT / "app" / "book",
]
PATTERNS = [
(re.compile(r"(?<!/book)/read#"), "/book/read#"),
(re.compile(r"(?<!/book)/read/"), "/book/read/"),
(re.compile(r"(?<!/book)/read(?=[`\"'\s\?]|$)"), "/book/read"),
]
def fix_text(text: str) -> str:
out = text
for pat, repl in PATTERNS:
out = pat.sub(repl, out)
out = out.replace("/book/book/read", "/book/read")
return out
def main() -> None:
n = 0
for base in TARGETS:
if not base.exists():
continue
for path in base.rglob("*"):
if path.suffix not in {".ts", ".tsx", ".js", ".jsx"}:
continue
if "node_modules" in path.parts:
continue
raw = path.read_text(encoding="utf-8")
fixed = fix_text(raw)
if fixed != raw:
path.write_text(fixed, encoding="utf-8")
n += 1
print("fixed", path.relative_to(ROOT))
print(f"updated {n} files")
if __name__ == "__main__":
main()