nomadro/apps/miniprogram/h5/src/pages/book/BookCoverPage.tsx
Eric 4389ebe6cb Ship WeChat audit release 2026-11-02: realtime config, audit vip-ebook shell, admin ops.
Document test9 tag 2026-11-02 for upload; POST config pull + WS, fixed dark home, no debug bar.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-02 16:12:57 +08:00

421 lines
15 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* 电子书 H5 封面 — 对齐门户首页 / 社群首页视觉语言
* (CommunityNavbar + hero shapes + gradient + typewriter + 固定 CTA)
* 内容 SoT: COVER_BOOK / nomadCodeBook;阅读入口 → /pages/reader
*/
import { useEffect, useMemo, useRef, useState } from 'react'
import { Button } from '@tarojs/components'
import Taro, { useDidShow, useLoad } from '@tarojs/taro'
import { fetchBook, type BookDetail } from '../../services/ebookApi'
import { COVER_BOOK } from '../../data/coverBook'
import {
formatAgo,
getReadingProgress,
type ReadingProgress,
} from '../../utils/readingProgress'
import { track, trackClick, trackPage } from '../../utils/track'
import { MiniModuleGate } from '@/components/MiniModuleGate'
import { CommunityNavbar } from '../../components/Chrome'
import { H5Box, H5Txt } from '../../components/H5Box'
import { applyH5Theme, useNomadroTheme } from '../../utils/h5Theme'
import { goPage } from '@/utils/nav'
import { getSafeAreaMetrics } from '../../utils/safeArea'
import {
getCachedRemoteConfig,
loadRemoteConfig,
subscribeRemoteConfig,
} from '@/services/remoteConfig'
import { resolveBookAudit } from '@/data/remoteConfig.defaults'
import './index.scss'
const isH5 = process.env.TARO_ENV === 'h5'
const BOOK_VISUAL_SVG = `<svg class="book-visual-svg" viewBox="0 0 400 400" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true">
<defs>
<radialGradient id="bookGlow" cx="50%" cy="45%" r="55%">
<stop offset="0%" stop-color="#4ECDC4" stop-opacity="0.28"/>
<stop offset="55%" stop-color="#FFE66D" stop-opacity="0.08"/>
<stop offset="100%" stop-color="#FF6B6B" stop-opacity="0"/>
</radialGradient>
<linearGradient id="bookSpine" x1="0%" y1="0%" x2="100%" y2="100%">
<stop offset="0%" stop-color="#FF6B6B"/>
<stop offset="50%" stop-color="#FFE66D"/>
<stop offset="100%" stop-color="#4ECDC4"/>
</linearGradient>
<linearGradient id="bookPageL" x1="100%" y1="0%" x2="0%" y2="100%">
<stop offset="0%" stop-color="#1e293b"/>
<stop offset="100%" stop-color="#0f172a"/>
</linearGradient>
<linearGradient id="bookPageR" x1="0%" y1="0%" x2="100%" y2="100%">
<stop offset="0%" stop-color="#1e293b"/>
<stop offset="100%" stop-color="#111827"/>
</linearGradient>
<filter id="bookSoft" x="-20%" y="-20%" width="140%" height="140%">
<feGaussianBlur stdDeviation="6" result="b"/>
<feMerge><feMergeNode in="b"/><feMergeNode in="SourceGraphic"/></feMerge>
</filter>
</defs>
<circle cx="200" cy="200" r="168" fill="url(#bookGlow)"/>
<ellipse class="book-shadow" cx="200" cy="318" rx="92" ry="14" fill="rgba(0,0,0,0.35)"/>
<g class="book-body" filter="url(#bookSoft)">
<path d="M200 78 C168 92 118 98 88 102 L88 278 C118 272 168 268 200 288 Z" fill="url(#bookPageL)" stroke="url(#bookSpine)" stroke-width="2.2"/>
<path d="M200 78 C232 92 282 98 312 102 L312 278 C282 272 232 268 200 288 Z" fill="url(#bookPageR)" stroke="url(#bookSpine)" stroke-width="2.2"/>
<path d="M200 78 L200 288" stroke="url(#bookSpine)" stroke-width="3.5" stroke-linecap="round"/>
<path class="book-line" d="M112 138 H176" stroke="#94a3b8" stroke-opacity="0.35" stroke-width="2" stroke-linecap="round"/>
<path class="book-line" d="M112 162 H168" stroke="#94a3b8" stroke-opacity="0.28" stroke-width="2" stroke-linecap="round"/>
<path class="book-line" d="M112 186 H172" stroke="#94a3b8" stroke-opacity="0.22" stroke-width="2" stroke-linecap="round"/>
<path class="book-line" d="M224 138 H288" stroke="#94a3b8" stroke-opacity="0.35" stroke-width="2" stroke-linecap="round"/>
<path class="book-line" d="M224 162 H280" stroke="#94a3b8" stroke-opacity="0.28" stroke-width="2" stroke-linecap="round"/>
<path class="book-line" d="M224 186 H284" stroke="#94a3b8" stroke-opacity="0.22" stroke-width="2" stroke-linecap="round"/>
<circle cx="200" cy="168" r="28" fill="rgba(10,14,23,0.92)" stroke="url(#bookSpine)" stroke-width="2.5"/>
<text text-anchor="middle" dominant-baseline="central" x="200" y="170" font-size="26">📖</text>
</g>
<circle class="book-spark" cx="96" cy="96" r="4" fill="#FFE66D"/>
<circle class="book-spark" cx="318" cy="120" r="3.5" fill="#4ECDC4"/>
<circle class="book-spark" cx="300" cy="260" r="3" fill="#FF6B6B"/>
<circle r="3.2" fill="#FFE66D"><animateMotion dur="4.2s" repeatCount="indefinite" path="M120 250 Q200 210 280 250"/></circle>
<circle r="2.8" fill="#4ECDC4"><animateMotion dur="5s" repeatCount="indefinite" path="M140 110 Q200 70 260 110" begin="0.8s"/></circle>
</svg>`
function coverAsBookDetail(): BookDetail {
return {
id: 'default',
title: COVER_BOOK.title,
subtitle: COVER_BOOK.subtitle,
author: COVER_BOOK.author,
cover_emoji: '📖',
description: COVER_BOOK.description,
tags: [...COVER_BOOK.viralTags],
price_fen: 0,
product_id: 'ebook_default',
unlock_percent: 100,
is_free: true,
chapter_count: COVER_BOOK.chapters.length,
word_count: 0,
rating: 0,
chapters: COVER_BOOK.chapters.map((ch, i) => ({
id: ch.slug,
title: ch.title,
order: i + 1,
})),
}
}
const HOOK_LINES = COVER_BOOK.hooks.map((h) => `${h.emoji} ${h.text}`)
const CHIP_TAGS = COVER_BOOK.viralTags.slice(0, 3)
function BookPageInner() {
const theme = useNomadroTheme()
// 封面视觉:正式 COVER_BOOK;提审时用线上 audit 书名(失联才兜底文案)
const [book, setBook] = useState<BookDetail | null>(coverAsBookDetail())
const [apiBook, setApiBook] = useState<BookDetail | null>(null)
const [loading, setLoading] = useState(false)
const [error, setError] = useState('')
const [progress, setProgress] = useState<ReadingProgress | null>(null)
const [tw, setTw] = useState('')
const [audit, setAudit] = useState(() => resolveBookAudit(getCachedRemoteConfig()))
const auditKeyRef = useRef(`${audit.reviewMode}:${audit.bookId}`)
useLoad(() => {
trackPage('pages/book/index', '小册封面')
loadBook()
})
useDidShow(() => {
void loadRemoteConfig(true).then((r) => {
applyAudit(resolveBookAudit(r.config))
})
loadBook(true)
})
useEffect(() => {
return subscribeRemoteConfig((r) => {
applyAudit(resolveBookAudit(r.config))
})
}, [])
useEffect(() => {
applyH5Theme(theme)
}, [theme])
function applyAudit(next: ReturnType<typeof resolveBookAudit>) {
const key = `${next.reviewMode}:${next.bookId}`
const changed = key !== auditKeyRef.current
auditKeyRef.current = key
setAudit(next)
const pid = next.reviewMode ? next.bookId || 'audit' : 'nomad'
setProgress(getReadingProgress(pid))
if (changed) {
void loadBook(true)
}
}
// 对齐正式封面:hooks 轮播打字机(提审同样跑)
useEffect(() => {
if (loading) return
const phrases = HOOK_LINES.length ? HOOK_LINES : [COVER_BOOK.subtitle]
let phraseIdx = 0
let charIdx = 0
let deleting = false
let timer: ReturnType<typeof setTimeout>
const type = () => {
const current = phrases[phraseIdx] || ''
if (!deleting) {
setTw(current.substring(0, charIdx + 1))
charIdx++
if (charIdx === current.length) {
deleting = true
timer = setTimeout(type, 2600)
return
}
timer = setTimeout(type, 42)
} else {
setTw(current.substring(0, charIdx - 1))
charIdx--
if (charIdx === 0) {
deleting = false
phraseIdx = (phraseIdx + 1) % phrases.length
}
timer = setTimeout(type, 22)
}
}
timer = setTimeout(type, 380)
return () => clearTimeout(timer)
}, [loading])
async function loadBook(silent = false) {
setError('')
const a = resolveBookAudit(getCachedRemoteConfig())
setAudit(a)
auditKeyRef.current = `${a.reviewMode}:${a.bookId}`
// 正式:封面品牌视觉;提审:立刻换成审核版书名/章节,保证开关可见
if (!a.reviewMode) {
setBook(coverAsBookDetail())
setApiBook(null)
}
try {
if (!silent) setLoading(true)
const bookId = a.reviewMode ? a.bookId || 'audit' : 'nomad'
const data = await fetchBook(bookId)
setApiBook(data)
if (a.reviewMode && data) {
setBook({
...coverAsBookDetail(),
id: data.id,
title: data.title || '数字游民入门指南',
subtitle: data.subtitle || '远程办公 · 自律生活 · 稳健成长',
description: data.description || coverAsBookDetail().description,
chapters: data.chapters?.length ? data.chapters : coverAsBookDetail().chapters,
is_free: true,
unlock_percent: 100,
})
}
} catch (e: any) {
if (a.reviewMode) {
setBook({
...coverAsBookDetail(),
id: a.bookId || 'audit',
title: '数字游民入门指南',
subtitle: '远程办公 · 自律生活 · 稳健成长',
is_free: true,
unlock_percent: 100,
})
}
track('error', {
page: 'pages/book/index',
label: 'load_book',
props: { msg: String(e.message || e) },
})
} finally {
if (!silent) setLoading(false)
}
}
const continueChapter = useMemo(() => {
const chapters = apiBook?.chapters?.length ? apiBook.chapters : book?.chapters
if (!chapters || !progress?.chapterId) return null
const found = chapters.find((c) => String(c.id) === String(progress.chapterId))
if (found) return found
return { id: progress.chapterId, title: `第 ${progress.chapterIndex + 1} 章` }
}, [book, apiBook, progress])
// 必须在一切 early-return 之前:reviewMode 冷启动 false→true 时否则 hooks 数量变化 → 黑屏
const safe = useMemo(() => getSafeAreaMetrics(), [])
const safeStyle = useMemo(
() => ({
['--safe-status-bar' as string]: `${safe.statusBarHeight}px`,
['--safe-nav-bar' as string]: `${safe.navBarHeight}px`,
['--safe-menu-pad' as string]: `${safe.menuRightPad}px`,
['--safe-header' as string]: `${safe.headerHeight}px`,
}),
[safe],
)
function goRead() {
const a = resolveBookAudit(getCachedRemoteConfig())
// 提审 / 正式同一套 vip-ebook 阅读壳(样式一致);提审只换正文来源
const bookId = a.reviewMode ? a.bookId || 'audit' : 'nomad'
const continuing = !!progress?.chapterId
trackClick(continuing ? '继续阅读' : '开始阅读', {
book_id: bookId,
has_progress: continuing,
audit: a.reviewMode,
})
track('read_start', {
page: 'pages/book/index',
label: continuing ? '继续阅读' : '开始阅读',
props: { book_id: bookId, audit: a.reviewMode },
})
goPage('/pages/vip-ebook/index?id=nomad')
}
if (loading && !book) {
return (
<H5Box className="page-shell book-flow book-flow--error">
<CommunityNavbar />
<H5Box className="book-error">
<H5Txt className="book-error-hint">加载中…</H5Txt>
</H5Box>
</H5Box>
)
}
if (error || !book) {
return (
<H5Box className="page-shell book-flow book-flow--error">
<CommunityNavbar />
<H5Box className="book-error">
<H5Txt className="book-error-title">暂时打不开</H5Txt>
<H5Txt className="book-error-hint">{error || '请稍后再试'}</H5Txt>
<Button
className="btn btn-primary"
onClick={() => {
trackClick('首页重试')
loadBook()
}}
>
再试一次
</Button>
</H5Box>
</H5Box>
)
}
const hasProgress = !!continueChapter
const unlockSource = apiBook || book
const isFree = !!(unlockSource.is_free || (unlockSource.unlock_percent ?? 0) >= 100)
const ctaText = hasProgress ? '📖 继续阅读' : '📖 开始阅读'
const ctaHint = hasProgress
? progress?.updatedAt
? `上次翻到 · ${formatAgo(progress.updatedAt)}`
: '接着上次的地方'
: isFree
? '点一下,直接进入正文'
: '先翻开前面的章节'
const displayTitle = audit.reviewMode
? book.title || '数字游民入门指南'
: COVER_BOOK.title
const tagParts = [
audit.reviewMode
? book.subtitle || '远程办公 · 自律生活 · 稳健成长'
: book.subtitle || COVER_BOOK.subtitle || '低成本工作室',
]
return (
<H5Box
className="page-shell home-flow home-flow--hero-only book-flow"
data-theme={theme}
style={safeStyle}
>
<CommunityNavbar />
<H5Box className="hero" id="hero">
<H5Box className="hero-bg-shapes" aria-hidden>
<H5Box className="shape shape-1" />
<H5Box className="shape shape-2" />
<H5Box className="shape shape-3" />
</H5Box>
<H5Box className="hero-inner">
<H5Box className="hero-top">
<H5Box className="hero-content">
<H5Box className="hero-title book-hero-title">
<H5Txt className="hero-title-line book-title-brand">{displayTitle}</H5Txt>
<H5Box className="hero-title-line book-tagline">
<H5Txt>{tagParts[0]}</H5Txt>
</H5Box>
</H5Box>
<H5Txt className="hero-title-spark" aria-hidden>
✨
</H5Txt>
<H5Txt className="hero-subtitle book-typewriter">
{tw}
<H5Txt className="typewriter-cursor">|</H5Txt>
</H5Txt>
</H5Box>
<H5Box className="hero-visual" onClick={goRead}>
<H5Box className="book-visual">
{isH5 ? (
<H5Box className="book-visual-host" html={BOOK_VISUAL_SVG} />
) : (
<H5Box className="book-visual-css" aria-hidden>
<H5Box className="book-visual-css-glow" />
<H5Box className="book-visual-css-body">
<H5Box className="book-visual-css-spine" />
<H5Txt className="book-visual-css-emoji">📖</H5Txt>
</H5Box>
</H5Box>
)}
<H5Box className="book-float-chips social-float-chips">
{CHIP_TAGS.map((tag, i) => (
<H5Box key={tag} className={`social-chip sc-${i + 1}`}>
<H5Txt>
{i === 0 ? '🏷 ' : i === 1 ? '⚡ ' : '🌐 '}
{tag}
</H5Txt>
</H5Box>
))}
</H5Box>
</H5Box>
</H5Box>
</H5Box>
<H5Box className="hero-bottom">
<H5Box className="hero-actions book-actions">
<Button className="btn btn-primary book-cta" onClick={goRead}>
{ctaText}
</Button>
<H5Txt className="book-cta-hint">{ctaHint}</H5Txt>
</H5Box>
</H5Box>
</H5Box>
</H5Box>
</H5Box>
)
}
/** 正式 / 提审同一封面壳;点阅读都进 vip-ebook(提审换线上 audit 正文) */
export default function BookCoverPage() {
useDidShow(() => {
void loadRemoteConfig(true)
// 预下载阅读壳,避免提审点开黑屏
try {
void Taro.loadSubPackage?.({ name: 'vip-ebook' })
} catch {
/* ignore */
}
})
return (
<MiniModuleGate moduleKey="book">
<BookPageInner />
</MiniModuleGate>
)
}