xiaoshuo commited on
Commit
5f674d2
·
1 Parent(s): 8214b38

番茄热榜:抓取分类榜、解码、趋势分析、总纲规划

Browse files
fanqie/mount.js CHANGED
@@ -23,6 +23,7 @@ module.exports = function mountFanqie(app, passwordOk, express) {
23
  app.use('/fanqie/api/materials', materials)
24
  // 母题库 v2(第二次提炼,按人物/关系/事件/逻辑约束检索 + 组稿),数据直接读 R2 motif_v2/
25
  try { app.use('/fanqie/api/motif2', require('./motif2.js')(express)) } catch (e) { console.error('motif2 mount failed:', e) }
 
26
  app.get('/fanqie/api/health', (_req, res) => res.json({ ok: true }))
27
 
28
  // 小说项目工作台:项目、作品圣经、大纲、章节、版本和检查结果全部保存到 R2。
 
23
  app.use('/fanqie/api/materials', materials)
24
  // 母题库 v2(第二次提炼,按人物/关系/事件/逻辑约束检索 + 组稿),数据直接读 R2 motif_v2/
25
  try { app.use('/fanqie/api/motif2', require('./motif2.js')(express)) } catch (e) { console.error('motif2 mount failed:', e) }
26
+ try { app.use('/fanqie/api/rank', require('./rank.js')(express)) } catch (e) { console.error('rank mount failed:', e) }
27
  app.get('/fanqie/api/health', (_req, res) => res.json({ ok: true }))
28
 
29
  // 小说项目工作台:项目、作品圣经、大纲、章节、版本和检查结果全部保存到 R2。
fanqie/rank.js ADDED
@@ -0,0 +1,555 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 'use strict'
2
+ // 番茄热榜:抓取番茄小说官网分类榜(阅读榜 + 新书榜)→ 解码防爬字体 → 统计分析 → 总纲规划任务。
3
+ // 所有数据存 R2 的 fanqie_rank/ 目录;不影响其他功能。
4
+ // fanqie_rank/index.json 快照目录
5
+ // fanqie_rank/snapshots/YYYY-MM-DD.json.gz 当天全部榜单
6
+ // fanqie_rank/books.json.gz 书籍详情缓存(明文书名/简介/官方标签)
7
+ // fanqie_rank/fontmap.json 防爬字体码表(自动从书籍详情页对照学习)
8
+ // fanqie_rank/ai/YYYY-MM-DD.json AI 解读(由 AI 阅读当天数据后写入)
9
+ // fanqie_rank/plans/index.json, plans/<id>.json 总纲规划任务与结果
10
+ const crypto = require('crypto')
11
+ const zlib = require('zlib')
12
+
13
+ const ENDPOINT = process.env.R2_ENDPOINT
14
+ const BUCKET = process.env.R2_BUCKET
15
+ const AK = process.env.R2_ACCESS_KEY_ID
16
+ const SK = process.env.R2_SECRET_ACCESS_KEY
17
+ const P = 'fanqie_rank/'
18
+ const SITE = 'https://fanqienovel.com'
19
+ const UA = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0 Safari/537.36'
20
+ const TAG_TOP = Number(process.env.RANK_TAG_TOP || 30) // 每个榜单前多少本抓取详情页(官方标签)
21
+
22
+ /* ---------------- R2(SigV4,UNSIGNED-PAYLOAD) ---------------- */
23
+ const sha = v => crypto.createHash('sha256').update(v).digest('hex')
24
+ const hm = (k, v, enc) => crypto.createHmac('sha256', k).update(v).digest(enc)
25
+ const enc = v => encodeURIComponent(String(v)).replace(/[!'()*]/g, c => `%${c.charCodeAt(0).toString(16).toUpperCase()}`)
26
+ async function r2(method, key, body, type) {
27
+ if (!ENDPOINT || !BUCKET || !AK || !SK) { const e = new Error('R2 未配置'); e.status = 503; throw e }
28
+ const url = new URL(ENDPOINT)
29
+ url.pathname = '/' + [url.pathname.replace(/^\/+|\/+$/g, ''), BUCKET, ...key.split('/')].filter(Boolean).map(enc).join('/')
30
+ const amz = new Date().toISOString().replace(/[:-]|\.\d{3}/g, '')
31
+ const day = amz.slice(0, 8)
32
+ const headers = { host: url.host.toLowerCase(), 'x-amz-content-sha256': 'UNSIGNED-PAYLOAD', 'x-amz-date': amz }
33
+ if (type) headers['content-type'] = type
34
+ const names = Object.keys(headers).sort()
35
+ const creq = [method, url.pathname, '', names.map(k => `${k}:${headers[k]}`).join('\n') + '\n', names.join(';'), 'UNSIGNED-PAYLOAD'].join('\n')
36
+ const scope = `${day}/auto/s3/aws4_request`
37
+ const sts = ['AWS4-HMAC-SHA256', amz, scope, sha(creq)].join('\n')
38
+ const kS = hm(hm(hm(hm(`AWS4${SK}`, day), 'auto'), 's3'), 'aws4_request')
39
+ headers.authorization = `AWS4-HMAC-SHA256 Credential=${AK}/${scope}, SignedHeaders=${names.join(';')}, Signature=${hm(kS, sts, 'hex')}`
40
+ delete headers.host
41
+ let last
42
+ for (let i = 0; i < 3; i++) {
43
+ try {
44
+ const r = await fetch(url, { method, headers, body })
45
+ if (method === 'GET' && r.status === 404) return null
46
+ if (r.ok) return method === 'GET' ? Buffer.from(await r.arrayBuffer()) : true
47
+ last = new Error(`R2 ${method} ${r.status}`)
48
+ } catch (e) { last = e }
49
+ await sleep(400 * (i + 1))
50
+ }
51
+ throw last
52
+ }
53
+ const getJ = async (key, fb = null) => { const b = await r2('GET', key); if (!b) return fb; return JSON.parse((key.endsWith('.gz') ? zlib.gunzipSync(b) : b).toString('utf8')) }
54
+ const putJ = (key, o) => key.endsWith('.gz')
55
+ ? r2('PUT', key, zlib.gzipSync(Buffer.from(JSON.stringify(o))), 'application/gzip')
56
+ : r2('PUT', key, Buffer.from(JSON.stringify(o)), 'application/json; charset=utf-8')
57
+ const sleep = ms => new Promise(ok => setTimeout(ok, ms))
58
+ const now = () => new Date().toISOString()
59
+ const cnDate = (d = new Date()) => new Date(d.getTime() + 8 * 3600e3).toISOString().slice(0, 10)
60
+ const cnHour = (d = new Date()) => new Date(d.getTime() + 8 * 3600e3).getUTCHours()
61
+ const rid = p => `${p}_${Date.now().toString(36)}_${crypto.randomBytes(3).toString('hex')}`
62
+
63
+ /* ---------------- 防爬字体解码 ---------------- */
64
+ // 番茄网页把常用字替换成私有区字符(U+E000–U+F8FF),配合自定义字体显示。
65
+ // 书籍详情页给出的是明文,所以用「榜单里的密文」和「详情页明文」逐字对照,就能学到码表。
66
+ const isPUA = ch => { const c = ch.codePointAt(0); return c >= 0xe000 && c <= 0xf8ff }
67
+ let FONT = { map: {}, updated_at: '' }
68
+ const decode = s => [...String(s || '')].map(ch => (isPUA(ch) ? (FONT.map[ch.codePointAt(0)] ?? '□') : ch)).join('')
69
+ const unknownIn = s => [...String(s || '')].filter(ch => isPUA(ch) && FONT.map[ch.codePointAt(0)] === undefined)
70
+ function learn(cipher, plain) {
71
+ const a = [...String(cipher || '')], b = [...String(plain || '')]
72
+ const n = Math.min(a.length, b.length)
73
+ if (n < 2) return 0
74
+ // 先校验:非密文位置必须基本一致,才认为对齐
75
+ let same = 0, plainCnt = 0
76
+ for (let i = 0; i < n; i++) if (!isPUA(a[i])) { plainCnt++; if (a[i] === b[i]) same++ }
77
+ if (plainCnt && same / plainCnt < 0.9) return 0
78
+ let added = 0
79
+ for (let i = 0; i < n; i++) {
80
+ if (!isPUA(a[i]) || isPUA(b[i])) continue
81
+ const c = a[i].codePointAt(0)
82
+ if (FONT.map[c] === undefined) { FONT.map[c] = b[i]; added++ }
83
+ }
84
+ return added
85
+ }
86
+
87
+ /* ---------------- 抓取 ---------------- */
88
+ const FALLBACK_CATS = {
89
+ male: [['1141', '西方奇幻'], ['1140', '东方仙侠'], ['8', '科幻末世'], ['261', '都市日常'], ['124', '都市修真'], ['1014', '都市高武'], ['273', '历史古代'], ['27', '战神赘婿'], ['263', '都市种田'], ['258', '传统玄幻'], ['272', '历史脑洞'], ['539', '悬疑脑洞'], ['262', '都市脑洞'], ['257', '玄幻脑洞'], ['751', '悬疑灵异'], ['504', '抗战谍战'], ['746', '游戏体育'], ['718', '动漫衍生'], ['1016', '男频衍生']].map(([id, name]) => ({ id, name })),
90
+ female: [['1139', '古风世情'], ['8', '科幻末世'], ['746', '游戏体育'], ['1015', '女频衍生'], ['248', '玄幻言情'], ['23', '种田'], ['79', '年代'], ['267', '现言脑洞'], ['246', '宫斗宅斗'], ['539', '悬疑脑洞'], ['253', '古言脑洞'], ['24', '快穿'], ['749', '青春甜宠'], ['745', '星光璀璨'], ['747', '女频悬疑'], ['750', '职场婚恋'], ['748', '豪门总裁'], ['1017', '民国言情']].map(([id, name]) => ({ id, name })),
91
+ }
92
+ async function http(url, { json = false, timeout = 25000 } = {}) {
93
+ let last
94
+ for (let i = 0; i < 3; i++) {
95
+ const ac = new AbortController(); const t = setTimeout(() => ac.abort(), timeout)
96
+ try {
97
+ const r = await fetch(url, { headers: { 'user-agent': UA, accept: json ? 'application/json' : 'text/html', 'accept-language': 'zh-CN,zh;q=0.9', referer: SITE + '/rank' }, signal: ac.signal })
98
+ if (!r.ok) throw new Error(`HTTP ${r.status}`)
99
+ return json ? await r.json() : await r.text()
100
+ } catch (e) { last = e } finally { clearTimeout(t) }
101
+ await sleep(800 * (i + 1))
102
+ }
103
+ throw new Error(`抓取失败 ${url}:${last?.message || last}`)
104
+ }
105
+ function stateOf(html) {
106
+ const i = html.indexOf('window.__INITIAL_STATE__=')
107
+ if (i < 0) return null
108
+ const s = html.slice(i + 'window.__INITIAL_STATE__='.length)
109
+ // 找到与第一个 { 匹配的 }(跳过字符串)
110
+ let depth = 0, inStr = false, esc = false
111
+ for (let k = 0; k < s.length; k++) {
112
+ const ch = s[k]
113
+ if (inStr) { if (esc) esc = false; else if (ch === '\\') esc = true; else if (ch === '"') inStr = false; continue }
114
+ if (ch === '"') inStr = true
115
+ else if (ch === '{') depth++
116
+ else if (ch === '}') { depth--; if (depth === 0) { try { return JSON.parse(s.slice(0, k + 1).replace(/\bundefined\b/g, 'null')) } catch { return null } } }
117
+ }
118
+ return null
119
+ }
120
+ async function categories() {
121
+ try {
122
+ const st = stateOf(await http(`${SITE}/rank/1_2_1141`))
123
+ const c = st?.rank?.rankCategoryTypeList
124
+ if (c?.male?.length && c?.female?.length) return c
125
+ } catch (e) { console.error('rank categories', e.message) }
126
+ return FALLBACK_CATS
127
+ }
128
+ async function rankList(gender, mold, cid) {
129
+ const url = `${SITE}/api/rank/category/list?app_id=2503&rank_list_type=3&offset=0&limit=100&category_id=${cid}&rank_version=&gender=${gender}&rankMold=${mold}`
130
+ const d = await http(url, { json: true })
131
+ if (d?.code !== 0) throw new Error(d?.message || '榜单接口返回异常')
132
+ return d.data?.book_list || []
133
+ }
134
+ // 书籍详情页:只读到页面状态里需要的那一段就停止,节省流量
135
+ const jsonStr = (s, key) => { const m = s.match(new RegExp(`"${key}":("(?:[^"\\\\]|\\\\.)*")`)); if (!m) return ''; try { return JSON.parse(m[1]) } catch { return '' } }
136
+ async function bookPage(id) {
137
+ const ac = new AbortController(); const t = setTimeout(() => ac.abort(), 30000)
138
+ try {
139
+ const r = await fetch(`${SITE}/page/${id}`, { headers: { 'user-agent': UA, accept: 'text/html', 'accept-language': 'zh-CN,zh;q=0.9' }, signal: ac.signal })
140
+ if (!r.ok) throw new Error(`HTTP ${r.status}`)
141
+ const reader = r.body.getReader(); const dec = new TextDecoder(); let html = ''
142
+ for (;;) {
143
+ const { done, value } = await reader.read()
144
+ if (done) break
145
+ html += dec.decode(value, { stream: true })
146
+ if (html.includes('"chapterListWithVolume"') || html.length > 600000) { try { await reader.cancel() } catch {} break }
147
+ }
148
+ const i = html.indexOf('"page":{')
149
+ if (i < 0) { if (html.length < 2000) { const e = new Error('throttled'); e.throttled = true; throw e } return null }
150
+ const seg = html.slice(i, i + 40000)
151
+ let cats = []
152
+ try { cats = JSON.parse(jsonStr(seg, 'categoryV2') || '[]').map(c => ({ n: c.Name, d: c.Dim })) } catch {}
153
+ return { t: jsonStr(seg, 'bookName'), a: jsonStr(seg, 'abstract').slice(0, 600), cats, at: now() }
154
+ } finally { clearTimeout(t) }
155
+ }
156
+ async function pool(items, n, fn) {
157
+ let i = 0
158
+ await Promise.all(Array.from({ length: n }, async () => { while (i < items.length) { const k = i++; await fn(items[k], k) } }))
159
+ }
160
+
161
+ // 慢速抓详情页:被限流(返回空页面)时整体暂停,逐步加长等待;连续限流太多次就先停,留给下一轮补
162
+ async function fetchDetails(list, { conc = 2, gap = 600, maxCool = 4, onEach } = {}) {
163
+ let cool = 0, wait = 60e3, stopped = false, ok = 0, pauseUntil = 0
164
+ await pool(list, conc, async b => {
165
+ if (stopped) return
166
+ for (;;) {
167
+ const w = pauseUntil - Date.now(); if (w > 0) await sleep(w)
168
+ if (stopped) return
169
+ try {
170
+ const d = await bookPage(b.bookId || b.id)
171
+ if (d) { BOOKS[b.bookId || b.id] = d; ok++; if (b.bookName) learn(b.bookName, d.t), learn(b.abstract, d.a) }
172
+ break
173
+ } catch (e) {
174
+ if (!e.throttled) break
175
+ if (Date.now() < pauseUntil) continue
176
+ cool++
177
+ if (cool > maxCool) { stopped = true; return }
178
+ say(`详情页被限流,暂停 ${Math.round(wait / 1000)} 秒后继续(第 ${cool} 次)`)
179
+ pauseUntil = Date.now() + wait; wait = Math.min(wait * 2, 10 * 60e3)
180
+ }
181
+ }
182
+ if (onEach) await onEach()
183
+ await sleep(gap)
184
+ })
185
+ return { ok, stopped }
186
+ }
187
+
188
+ const JOB = { running: false, step: '', done: 0, total: 0, started_at: '', finished_at: '', error: '', log: [] }
189
+ const say = m => { JOB.step = m; JOB.log.push(`${new Date().toISOString().slice(11, 19)} ${m}`); if (JOB.log.length > 60) JOB.log.shift() }
190
+ let BOOKS = null
191
+ async function loadState() {
192
+ if (!FONT.updated_at) FONT = await getJ(P + 'fontmap.json', { map: {}, updated_at: '' }) || { map: {}, updated_at: '' }
193
+ if (!BOOKS) BOOKS = await getJ(P + 'books.json.gz', {}) || {}
194
+ }
195
+
196
+ async function scrape() {
197
+ if (JOB.running) return JOB
198
+ Object.assign(JOB, { running: true, step: '', done: 0, total: 0, started_at: now(), finished_at: '', error: '', log: [] })
199
+ ;(async () => {
200
+ try {
201
+ await loadState()
202
+ const font0 = Object.keys(FONT.map).length
203
+ say('读取分类列表')
204
+ const cats = await categories()
205
+ const jobs = []
206
+ for (const [g, key] of [[1, 'male'], [0, 'female']]) for (const c of cats[key] || []) for (const mold of [2, 1]) jobs.push({ gender: g, mold, cid: String(c.id), cname: c.name })
207
+ JOB.total = jobs.length
208
+ say(`抓取 ${jobs.length} 个榜单(男频/女频 × 分类 × 阅读榜/新书榜)`)
209
+ const lists = []
210
+ await pool(jobs, 3, async j => {
211
+ try { j.raw = await rankList(j.gender, j.mold, j.cid) } catch (e) { j.raw = []; j.err = e.message }
212
+ lists.push(j); JOB.done++
213
+ await sleep(250)
214
+ })
215
+ const failed = lists.filter(l => l.err)
216
+ if (failed.length === lists.length) throw new Error('所有榜单都抓取失败:' + (failed[0]?.err || ''))
217
+ // 需要详情页的书:每榜前 TAG_TOP 本里还没有缓存的;以及含未知密文字的书(用于学码表)
218
+ const need = new Map()
219
+ for (const l of lists) l.raw.forEach((b, i) => { if (i < TAG_TOP && !BOOKS[b.bookId]) need.set(b.bookId, b) })
220
+ const unk = new Set()
221
+ for (const l of lists) for (const b of l.raw) for (const ch of unknownIn(b.bookName + b.abstract)) unk.add(ch)
222
+ // 码表还缺字:挑覆盖缺字最多的书补抓(每次最多 150 本)
223
+ if (unk.size) {
224
+ const covered = new Set()
225
+ for (const b of need.values()) for (const ch of unknownIn(b.bookName + b.abstract)) covered.add(ch)
226
+ const cand = []
227
+ for (const l of lists) for (const b of l.raw) if (!need.has(b.bookId) && !BOOKS[b.bookId]) cand.push(b)
228
+ let extra = 0
229
+ for (const b of cand.sort((x, y) => unknownIn(y.bookName + y.abstract).length - unknownIn(x.bookName + x.abstract).length)) {
230
+ if (extra >= 150) break
231
+ const u = unknownIn(b.bookName + b.abstract).filter(ch => !covered.has(ch))
232
+ if (!u.length) continue
233
+ u.forEach(ch => covered.add(ch)); need.set(b.bookId, b); extra++
234
+ }
235
+ }
236
+ say(`读取 ${need.size} 本书的详情页(官方标签 + 明文简介,已缓存的跳过)`)
237
+ JOB.done = 0; JOB.total = need.size
238
+ const arr = [...need.values()]
239
+ const fr = await fetchDetails(arr, { onEach: async () => {
240
+ JOB.done++
241
+ if (JOB.done % 100 === 0) { await putJ(P + 'books.json.gz', BOOKS).catch(() => {}); await putJ(P + 'fontmap.json', { ...FONT, updated_at: now() }).catch(() => {}) }
242
+ } })
243
+ if (fr.stopped) say(`详情页限流较严,本轮先读到这里(成功 ${fr.ok} 本),剩下的由后台慢慢补`)
244
+ // 已缓存的书也可以拿来补码表
245
+ for (const l of lists) for (const b of l.raw) { const d = BOOKS[b.bookId]; if (d && unknownIn(b.bookName + b.abstract).length) learn(b.bookName, d.t), learn(b.abstract, d.a) }
246
+ const learned = Object.keys(FONT.map).length - font0
247
+ FONT.updated_at = now()
248
+ await putJ(P + 'fontmap.json', FONT)
249
+ await putJ(P + 'books.json.gz', BOOKS)
250
+ say(`码表 ${Object.keys(FONT.map).length} 字(本次新学 ${learned})`)
251
+ // 组装快照
252
+ let chars = 0, bad = 0
253
+ const out = lists.sort((a, b) => b.gender - a.gender || a.cid.localeCompare(b.cid) || b.mold - a.mold).map(l => ({
254
+ gender: l.gender, mold: l.mold, cid: l.cid, cname: l.cname, err: l.err || undefined,
255
+ books: l.raw.map(b => {
256
+ const d = BOOKS[b.bookId]
257
+ const title = d?.t || decode(b.bookName)
258
+ const abs = (d?.a || decode(b.abstract)).slice(0, 400)
259
+ chars += title.length + abs.length; bad += (title + abs).split('□').length - 1
260
+ return {
261
+ pos: Number(b.currentPos), id: b.bookId, title, author: decode(b.author), abs,
262
+ words: Number(b.wordNumber) || 0, reads: Number(b.read_count) || 0, done: String(b.creationStatus) === '0',
263
+ diff: Number(b.rankPosDiff) || 0, upd: Number(b.lastChapterUpdateTime) || 0, last: decode(b.lastChapterTitle),
264
+ tags: d?.cats?.map(c => c.n) || null, main: d?.cats?.find(c => c.d === 1)?.n || '',
265
+ }
266
+ }),
267
+ }))
268
+ const date = cnDate()
269
+ const snap = { date, at: now(), lists: out, quality: { chars, unknown: bad }, tag_top: TAG_TOP }
270
+ await putJ(`${P}snapshots/${date}.json.gz`, snap)
271
+ const idx = await getJ(P + 'index.json', { snapshots: [] }) || { snapshots: [] }
272
+ const books = new Set(); out.forEach(l => l.books.forEach(b => books.add(b.id)))
273
+ idx.snapshots = [{ date, at: snap.at, lists: out.length, failed: failed.length, books: books.size }, ...idx.snapshots.filter(s => s.date !== date)].slice(0, 400)
274
+ idx.latest = date
275
+ await putJ(P + 'index.json', idx)
276
+ CACHE.clear()
277
+ say(`完成:${out.length} 个榜单、${books.size} 本书${failed.length ? `,${failed.length} 个榜单失败` : ''};无法解码的字 ${bad}/${chars}`)
278
+ } catch (e) {
279
+ JOB.error = e.message || String(e); say('失败:' + JOB.error)
280
+ } finally { JOB.running = false; JOB.finished_at = now() }
281
+ })()
282
+ return JOB
283
+ }
284
+
285
+ // 后台补标签:把最新快照里每榜前 TAG_TOP 本还没有官方标签的书,慢慢补上
286
+ function applyBooks(snap) {
287
+ let n = 0
288
+ for (const l of snap.lists) for (const b of l.books) {
289
+ const d = BOOKS[b.id]
290
+ if (!d || b.tags) continue
291
+ b.tags = d.cats?.map(c => c.n) || []; b.main = d.cats?.find(c => c.d === 1)?.n || ''
292
+ if (d.t) b.title = d.t
293
+ if (d.a) b.abs = d.a.slice(0, 400)
294
+ n++
295
+ }
296
+ return n
297
+ }
298
+ function missingOf(snap) {
299
+ const m = new Map()
300
+ for (const l of snap.lists) l.books.slice(0, snap.tag_top || TAG_TOP).forEach(b => { if (!b.tags && !BOOKS[b.id]) m.set(b.id, b) })
301
+ return [...m.values()]
302
+ }
303
+ async function enrich(limit = 300) {
304
+ if (JOB.running) return JOB
305
+ Object.assign(JOB, { running: true, step: '', done: 0, total: 0, started_at: now(), finished_at: '', error: '', log: [] })
306
+ ;(async () => {
307
+ try {
308
+ await loadState()
309
+ const idx = await getJ(P + 'index.json', { snapshots: [] })
310
+ if (!idx?.latest) throw new Error('还没有快照')
311
+ const key = `${P}snapshots/${idx.latest}.json.gz`
312
+ const snap = await getJ(key, null)
313
+ const miss = missingOf(snap).slice(0, limit)
314
+ JOB.total = miss.length
315
+ say(`补全 ${idx.latest} 榜单书籍标签:本轮 ${miss.length} 本`)
316
+ const fr = await fetchDetails(miss, { conc: 1, gap: 1500, maxCool: 1, onEach: async () => { JOB.done++; if (JOB.done % 50 === 0) await putJ(P + 'books.json.gz', BOOKS).catch(() => {}) } })
317
+ await putJ(P + 'books.json.gz', BOOKS)
318
+ const n = applyBooks(snap)
319
+ if (n) { await putJ(key, snap); CACHE.clear() }
320
+ say(`补上 ${n} 本书的标签${fr.stopped ? '(遇到限流,稍后继续)' : ''};还缺 ${missingOf(snap).length} 本`)
321
+ } catch (e) { JOB.error = e.message || String(e); say('失败:' + JOB.error) } finally { JOB.running = false; JOB.finished_at = now() }
322
+ })()
323
+ return JOB
324
+ }
325
+
326
+ /* ---------------- 分析(纯统计,数字说话;解读交给 AI) ---------------- */
327
+ const CACHE = new Map()
328
+ async function snapshot(date) {
329
+ const idx = await getJ(P + 'index.json', { snapshots: [] }) || { snapshots: [] }
330
+ const d = date || idx.latest
331
+ if (!d) return { idx, snap: null }
332
+ const k = 'snap:' + d
333
+ if (!CACHE.has(k)) CACHE.set(k, await getJ(`${P}snapshots/${d}.json.gz`, null))
334
+ return { idx, snap: CACHE.get(k) }
335
+ }
336
+ const sum = a => a.reduce((x, y) => x + y, 0)
337
+ const median = a => { if (!a.length) return 0; const s = [...a].sort((x, y) => x - y); return s[Math.floor(s.length / 2)] }
338
+ const GEN = { 1: '男频', 0: '女频' }
339
+ const MOLD = { 2: '阅读榜', 1: '新书榜' }
340
+ // 简介开头的【…】是作者自己写的卖点标签
341
+ function labelsOf(abs) {
342
+ const out = []
343
+ for (const m of String(abs || '').matchAll(/[【\[]([^】\]]{2,60})[】\]]/g)) {
344
+ for (const t of m[1].split(/[\//++、,,||\s×xX]+/)) { const s = t.trim().replace(/^[##]/, ''); if (s.length >= 2 && s.length <= 10 && !/□/.test(s)) out.push(s) }
345
+ }
346
+ return out
347
+ }
348
+ function tagStats(books, catNames) {
349
+ // books: [{tags, reads, w}],按读者数开方加权,避免头部一本书压倒一切
350
+ const m = new Map(); let tw = 0, n = 0
351
+ for (const b of books) {
352
+ if (!b.tags) continue
353
+ n++; const w = Math.sqrt(Math.max(1, b.reads)); tw += w
354
+ for (const t of new Set(b.tags)) { if (catNames.has(t)) continue; const x = m.get(t) || { k: t, n: 0, w: 0 }; x.n++; x.w += w; m.set(t, x) }
355
+ }
356
+ return { n, list: [...m.values()].map(x => ({ k: x.k, n: x.n, share: n ? x.n / n : 0, heat: tw ? x.w / tw : 0 })).sort((a, b) => b.heat - a.heat) }
357
+ }
358
+ function analyze(snap, prev) {
359
+ const catNames = new Set(snap.lists.map(l => l.cname)); catNames.add('男频'); catNames.add('女频')
360
+ for (const l of snap.lists) for (const b of l.books) if (b.main) catNames.add(b.main)
361
+ const prevMap = new Map((prev?.lists || []).map(l => [`${l.gender}_${l.mold}_${l.cid}`, l]))
362
+ const cats = {}
363
+ for (const l of snap.lists) {
364
+ const key = `${l.gender}_${l.cid}`
365
+ const c = cats[key] || (cats[key] = { gender: l.gender, g: GEN[l.gender], cid: l.cid, name: l.cname })
366
+ const top20 = l.books.slice(0, 20), top10 = l.books.slice(0, 10)
367
+ const pl = prevMap.get(`${l.gender}_${l.mold}_${l.cid}`)
368
+ const prevIds = new Set((pl?.books || []).slice(0, 10).map(b => b.id))
369
+ const s = {
370
+ total: sum(l.books.map(b => b.reads)), top10: sum(top10.map(b => b.reads)), head: l.books[0]?.reads || 0,
371
+ words_med: median(top20.map(b => b.words)), done_share: top20.length ? top20.filter(b => b.done).length / top20.length : 0,
372
+ prev_total: pl ? sum(pl.books.map(b => b.reads)) : null,
373
+ new_in_top10: pl ? top10.filter(b => !prevIds.has(b.id)).map(b => b.title) : [],
374
+ risers: l.books.filter(b => b.diff > 0).sort((a, b) => b.diff - a.diff).slice(0, 3).map(b => ({ title: b.title, diff: b.diff, pos: b.pos })),
375
+ top: top10.slice(0, 5).map(b => ({ id: b.id, title: b.title, reads: b.reads, tags: b.tags, done: b.done, words: b.words })),
376
+ }
377
+ if (l.mold === 2) c.read = s; else c.fresh = s
378
+ }
379
+ const catList = Object.values(cats)
380
+ for (const g of [1, 0]) {
381
+ const mine = catList.filter(c => c.gender === g)
382
+ const T = sum(mine.map(c => c.read?.total || 0)) || 1, F = sum(mine.map(c => c.fresh?.total || 0)) || 1
383
+ for (const c of mine) {
384
+ c.read_share = (c.read?.total || 0) / T
385
+ c.fresh_share = (c.fresh?.total || 0) / F
386
+ // 新书机会:新书榜份额 / 阅读榜份额,>1 说明新书在这个分类更容易被看见
387
+ c.chance = c.read_share ? c.fresh_share / c.read_share : 0
388
+ c.trend = c.read?.prev_total ? (c.read.total - c.read.prev_total) / c.read.prev_total : null
389
+ }
390
+ }
391
+ const tags = {}, labels = {}
392
+ for (const g of [1, 0]) for (const mold of [2, 1]) {
393
+ const books = snap.lists.filter(l => l.gender === g && l.mold === mold).flatMap(l => l.books.slice(0, snap.tag_top || 30))
394
+ tags[`${g}_${mold}`] = tagStats(books, catNames)
395
+ const lm = new Map()
396
+ for (const b of snap.lists.filter(l => l.gender === g && l.mold === mold).flatMap(l => l.books.slice(0, 50))) for (const t of new Set(labelsOf(b.abs))) lm.set(t, (lm.get(t) || 0) + 1)
397
+ labels[`${g}_${mold}`] = [...lm.entries()].map(([k, n]) => ({ k, n })).filter(x => x.n >= 2).sort((a, b) => b.n - a.n).slice(0, 40)
398
+ }
399
+ // 标签上升:新书榜份额 - 阅读榜份额
400
+ const rising = {}
401
+ for (const g of [1, 0]) {
402
+ const r = new Map(tags[`${g}_2`].list.map(x => [x.k, x]))
403
+ rising[g] = tags[`${g}_1`].list.filter(x => x.n >= 3).map(x => ({ k: x.k, fresh: x.share, read: r.get(x.k)?.share || 0, d: x.share - (r.get(x.k)?.share || 0) })).sort((a, b) => b.d - a.d).slice(0, 20)
404
+ }
405
+ return {
406
+ date: snap.date, at: snap.at, prev: prev?.date || null, quality: snap.quality,
407
+ cats: catList, tags: Object.fromEntries(Object.entries(tags).map(([k, v]) => [k, { n: v.n, list: v.list.slice(0, 60) }])), labels, rising,
408
+ }
409
+ }
410
+ async function analysisFor(date) {
411
+ const { idx, snap } = await snapshot(date)
412
+ if (!snap) return { empty: true, snapshots: idx.snapshots || [] }
413
+ const k = 'ana:' + snap.date
414
+ if (!CACHE.has(k)) {
415
+ const prevMeta = (idx.snapshots || []).find(s => s.date < snap.date)
416
+ const prev = prevMeta ? (await snapshot(prevMeta.date)).snap : null
417
+ CACHE.set(k, analyze(snap, prev))
418
+ }
419
+ const ai = await getJ(`${P}ai/${snap.date}.json`, null)
420
+ return { ...CACHE.get(k), ai, snapshots: idx.snapshots || [] }
421
+ }
422
+
423
+ /* ---------------- 总纲规划任务 ---------------- */
424
+ async function planIndex() { return await getJ(P + 'plans/index.json', { plans: [] }) || { plans: [] } }
425
+ async function savePlanMeta(plan) {
426
+ const idx = await planIndex()
427
+ const meta = { id: plan.id, title: plan.result?.title || plan.target?.title || '', target: plan.target, status: plan.status, created_at: plan.created_at, updated_at: plan.updated_at, project_id: plan.project_id || null }
428
+ idx.plans = [meta, ...idx.plans.filter(p => p.id !== plan.id)].slice(0, 500)
429
+ await putJ(P + 'plans/index.json', idx)
430
+ }
431
+ async function llm(pack) {
432
+ const base = process.env.LLM_BASE_URL, key = process.env.LLM_API_KEY, model = process.env.LLM_MODEL
433
+ if (!base || !key || !model) return null
434
+ const r = await fetch(base.replace(/\/$/, '') + '/chat/completions', {
435
+ method: 'POST', headers: { 'content-type': 'application/json', authorization: `Bearer ${key}` },
436
+ body: JSON.stringify({ model, messages: [{ role: 'user', content: pack }], temperature: 0.8 }),
437
+ })
438
+ if (!r.ok) throw new Error(`AI 接口返回 ${r.status}`)
439
+ const d = await r.json()
440
+ return d.choices?.[0]?.message?.content || ''
441
+ }
442
+ function parseResult(text) {
443
+ if (text && typeof text === 'object') return text
444
+ const s = String(text || '')
445
+ const m = s.match(/```(?:json)?\s*([\s\S]*?)```/)
446
+ const body = m ? m[1] : s.slice(s.indexOf('{'), s.lastIndexOf('}') + 1)
447
+ try { return JSON.parse(body) } catch { const e = new Error('没能读出总纲:请确认粘贴的是 AI 输出的完整 JSON'); e.status = 400; throw e }
448
+ }
449
+
450
+ module.exports = function buildRank(express) {
451
+ const router = express.Router()
452
+ router.use(express.json({ limit: '4mb' }))
453
+ const wrap = fn => async (req, res) => { try { res.json(await fn(req, res)) } catch (e) { res.status(e.status || 500).json({ error: e.message || String(e) }) } }
454
+ const bad = m => { const e = new Error(m); e.status = 400; return e }
455
+
456
+ router.get('/status', wrap(() => ({ ...JOB, log: JOB.log.slice(-20), llm: Boolean(process.env.LLM_API_KEY && process.env.LLM_BASE_URL && process.env.LLM_MODEL) })))
457
+ router.post('/scrape', wrap(async () => { await scrape(); return { ...JOB } }))
458
+ router.post('/enrich', wrap(async () => { await enrich(); return { ...JOB } }))
459
+ router.get('/analysis', wrap(req => analysisFor(String(req.query.date || ''))))
460
+ router.get('/list', wrap(async req => {
461
+ const { snap } = await snapshot(String(req.query.date || ''))
462
+ if (!snap) return { books: [] }
463
+ const l = snap.lists.find(x => String(x.gender) === String(req.query.gender) && String(x.mold) === String(req.query.mold) && x.cid === String(req.query.cid))
464
+ return l || { books: [] }
465
+ }))
466
+ router.get('/book', wrap(async req => {
467
+ await loadState()
468
+ const id = String(req.query.id || '')
469
+ const { snap } = await snapshot(String(req.query.date || ''))
470
+ const seen = []
471
+ for (const l of snap?.lists || []) { const b = l.books.find(x => x.id === id); if (b) seen.push({ g: GEN[l.gender], mold: MOLD[l.mold], cname: l.cname, pos: b.pos, b }) }
472
+ return { id, detail: BOOKS[id] || null, seen }
473
+ }))
474
+ // AI 解读:由 AI 读完当天数据后写入(也可以把 AI 的回答粘贴进来)
475
+ router.put('/ai/:date', wrap(async req => {
476
+ const date = String(req.params.date)
477
+ if (!/^\d{4}-\d{2}-\d{2}$/.test(date)) throw bad('日期格式不对')
478
+ const body = req.body || {}
479
+ const doc = { date, by: String(body.by || 'AI'), at: now(), summary: String(body.summary || ''), sections: Array.isArray(body.sections) ? body.sections : [], ideas: Array.isArray(body.ideas) ? body.ideas : [] }
480
+ await putJ(`${P}ai/${date}.json`, doc)
481
+ return doc
482
+ }))
483
+ router.get('/plans', wrap(() => planIndex()))
484
+ router.get('/plans/:id', wrap(async req => { const p = await getJ(`${P}plans/${req.params.id}.json`, null); if (!p) { const e = new Error('没有这个规划'); e.status = 404; throw e } return p }))
485
+ router.post('/plans', wrap(async req => {
486
+ const b = req.body || {}
487
+ if (!b.target || !String(b.pack || '').trim()) throw bad('缺少规划目标或任务包')
488
+ const plan = { id: rid('plan'), target: b.target, pack: String(b.pack).slice(0, 200000), status: 'pending', result: null, note: '', created_at: now(), updated_at: now(), date: b.date || '' }
489
+ await putJ(`${P}plans/${plan.id}.json`, plan); await savePlanMeta(plan)
490
+ return plan
491
+ }))
492
+ router.put('/plans/:id/result', wrap(async req => {
493
+ const p = await getJ(`${P}plans/${req.params.id}.json`, null)
494
+ if (!p) throw bad('没有这个规划')
495
+ const result = parseResult(req.body?.result ?? req.body?.text)
496
+ if (!result.title && !result.volumes && !result.chapters) throw bad('内容里没有书名、分卷或章纲,不像总纲')
497
+ Object.assign(p, { result, status: 'done', by: String(req.body?.by || '粘贴'), updated_at: now() })
498
+ await putJ(`${P}plans/${p.id}.json`, p); await savePlanMeta(p)
499
+ return p
500
+ }))
501
+ router.post('/plans/:id/generate', wrap(async req => {
502
+ const p = await getJ(`${P}plans/${req.params.id}.json`, null)
503
+ if (!p) throw bad('没有这个规划')
504
+ const text = await llm(p.pack)
505
+ if (text === null) throw bad('服务器没有配置 AI 接口;请复制任务包交给 AI,或等 AI 代办处理')
506
+ Object.assign(p, { result: parseResult(text), status: 'done', by: process.env.LLM_MODEL, updated_at: now() })
507
+ await putJ(`${P}plans/${p.id}.json`, p); await savePlanMeta(p)
508
+ return p
509
+ }))
510
+ router.delete('/plans/:id', wrap(async req => {
511
+ const idx = await planIndex()
512
+ idx.plans = idx.plans.filter(x => x.id !== req.params.id)
513
+ await putJ(P + 'plans/index.json', idx)
514
+ return { ok: true }
515
+ }))
516
+ router.post('/plans/:id/project', wrap(async req => {
517
+ const projects = require('./projects.js')
518
+ const p = await getJ(`${P}plans/${req.params.id}.json`, null)
519
+ if (!p?.result) throw bad('这个规划还没有总纲结果')
520
+ const r = p.result
521
+ const t = p.target || {}
522
+ const bundle = await projects.createProject({
523
+ title: r.title || t.title || '未命名新书', genre: [t.g, t.cname].filter(Boolean).join('·') || r.genre || '', target_platform: '番茄小说',
524
+ target_words: Number(r.target_words || t.words || 0), pov: r.pov || t.pov || '', style: r.style || '',
525
+ premise: [r.logline, r.blurb].filter(Boolean).join('\n\n').slice(0, 2000), status: 'planning',
526
+ })
527
+ const id = bundle.project.project_id
528
+ const arr = v => (Array.isArray(v) ? v : [])
529
+ const strs = v => arr(v).map(x => (typeof x === 'string' ? x : Object.values(x || {}).filter(Boolean).join(':'))).filter(Boolean)
530
+ await projects.saveBible(id, {
531
+ story_core: r.story_core || r.logline || '', main_plot: r.main_plot || '', ending_direction: r.ending_direction || '', reader_expectation: r.reader_expectation || '',
532
+ characters: arr(r.characters), relationships: arr(r.relationships), timeline: arr(r.timeline), settings: strs(r.settings),
533
+ foreshadowing: arr(r.foreshadowing).map((f, i) => ({ id: f.id || `F${i + 1}`, status: f.status || 'planted', plant: f.plant || '', payoff: f.payoff || '' })),
534
+ open_questions: strs(r.open_questions), style_rules: strs(r.style_rules), safety_rules: strs(r.safety_rules || r.risks), source_material_uids: arr(r.source_material_uids),
535
+ })
536
+ await projects.saveOutline(id, { three_act: arr(r.three_act), volumes: arr(r.volumes), chapters: arr(r.chapters) })
537
+ Object.assign(p, { project_id: id, updated_at: now() })
538
+ await putJ(`${P}plans/${p.id}.json`, p); await savePlanMeta(p)
539
+ return { project_id: id }
540
+ }))
541
+
542
+ // 每天北京时间 8 点后自动抓一次(服务在线时)
543
+ if (process.env.RANK_AUTO !== '0') setInterval(async () => {
544
+ try {
545
+ if (JOB.running || cnHour() < 8) return
546
+ const idx = await getJ(P + 'index.json', { snapshots: [] })
547
+ if (idx?.latest !== cnDate()) return void scrape()
548
+ await loadState()
549
+ const { snap } = await snapshot(idx.latest)
550
+ if (snap && missingOf(snap).length) enrich(200)
551
+ } catch {}
552
+ }, 20 * 60 * 1000).unref?.()
553
+ return router
554
+ }
555
+ module.exports._internal = { scrape, enrich, missingOf, applyBooks, loadState, JOB, analysisFor, snapshot, decode, learn, bookPage, rankList, categories, FONT: () => FONT }
public/assets/index-B9H0vwhc.js ADDED
The diff for this file is too large to render. See raw diff
 
public/assets/{index-CJ2d1DZw.css → index-CGHkSQ1Y.css} RENAMED
The diff for this file is too large to render. See raw diff
 
public/assets/index-CmUi1EQO.js DELETED
The diff for this file is too large to render. See raw diff
 
public/index.html CHANGED
@@ -8,8 +8,8 @@
8
  <title>小说写作台</title>
9
  <link rel="icon" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 64 64'%3E%3Crect width='64' height='64' rx='12' fill='%23b8432f'/%3E%3Ctext x='32' y='44' font-size='34' text-anchor='middle' fill='%23fff' font-family='serif'%3E%E6%96%87%3C/text%3E%3C/svg%3E" />
10
  <script>try{var t=localStorage.getItem('xs_theme');if(t==='night')document.documentElement.dataset.theme='night'}catch(e){}</script>
11
- <script type="module" crossorigin src="/assets/index-CmUi1EQO.js"></script>
12
- <link rel="stylesheet" crossorigin href="/assets/index-CJ2d1DZw.css">
13
  </head>
14
  <body>
15
  <div id="root"></div>
 
8
  <title>小说写作台</title>
9
  <link rel="icon" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 64 64'%3E%3Crect width='64' height='64' rx='12' fill='%23b8432f'/%3E%3Ctext x='32' y='44' font-size='34' text-anchor='middle' fill='%23fff' font-family='serif'%3E%E6%96%87%3C/text%3E%3C/svg%3E" />
10
  <script>try{var t=localStorage.getItem('xs_theme');if(t==='night')document.documentElement.dataset.theme='night'}catch(e){}</script>
11
+ <script type="module" crossorigin src="/assets/index-B9H0vwhc.js"></script>
12
+ <link rel="stylesheet" crossorigin href="/assets/index-CGHkSQ1Y.css">
13
  </head>
14
  <body>
15
  <div id="root"></div>
ui-src/src/App.tsx CHANGED
@@ -1,5 +1,5 @@
1
  import React, { useEffect, useState } from 'react'
2
- import { BookOpen, Library, Radio, Compass, Moon, Sun, Lock, Feather, Layers } from 'lucide-react'
3
  import { authRequired, checkPassword, getPassword, setPassword, setUnauthorizedHandler } from './api'
4
  import { cx, useRoute } from './lib'
5
  import { ConfirmHost, ToastHost, Spinner } from './ui'
@@ -9,6 +9,7 @@ import LibraryRoom from './rooms/Library'
9
  import Sources from './rooms/Sources'
10
  import Guide from './rooms/Guide'
11
  import Motif2Room from './rooms/Motif2'
 
12
 
13
  type Gate = 'checking' | 'locked' | 'open'
14
 
@@ -66,6 +67,7 @@ const ROOMS = [
66
  { id: 'guide', match: ['guide'], label: '手册', icon: Compass },
67
  { id: 'shelf', match: ['', 'shelf', 'book'], label: '书房', icon: BookOpen },
68
  { id: 'library', match: ['library'], label: '素材馆', icon: Library },
 
69
  { id: 'motif2', match: ['motif2'], label: '母题库', icon: Layers },
70
  { id: 'sources', match: ['sources'], label: '采集', icon: Radio },
71
  ]
@@ -82,12 +84,13 @@ function Shell({ onLock }: { onLock: () => void }) {
82
  const head = parts[0] || ''
83
  const room = ROOMS.find(r => r.match.includes(head)) || ROOMS.find(r => r.id === 'shelf')!
84
  useEffect(() => {
85
- const titles: Record<string, string> = { shelf: '书房', library: '素材馆', motif2: '母题库', sources: '素材采集', guide: '写作手册' }
86
  if (room.id !== 'shelf' || head !== 'book') document.title = `${titles[room.id]} · 小说写作台`
87
  }, [room.id, head])
88
 
89
  let content: React.ReactNode
90
  if (head === 'book' && parts[1]) content = <Book key={parts[1]} projectId={parts[1]} sub={parts[2] || ''} />
 
91
  else if (head === 'motif2') content = <Motif2Room tab={parts[1] || 'role'} arg={parts[2] || ''} />
92
  else if (head === 'library') content = <LibraryRoom tab={parts[1] || 'materials'} arg={parts[2] || ''} />
93
  else if (head === 'sources') content = <Sources channel={parts[1] || ''} tab={parts[2] || ''} />
 
1
  import React, { useEffect, useState } from 'react'
2
+ import { BookOpen, Library, Radio, Compass, Moon, Sun, Lock, Feather, Layers, TrendingUp } from 'lucide-react'
3
  import { authRequired, checkPassword, getPassword, setPassword, setUnauthorizedHandler } from './api'
4
  import { cx, useRoute } from './lib'
5
  import { ConfirmHost, ToastHost, Spinner } from './ui'
 
9
  import Sources from './rooms/Sources'
10
  import Guide from './rooms/Guide'
11
  import Motif2Room from './rooms/Motif2'
12
+ import RankRoom from './rooms/Rank'
13
 
14
  type Gate = 'checking' | 'locked' | 'open'
15
 
 
67
  { id: 'guide', match: ['guide'], label: '手册', icon: Compass },
68
  { id: 'shelf', match: ['', 'shelf', 'book'], label: '书房', icon: BookOpen },
69
  { id: 'library', match: ['library'], label: '素材馆', icon: Library },
70
+ { id: 'rank', match: ['rank'], label: '热榜', icon: TrendingUp },
71
  { id: 'motif2', match: ['motif2'], label: '母题库', icon: Layers },
72
  { id: 'sources', match: ['sources'], label: '采集', icon: Radio },
73
  ]
 
84
  const head = parts[0] || ''
85
  const room = ROOMS.find(r => r.match.includes(head)) || ROOMS.find(r => r.id === 'shelf')!
86
  useEffect(() => {
87
+ const titles: Record<string, string> = { shelf: '书房', library: '素材馆', rank: '番茄热榜', motif2: '母题库', sources: '素材采集', guide: '写作手册' }
88
  if (room.id !== 'shelf' || head !== 'book') document.title = `${titles[room.id]} · 小说写作台`
89
  }, [room.id, head])
90
 
91
  let content: React.ReactNode
92
  if (head === 'book' && parts[1]) content = <Book key={parts[1]} projectId={parts[1]} sub={parts[2] || ''} />
93
+ else if (head === 'rank') content = <RankRoom tab={parts[1] || 'analysis'} arg={parts[2] || ''} />
94
  else if (head === 'motif2') content = <Motif2Room tab={parts[1] || 'role'} arg={parts[2] || ''} />
95
  else if (head === 'library') content = <LibraryRoom tab={parts[1] || 'materials'} arg={parts[2] || ''} />
96
  else if (head === 'sources') content = <Sources channel={parts[1] || ''} tab={parts[2] || ''} />
ui-src/src/rooms/Rank.tsx ADDED
@@ -0,0 +1,488 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import React, { useEffect, useMemo, useState } from 'react'
2
+ import { TrendingUp, RefreshCw, Copy, Send, Sparkles, BookPlus, ArrowUp, ArrowDown, Flame, Lightbulb, FileText, Trash2, ClipboardPaste, ChevronRight } from 'lucide-react'
3
+ import { get, post, put, del, qs } from '../api'
4
+ import { copyText, cx, fmtAgo, fmtNum, go, useAsync, useLocal } from '../lib'
5
+ import { Drawer, Empty, ErrorNote, Loading, Segmented, Tabs, Tag, useToast, useConfirm } from '../ui'
6
+ import { ai as AI } from '../handbook'
7
+
8
+ const A = '/fanqie/api/rank'
9
+ const api = {
10
+ status: () => get<any>(`${A}/status`),
11
+ scrape: () => post<any>(`${A}/scrape`, {}),
12
+ analysis: (date = '') => get<any>(`${A}/analysis${qs({ date })}`),
13
+ list: (p: Record<string, any>) => get<any>(`${A}/list${qs(p)}`),
14
+ book: (id: string, date = '') => get<any>(`${A}/book${qs({ id, date })}`),
15
+ plans: () => get<any>(`${A}/plans`),
16
+ plan: (id: string) => get<any>(`${A}/plans/${id}`),
17
+ createPlan: (b: any) => post<any>(`${A}/plans`, b),
18
+ savePlanResult: (id: string, text: string) => put<any>(`${A}/plans/${id}/result`, { text }),
19
+ generate: (id: string) => post<any>(`${A}/plans/${id}/generate`, {}),
20
+ delPlan: (id: string) => del<any>(`${A}/plans/${id}`),
21
+ toProject: (id: string) => post<any>(`${A}/plans/${id}/project`, {}),
22
+ }
23
+ type TabId = 'board' | 'analysis' | 'plan' | 'plans'
24
+ const G: Record<string, string> = { '1': '男频', '0': '女频' }
25
+ const MOLD: Record<string, string> = { '2': '阅读榜', '1': '新书榜' }
26
+ const pct = (x: number | null | undefined, d = 1) => (x == null ? '—' : `${(x * 100).toFixed(d)}%`)
27
+ const wan = (n: number) => (n >= 1e8 ? `${(n / 1e8).toFixed(1)} 亿` : fmtNum(n))
28
+ export type PlanDraft = { gender: string; cid: string; tags: string[]; idea: string; words: string; pov: string; extra: string }
29
+ const EMPTY_DRAFT: PlanDraft = { gender: '1', cid: '', tags: [], idea: '', words: '100', pov: '第三人称', extra: '' }
30
+
31
+ export default function RankRoom({ tab, arg }: { tab: string; arg: string }) {
32
+ const t = (['board', 'analysis', 'plan', 'plans'].includes(tab) ? tab : 'analysis') as TabId
33
+ const ana = useAsync(() => api.analysis(), [])
34
+ const [openBook, setOpenBook] = useState('')
35
+ const date = ana.data?.date
36
+ return (
37
+ <div className="room library rk">
38
+ <header className="room-head">
39
+ <div>
40
+ <div className="eyebrow"><TrendingUp size={14} />番茄热榜</div>
41
+ <h1 className="room-title serif">看榜单、读趋势,再定新书总纲</h1>
42
+ <p className="muted small-note">
43
+ 每天自动抓取番茄官网的分类榜(男频 19 类、女频 18 类,各含阅读榜和新书榜,每榜前 100 本),附带书籍的官方标签。数字由系统统计,「AI 解读」和「总纲」由 AI 阅读数据后撰写。
44
+ </p>
45
+ </div>
46
+ <ScrapeBox date={date} onDone={() => ana.reload()} />
47
+ </header>
48
+ <Tabs<TabId> value={t} onChange={v => go(`rank/${v}`)} className="room-tabs" items={[
49
+ { id: 'analysis', label: '趋势分析' }, { id: 'board', label: '榜单' }, { id: 'plan', label: '规划总纲' }, { id: 'plans', label: '我的规划' },
50
+ ]} />
51
+ <div className="room-body">
52
+ {ana.loading && !ana.data && <Loading label="正在读取榜单数据…" />}
53
+ {ana.error && <ErrorNote error={ana.error} onRetry={ana.reload} />}
54
+ {ana.data?.empty && t !== 'plans' && <Empty icon={<TrendingUp size={22} />} title="还没有榜单数据">点右上角「立即抓取」,大约需要 5–10 分钟。</Empty>}
55
+ {ana.data && !ana.data.empty && t === 'analysis' && <AnalysisTab a={ana.data} onBook={setOpenBook} />}
56
+ {ana.data && !ana.data.empty && t === 'board' && <BoardTab a={ana.data} arg={arg} onBook={setOpenBook} />}
57
+ {ana.data && !ana.data.empty && t === 'plan' && <PlanTab a={ana.data} />}
58
+ {t === 'plans' && <PlansTab arg={arg} />}
59
+ </div>
60
+ <BookDrawer id={openBook} date={date} onClose={() => setOpenBook('')} />
61
+ </div>
62
+ )
63
+ }
64
+
65
+ /* ---------------- 抓取状态 ---------------- */
66
+ function ScrapeBox({ date, onDone }: { date?: string; onDone: () => void }) {
67
+ const [st, setSt] = useState<any>(null)
68
+ const toast = useToast()
69
+ useEffect(() => {
70
+ let alive = true, timer: any
71
+ const tick = async () => {
72
+ try {
73
+ const s = await api.status(); if (!alive) return
74
+ setSt((prev: any) => { if (prev?.running && !s.running) { s.error ? toast('抓取失败:' + s.error, 'err') : (toast('榜单已更新', 'ok'), onDone()) } return s })
75
+ timer = setTimeout(tick, s.running ? 3000 : 30000)
76
+ } catch { timer = setTimeout(tick, 30000) }
77
+ }
78
+ tick()
79
+ return () => { alive = false; clearTimeout(timer) }
80
+ // eslint-disable-next-line react-hooks/exhaustive-deps
81
+ }, [])
82
+ const start = async () => { try { setSt(await api.scrape()); setTimeout(async () => setSt(await api.status()), 1500) } catch (e: any) { toast(e.message, 'err') } }
83
+ return (
84
+ <div className="rk-scrape">
85
+ <div className="small-note muted">{date ? <>数据日期 <b>{date}</b></> : '暂无数据'}</div>
86
+ {st?.running ? (
87
+ <div className="rk-prog"><div className="small-note">{st.step} {st.total ? `${st.done}/${st.total}` : ''}</div><div className="bar"><i style={{ width: `${st.total ? (st.done / st.total) * 100 : 5}%` }} /></div></div>
88
+ ) : <button className="btn small ghost" onClick={start}><RefreshCw size={13} />立即抓取</button>}
89
+ </div>
90
+ )
91
+ }
92
+
93
+ /* ---------------- 趋势分析 ---------------- */
94
+ function AnalysisTab({ a, onBook }: { a: any; onBook: (id: string) => void }) {
95
+ const [g, setG] = useLocal<string>('rk-g', '1')
96
+ const [sort, setSort] = useState<'read' | 'chance' | 'fresh'>('read')
97
+ const cats = useMemo(() => (a.cats || []).filter((c: any) => String(c.gender) === g).sort((x: any, y: any) => sort === 'read' ? y.read_share - x.read_share : sort === 'fresh' ? y.fresh_share - x.fresh_share : y.chance - x.chance), [a, g, sort])
98
+ const maxShare = Math.max(...cats.map((c: any) => Math.max(c.read_share, c.fresh_share)), 0.01)
99
+ const tagsRead = a.tags?.[`${g}_2`]?.list || [], tagsFresh = a.tags?.[`${g}_1`]?.list || []
100
+ const rising = a.rising?.[g] || []
101
+ const labels = a.labels?.[`${g}_1`] || []
102
+ const [, setDraft] = useLocal<PlanDraft>('rk-draft', EMPTY_DRAFT)
103
+ const planWith = (cid: string, tags: string[] = []) => { setDraft({ ...EMPTY_DRAFT, gender: g, cid, tags }); go('rank/plan') }
104
+ return (
105
+ <div className="rk-ana">
106
+ <AiNote ai={a.ai} date={a.date} />
107
+ <div className="row between rk-bar">
108
+ <Segmented value={g} onChange={setG} items={[{ id: '1', label: '男频' }, { id: '0', label: '女频' }]} />
109
+ <span className="muted small-note">对比上次:{a.prev || '暂无(明天起可看涨跌)'}</span>
110
+ </div>
111
+
112
+ <section className="sheet">
113
+ <h2 className="sheet-title serif"><Flame size={16} />题材热度</h2>
114
+ <p className="sheet-note">「阅读份额」= 该分类阅读榜前 100 本的在读人数占全部分类的比例;「新书份额」同理按新书榜算。「新书机会」= 新书份额 ÷ 阅读份额,大于 1 说明新书在这里更容易被看见。</p>
115
+ <div className="row gap-s rk-sort">排序:
116
+ {([['read', '阅读份额'], ['fresh', '新书份额'], ['chance', '新书机会']] as const).map(([k, l]) => <button key={k} className={cx('chip', sort === k && 'on')} onClick={() => setSort(k)}>{l}</button>)}
117
+ </div>
118
+ <div className="rk-table-wrap"><table className="rk-table">
119
+ <thead><tr><th>分类</th><th>阅读份额</th><th>新书份额</th><th>新书机会</th><th>阅读榜头部</th><th>前20完结</th><th>字数中位</th><th></th></tr></thead>
120
+ <tbody>{cats.map((c: any) => (
121
+ <tr key={c.cid}>
122
+ <td><button className="link-btn" onClick={() => go(`rank/board/${c.gender}_${c.cid}`)}>{c.name}</button>
123
+ {c.trend != null && <span className={cx('rk-trend', c.trend >= 0 ? 'up' : 'down')}>{c.trend >= 0 ? <ArrowUp size={11} /> : <ArrowDown size={11} />}{pct(Math.abs(c.trend))}</span>}</td>
124
+ <td className="rk-sharecell"><div className="rk-share"><i style={{ width: `${(c.read_share / maxShare) * 100}%` }} /></div>{pct(c.read_share)}</td>
125
+ <td className="rk-sharecell"><div className="rk-share fresh"><i style={{ width: `${(c.fresh_share / maxShare) * 100}%` }} /></div>{pct(c.fresh_share)}</td>
126
+ <td><b className={cx(c.chance >= 1.3 && 'ok', c.chance < 0.7 && 'warn')}>{c.chance ? c.chance.toFixed(2) : '—'}</b></td>
127
+ <td className="rk-top">{c.read?.top?.[0] ? <button className="link-btn" onClick={() => onBook(c.read.top[0].id)}>{c.read.top[0].title}</button> : '—'}<span className="muted"> {wan(c.read?.head || 0)}</span></td>
128
+ <td>{pct(c.read?.done_share, 0)}</td>
129
+ <td>{c.read?.words_med ? `${Math.round(c.read.words_med / 10000)} 万` : '—'}</td>
130
+ <td><button className="btn small ghost" onClick={() => planWith(c.cid)}>规划<ChevronRight size={12} /></button></td>
131
+ </tr>))}</tbody>
132
+ </table></div>
133
+ </section>
134
+
135
+ <div className="rk-grid2">
136
+ <section className="sheet">
137
+ <h2 className="sheet-title serif">阅读榜热门标签</h2>
138
+ <p className="sheet-note">各分类阅读榜前 {30} 本的官方标签,按在读人数加权。</p>
139
+ <TagBars list={tagsRead.slice(0, 24)} />
140
+ </section>
141
+ <section className="sheet">
142
+ <h2 className="sheet-title serif"><TrendingUp size={16} />新书正在涨的标签</h2>
143
+ <p className="sheet-note">新书榜里出现得比阅读榜更多的标签——往往是下一波的苗头。</p>
144
+ <div className="rk-rise">{rising.map((r: any) => (
145
+ <div key={r.k} className="rk-rise-row"><span>{r.k}</span><span className="muted">{pct(r.read, 0)} → <b>{pct(r.fresh, 0)}</b></span><span className="ok">+{(r.d * 100).toFixed(1)}</span></div>))}
146
+ </div>
147
+ {!rising.length && <div className="muted small-note">数据不足</div>}
148
+ </section>
149
+ </div>
150
+ <div className="rk-grid2">
151
+ <section className="sheet">
152
+ <h2 className="sheet-title serif">新书榜热门标签</h2>
153
+ <TagBars list={tagsFresh.slice(0, 24)} />
154
+ </section>
155
+ <section className="sheet">
156
+ <h2 className="sheet-title serif"><Lightbulb size={16} />新书简介里的卖点词</h2>
157
+ <p className="sheet-note">作者写在简介【】里的自我标签,反映新书在主打什么。</p>
158
+ <div className="chips-row">{labels.map((l: any) => <span key={l.k} className="chip">{l.k}<em>{l.n}</em></span>)}</div>
159
+ {!labels.length && <div className="muted small-note">数据不足</div>}
160
+ </section>
161
+ </div>
162
+ <section className="sheet">
163
+ <h2 className="sheet-title serif">各分类新书榜前列</h2>
164
+ <div className="rk-fresh-grid">{cats.slice(0, 40).map((c: any) => (
165
+ <div key={c.cid} className="rk-fresh">
166
+ <div className="row between"><b>{c.name}</b><button className="link-btn small-note" onClick={() => go(`rank/board/${c.gender}_${c.cid}_1`)}>全部</button></div>
167
+ {(c.fresh?.top || []).slice(0, 3).map((b: any, i: number) => (
168
+ <div key={b.id} className="rk-fresh-b" onClick={() => onBook(b.id)}><span className="rk-no">{i + 1}</span><span className="rk-ft">{b.title}</span><span className="muted">{wan(b.reads)}</span></div>))}
169
+ </div>))}
170
+ </div>
171
+ </section>
172
+ </div>
173
+ )
174
+ }
175
+ function TagBars({ list }: { list: any[] }) {
176
+ const max = Math.max(...list.map(x => x.heat), 0.01)
177
+ if (!list.length) return <div className="muted small-note">数据不足</div>
178
+ return <div className="bars">{list.map(x => (
179
+ <div key={x.k} className="bar-row rk-tagrow"><span className="bar-label">{x.k}</span><div className="bar"><i style={{ width: `${(x.heat / max) * 100}%` }} /></div><span className="bar-n">{pct(x.heat, 0)}</span><span className="bar-sub muted">{x.n} 本</span></div>))}</div>
180
+ }
181
+ function AiNote({ ai, date }: { ai: any; date: string }) {
182
+ if (!ai) return (
183
+ <div className="rk-ai empty"><Sparkles size={15} /><div><b>AI 解读</b><div className="muted small-note">{date} 的数据还没有 AI 解读。AI 读完榜单后会在这里写出判断和选题建议。</div></div></div>
184
+ )
185
+ return (
186
+ <section className="rk-ai">
187
+ <div className="row between"><div className="eyebrow"><Sparkles size={14} />AI 解读 · {ai.date}</div><span className="muted small-note">{ai.by} · {fmtAgo(ai.at)}</span></div>
188
+ {ai.summary && <p className="rk-ai-sum serif">{ai.summary}</p>}
189
+ <div className="rk-ai-secs">{(ai.sections || []).map((s: any, i: number) => (
190
+ <div key={i} className="rk-ai-sec"><h4>{s.title}</h4>{(s.points || []).map((p: string, j: number) => <p key={j}>{p}</p>)}</div>))}
191
+ </div>
192
+ {ai.ideas?.length > 0 && <div className="rk-ideas"><h4>可以写的方向</h4>
193
+ {ai.ideas.map((x: any, i: number) => (
194
+ <div key={i} className="rk-idea"><div><b>{x.title}</b> <span className="muted small-note">{x.g}·{x.cname}</span>{(x.tags || []).map((t: string) => <Tag key={t}>{t}</Tag>)}</div><div className="small-note">{x.pitch}</div>{x.why && <div className="muted small-note">依据:{x.why}</div>}</div>))}
195
+ </div>}
196
+ </section>
197
+ )
198
+ }
199
+
200
+ /* ---------------- 榜单 ---------------- */
201
+ function BoardTab({ a, arg, onBook }: { a: any; arg: string; onBook: (id: string) => void }) {
202
+ const [ag, acid, amold] = (arg || '').split('_')
203
+ const [g, setG] = useState(ag || '1')
204
+ const cats = useMemo(() => (a.cats || []).filter((c: any) => String(c.gender) === g), [a, g])
205
+ const [cid, setCid] = useState(acid || '')
206
+ const [mold, setMold] = useState(amold || '2')
207
+ useEffect(() => { if (ag) { setG(ag); setCid(acid || ''); setMold(amold || '2') } }, [arg]) // eslint-disable-line
208
+ const cur = cats.find((c: any) => c.cid === cid) ? cid : cats[0]?.cid || ''
209
+ const list = useAsync(() => (cur ? api.list({ gender: g, cid: cur, mold }) : Promise.resolve({ books: [] })), [g, cur, mold])
210
+ const [onlyTag, setOnlyTag] = useState('')
211
+ const books = (list.data?.books || []).filter((b: any) => !onlyTag || b.tags?.includes(onlyTag))
212
+ const tagCount = useMemo(() => { const m = new Map<string, number>(); for (const b of list.data?.books || []) for (const t of b.tags || []) if (t !== list.data?.cname && t !== b.main && t !== G[g]) m.set(t, (m.get(t) || 0) + 1); return [...m.entries()].sort((x, y) => y[1] - x[1]).slice(0, 24) }, [list.data, g])
213
+ return (
214
+ <div className="rk-board">
215
+ <div className="row gap rk-bar">
216
+ <Segmented value={g} onChange={v => { setG(v); setCid(''); setOnlyTag('') }} items={[{ id: '1', label: '男频' }, { id: '0', label: '女频' }]} />
217
+ <Segmented value={mold} onChange={v => { setMold(v); setOnlyTag('') }} items={[{ id: '2', label: '阅读榜' }, { id: '1', label: '新书榜' }]} />
218
+ </div>
219
+ <div className="chips-row">{cats.map((c: any) => <button key={c.cid} className={cx('chip', c.cid === cur && 'on')} onClick={() => { setCid(c.cid); setOnlyTag('') }}>{c.name}</button>)}</div>
220
+ {tagCount.length > 0 && <div className="chips-row tight rk-tagf"><span className="muted small-note">标签筛选(前 30 本有标签):</span>{tagCount.map(([t, n]) => <button key={t} className={cx('chip', onlyTag === t && 'on')} onClick={() => setOnlyTag(onlyTag === t ? '' : t)}>{t}<em>{n}</em></button>)}</div>}
221
+ {list.loading && <Loading />}
222
+ {list.error && <ErrorNote error={list.error} onRetry={list.reload} />}
223
+ {list.data?.err && <ErrorNote error={`这个榜单抓取失败:${list.data.err}`} />}
224
+ <div className="rk-books">{books.map((b: any) => (
225
+ <div key={b.id} className="rk-book" onClick={() => onBook(b.id)}>
226
+ <span className={cx('rk-pos', b.pos <= 3 && 'top')}>{b.pos}</span>
227
+ <div className="rk-book-main">
228
+ <div className="rk-book-t"><b>{b.title}</b><span className="muted small-note"> {b.author}</span>
229
+ {b.diff > 0 && <span className="rk-trend up"><ArrowUp size={11} />{b.diff}</span>}{b.diff < 0 && <span className="rk-trend down"><ArrowDown size={11} />{-b.diff}</span>}</div>
230
+ <div className="rk-abs">{b.abs}</div>
231
+ <div className="m2-tags">{(b.tags || []).filter((t: string) => t !== G[g]).map((t: string) => <Tag key={t}>{t}</Tag>)}</div>
232
+ </div>
233
+ <div className="rk-book-num"><b>{wan(b.reads)}</b><span className="muted">在读</span><span className="muted">{Math.round(b.words / 10000)} 万字 · {b.done ? '完结' : '连载'}</span></div>
234
+ </div>))}
235
+ </div>
236
+ </div>
237
+ )
238
+ }
239
+ function BookDrawer({ id, date, onClose }: { id: string; date?: string; onClose: () => void }) {
240
+ const d = useAsync(() => (id ? api.book(id, date) : Promise.resolve(null)), [id])
241
+ const b = d.data?.seen?.[0]?.b
242
+ return (
243
+ <Drawer open={!!id} onClose={onClose} title={b?.title || '书籍详情'} width={560}>
244
+ {d.loading && <Loading />}
245
+ {b && <div className="rk-bd">
246
+ <div className="muted small-note">{b.author} · {Math.round(b.words / 10000)} 万字 · {b.done ? '已完结' : '连载中'} · 在读 {wan(b.reads)}</div>
247
+ <div className="m2-tags">{(d.data.detail?.cats || []).map((c: any) => <Tag key={c.n} tone={c.d === 1 ? 'accent' : undefined}>{c.n}</Tag>)}</div>
248
+ <div className="rk-seen">{d.data.seen.map((s: any, i: number) => <span key={i} className="chip">{s.g}·{s.cname}·{s.mold} 第 {s.pos} 名</span>)}</div>
249
+ <p className="rk-bd-abs">{d.data.detail?.a || b.abs}</p>
250
+ {b.last && <div className="muted small-note">最新章节:{b.last}</div>}
251
+ <a className="btn small ghost" href={`https://fanqienovel.com/page/${id}`} target="_blank" rel="noreferrer">在番茄打开</a>
252
+ </div>}
253
+ </Drawer>
254
+ )
255
+ }
256
+
257
+ /* ---------------- 规划总纲 ---------------- */
258
+ const OUTPUT_SPEC = `只输出一个 JSON 对象(放在 \`\`\`json 代码块里),字段如下:
259
+ {
260
+ "title": "书名(番茄风格,8–15 字,有钩子)",
261
+ "alt_titles": ["备选书名", "..."],
262
+ "genre": "番茄分类",
263
+ "tags": ["3–6 个番茄官方标签"],
264
+ "logline": "一句话卖点(主角是谁 + 遇到什么 + 爽点/虐点是什么)",
265
+ "blurb": "番茄简介(150–300 字,开头可用【】标卖点)",
266
+ "why": ["选题依据:引用上面榜单数据里的具体数字或书名,说明为什么这个方向现在有机会"],
267
+ "differentiation": ["和榜上同类书相比的差异点"],
268
+ "target_words": 1000000,
269
+ "pov": "人称",
270
+ "story_core": "故事内核(这本书真正在讲什么)",
271
+ "main_plot": "主线(300 字内)",
272
+ "ending_direction": "结局方向",
273
+ "reader_expectation": "读者追更的期待(每卷持续给什么爽感/情绪)",
274
+ "characters": [{"name": "", "role": "主角/女主/反派/配角", "goal": "", "fear": "", "secret": ""}],
275
+ "relationships": [{"from": "", "to": "", "relation": "", "change": "关系如何变化"}],
276
+ "settings": ["世界观/金手指/力量体系/规则,每条一句"],
277
+ "foreshadowing": [{"id": "F1", "plant": "在哪埋", "payoff": "在哪收"}],
278
+ "style_rules": ["文风要求"],
279
+ "safety_rules": ["本书需要特别注意的平台红线"],
280
+ "three_act": [{"act": "第一幕", "goal": "", "turning_point": "", "ending": ""}],
281
+ "volumes": [{"volume": 1, "title": "", "goal": "", "conflict": "", "ending": "卷末高潮/钩子"}],
282
+ "chapters": [{"number": 1, "title": "", "goal": "本章发生什么", "hook": "章末钩子"}],
283
+ "risks": ["这个选题的风险和应对"]
284
+ }
285
+ 要求:volumes 覆盖全书(按目标字数分 4–8 卷);chapters 写前 30 章,前 3 章必须完成「主角处境 + 金手指/核心冲突亮相 + 第一个爽点或强钩子」;全部原创,不得照搬榜上书的人物、情节和书名。`
286
+
287
+ function PlanTab({ a }: { a: any }) {
288
+ const toast = useToast()
289
+ const [draft, setDraft] = useLocal<PlanDraft>('rk-draft', EMPTY_DRAFT)
290
+ const set = (p: Partial<PlanDraft>) => setDraft({ ...draft, ...p })
291
+ const cats = (a.cats || []).filter((c: any) => String(c.gender) === draft.gender)
292
+ const cat = cats.find((c: any) => c.cid === draft.cid)
293
+ const lists = useAsync(async () => {
294
+ if (!cat) return null
295
+ const [r, f] = await Promise.all([api.list({ gender: draft.gender, cid: cat.cid, mold: 2 }), api.list({ gender: draft.gender, cid: cat.cid, mold: 1 })])
296
+ return { r, f }
297
+ }, [draft.gender, cat?.cid])
298
+ const catTags = useMemo(() => {
299
+ const m = new Map<string, { n: number; f: number }>()
300
+ const skip = new Set([cat?.name, G[draft.gender]])
301
+ for (const [k, l] of [['n', lists.data?.r], ['f', lists.data?.f]] as const) for (const b of l?.books || []) for (const t of b.tags || []) { if (skip.has(t) || t === b.main) continue; const x = m.get(t) || { n: 0, f: 0 }; x[k]++; m.set(t, x) }
302
+ return [...m.entries()].map(([k, v]) => ({ k, ...v })).sort((x, y) => y.n + y.f - x.n - x.f).slice(0, 30)
303
+ }, [lists.data, cat, draft.gender])
304
+ const pack = useMemo(() => (cat && lists.data ? buildPack(a, cat, lists.data, catTags, draft) : ''), [a, cat, lists.data, catTags, draft])
305
+ const [busy, setBusy] = useState(false)
306
+ const submit = async () => {
307
+ setBusy(true)
308
+ try {
309
+ const p = await api.createPlan({ target: { gender: draft.gender, g: G[draft.gender], cid: cat.cid, cname: cat.name, tags: draft.tags, idea: draft.idea, words: Number(draft.words) * 10000, pov: draft.pov }, pack, date: a.date })
310
+ toast('已提交:AI 处理后会出现在「我的规划」里', 'ok'); go(`rank/plans/${p.id}`)
311
+ } catch (e: any) { toast(e.message, 'err') } finally { setBusy(false) }
312
+ }
313
+ return (
314
+ <div className="rk-plan">
315
+ <section className="sheet">
316
+ <h2 className="sheet-title serif">1. 选题材</h2>
317
+ <div className="row gap"><Segmented value={draft.gender} onChange={v => set({ gender: v, cid: '', tags: [] })} items={[{ id: '1', label: '男频' }, { id: '0', label: '女频' }]} /></div>
318
+ <div className="chips-row">{cats.slice().sort((x: any, y: any) => y.read_share - x.read_share).map((c: any) => (
319
+ <button key={c.cid} className={cx('chip', c.cid === draft.cid && 'on')} onClick={() => set({ cid: c.cid, tags: [] })}>{c.name}<em>{pct(c.read_share, 0)} · 机会 {c.chance?.toFixed(1)}</em></button>))}
320
+ </div>
321
+ {cat && <div className="rk-catcard small-note">
322
+ 阅读份额 <b>{pct(cat.read_share)}</b> · 新书份额 <b>{pct(cat.fresh_share)}</b> · 新书机会 <b>{cat.chance?.toFixed(2)}</b> · 阅读榜前 20 完结占比 {pct(cat.read?.done_share, 0)} · 字数中位 {Math.round((cat.read?.words_med || 0) / 10000)} 万
323
+ </div>}
324
+ {cat && <>
325
+ <h2 className="sheet-title serif rk-mt">2. 选标签(最多 5 个,可不选)</h2>
326
+ {lists.loading && <Loading />}
327
+ <div className="chips-row">{catTags.map(t => (
328
+ <button key={t.k} className={cx('chip', draft.tags.includes(t.k) && 'on')} onClick={() => set({ tags: draft.tags.includes(t.k) ? draft.tags.filter(x => x !== t.k) : draft.tags.length >= 5 ? draft.tags : [...draft.tags, t.k] })}>{t.k}<em>阅{t.n}/新{t.f}</em></button>))}
329
+ </div>
330
+ <h2 className="sheet-title serif rk-mt">3. 你的想法(可选)</h2>
331
+ <textarea className="textarea serif-input" rows={3} value={draft.idea} onChange={e => set({ idea: e.target.value })} placeholder="一句话设定、想写的人设或桥段,都可以;留空就让 AI 根据数据自己选方向" />
332
+ <div className="m2-selects">
333
+ <label className="m2-sel"><span>目标字数(万)</span><select className="input mini" value={draft.words} onChange={e => set({ words: e.target.value })}>{['30', '60', '100', '150', '200', '300'].map(x => <option key={x}>{x}</option>)}</select></label>
334
+ <label className="m2-sel"><span>人称</span><select className="input mini" value={draft.pov} onChange={e => set({ pov: e.target.value })}><option>第三人称</option><option>第一人称</option></select></label>
335
+ </div>
336
+ <textarea className="textarea" rows={2} value={draft.extra} onChange={e => set({ extra: e.target.value })} placeholder="其他要求(可选),例如:不要系统流、主角要有家人羁绊、节奏要快" />
337
+ </>}
338
+ </section>
339
+ {!cat && <Empty icon={<FileText size={22} />} title="先选一个题材">也可以在「趋势分析」的题材表里点「规划」直接跳过来。</Empty>}
340
+ {cat && pack && <section className="sheet">
341
+ <h2 className="sheet-title serif">4. 交给 AI 规划</h2>
342
+ <p className="sheet-note">任务包里已附上这个题材的榜单数据(头部书、标签、新书动向)、平台写作规范和输出格式。可以提交给 AI 代办,或复制给你常用的 AI,再把结果粘贴回「我的规划」。</p>
343
+ <div className="row gap">
344
+ <button className="btn primary" disabled={busy} onClick={submit}><Send size={14} />{busy ? '提交中…' : '提交给 AI 规划'}</button>
345
+ <button className="btn ghost" onClick={async () => { await copyText(pack); toast('任务包已复制', 'ok') }}><Copy size={14} />复制任务包</button>
346
+ </div>
347
+ <details className="rk-pack"><summary>查看任务包({pack.length} 字)</summary><pre className="pre">{pack}</pre></details>
348
+ </section>}
349
+ </div>
350
+ )
351
+ }
352
+ function buildPack(a: any, cat: any, lists: any, catTags: any[], d: PlanDraft) {
353
+ const g = G[d.gender]
354
+ const out: string[] = []
355
+ out.push('你是熟悉番茄小说平台、擅长策划爆款网文的资深主编。请根据下面的番茄热榜数据,为一本新书规划总纲。')
356
+ out.push(`\n【目标】${g} · ${cat.name}${d.tags.length ? ` · 标签:${d.tags.join('、')}` : ''} · 目标 ${d.words} 万字 · ${d.pov}`)
357
+ if (d.idea.trim()) out.push(`作者想法:${d.idea.trim()}`)
358
+ if (d.extra.trim()) out.push(`其他要求:${d.extra.trim()}`)
359
+ out.push(`\n【题材数据(番茄官网分类榜,${a.date})】`)
360
+ out.push(`- ${cat.name}占${g}阅读榜在读人数的 ${pct(cat.read_share)},占新书榜的 ${pct(cat.fresh_share)},新书机会指数 ${cat.chance?.toFixed(2)}(>1 表示新书更容易冒头)`)
361
+ out.push(`- 阅读榜前 20:完结占 ${pct(cat.read?.done_share, 0)},字数中位 ${Math.round((cat.read?.words_med || 0) / 10000)} 万;新书榜前 20 字数中位 ${Math.round((cat.fresh?.words_med || 0) / 10000)} 万`)
362
+ if (catTags.length) out.push(`- 该分类常见标签(阅读榜/新书榜出现次数):${catTags.slice(0, 20).map(t => `${t.k}(${t.n}/${t.f})`).join('、')}`)
363
+ const rising = (a.rising?.[d.gender] || []).slice(0, 10)
364
+ if (rising.length) out.push(`- ${g}整体在新书榜上升的标签:${rising.map((r: any) => `${r.k}(${pct(r.read, 0)}→${pct(r.fresh, 0)})`).join('、')}`)
365
+ const book = (b: any) => `${b.pos}.《${b.title}》${wan(b.reads)}在读·${Math.round(b.words / 10000)}万字·${b.done ? '完结' : '连载'}${b.tags?.length ? `|${b.tags.filter((t: string) => t !== g).join('/')}` : ''}\n ${String(b.abs || '').replace(/\s+/g, ' ').slice(0, 110)}`
366
+ out.push(`\n【阅读榜前 12(老书,代表读者长期买账的东西)】`)
367
+ for (const b of (lists.r?.books || []).slice(0, 12)) out.push(book(b))
368
+ out.push(`\n【新书榜前 15(近期新书,代表现在的竞争和风向)】`)
369
+ for (const b of (lists.f?.books || []).slice(0, 15)) out.push(book(b))
370
+ if (a.ai?.summary) out.push(`\n【AI 对当日榜单的整体判断】\n${a.ai.summary}`)
371
+ out.push('\n【平台写作规范(必须遵守)】')
372
+ AI.preamble.slice(0, 6).forEach(p => out.push(`- ${p}`))
373
+ AI.rules.filter(r => r.hard).slice(0, 18).forEach(r => out.push(`- ${r.rule}`))
374
+ out.push('\n【规划步骤】')
375
+ out.push('1. 先读数据:找出这个题材里读者反复买账的爽点/情绪、新书在卷什么、哪里还有空位。')
376
+ out.push('2. 定方向:在热门元素上做一个清晰的差异化(新身份、新金手指、新关系或新场景),不要做榜上已有书的翻版。')
377
+ out.push('3. 再写总纲:人物、设定、分卷、前 30 章章纲,黄金三章要立住钩子。')
378
+ out.push('\n【输出格式】\n' + OUTPUT_SPEC)
379
+ return out.join('\n')
380
+ }
381
+
382
+ /* ---------------- 我的规划 ---------------- */
383
+ function PlansTab({ arg }: { arg: string }) {
384
+ const list = useAsync(() => api.plans(), [])
385
+ const plans = list.data?.plans || []
386
+ const toast = useToast(); const confirm = useConfirm()
387
+ const sel = arg || plans[0]?.id || ''
388
+ return (
389
+ <div className="rk-plans">
390
+ <aside className="rk-plan-list">
391
+ {list.loading && <Loading />}
392
+ {!list.loading && !plans.length && <div className="muted small-note">还没有规划。去「规划总纲」提交一个。</div>}
393
+ {plans.map((p: any) => (
394
+ <button key={p.id} className={cx('rk-plan-item', p.id === sel && 'on')} onClick={() => go(`rank/plans/${p.id}`)}>
395
+ <b>{p.title || `${p.target?.cname || ''}新书`}</b>
396
+ <span className="muted small-note">{p.target?.g}·{p.target?.cname}{p.target?.tags?.length ? '·' + p.target.tags.join('/') : ''}</span>
397
+ <span className="small-note">{p.status === 'done' ? (p.project_id ? '已建作品' : '总纲已完成') : '等待 AI 规划'} · {fmtAgo(p.updated_at)}</span>
398
+ </button>))}
399
+ </aside>
400
+ <div className="rk-plan-main">
401
+ {sel ? <PlanView key={sel} id={sel} onChange={list.reload} onDelete={async () => {
402
+ if (!(await confirm({ title: '删除这个规划?', body: '只从列表移除,已建的作品不受影响。', danger: true, ok: '删除' }))) return
403
+ await api.delPlan(sel); toast('已删除', 'ok'); list.reload(); go('rank/plans')
404
+ }} /> : <Empty icon={<FileText size={22} />} title="选择左侧的规划查看" />}
405
+ </div>
406
+ </div>
407
+ )
408
+ }
409
+ function PlanView({ id, onChange, onDelete }: { id: string; onChange: () => void; onDelete: () => void }) {
410
+ const p = useAsync(() => api.plan(id), [id])
411
+ const st = useAsync(() => api.status(), [])
412
+ const toast = useToast()
413
+ const [paste, setPaste] = useState('')
414
+ const [busy, setBusy] = useState('')
415
+ if (p.loading) return <Loading />
416
+ if (p.error) return <ErrorNote error={p.error} onRetry={p.reload} />
417
+ const plan = p.data, r = plan.result
418
+ const savePaste = async () => { setBusy('paste'); try { p.setData(await api.savePlanResult(id, paste)); setPaste(''); toast('总纲已保存', 'ok'); onChange() } catch (e: any) { toast(e.message, 'err') } finally { setBusy('') } }
419
+ const gen = async () => { setBusy('gen'); try { p.setData(await api.generate(id)); toast('AI 已生成总纲', 'ok'); onChange() } catch (e: any) { toast(e.message, 'err') } finally { setBusy('') } }
420
+ const mk = async () => { setBusy('proj'); try { const x = await api.toProject(id); toast('已创建作品,作品圣经和大纲已填好', 'ok'); onChange(); go(`book/${x.project_id}/about`) } catch (e: any) { toast(e.message, 'err') } finally { setBusy('') } }
421
+ const T = plan.target || {}
422
+ return (
423
+ <div className="rk-pv">
424
+ <div className="row between">
425
+ <div className="muted small-note">{T.g}·{T.cname}{T.tags?.length ? ' · ' + T.tags.join('/') : ''} · {Math.round((T.words || 0) / 10000)} 万字 · 数据日期 {plan.date || '—'}</div>
426
+ <div className="row gap-s">
427
+ <button className="btn small ghost" onClick={async () => { await copyText(plan.pack); toast('任务包已复制', 'ok') }}><Copy size={13} />复制任务包</button>
428
+ <button className="btn small ghost" onClick={onDelete}><Trash2 size={13} /></button>
429
+ </div>
430
+ </div>
431
+ {!r && <section className="sheet">
432
+ <h2 className="sheet-title serif">等待 AI 规划</h2>
433
+ <p className="sheet-note">这个规划已进入 AI 代办队列。也可以复制任务包交给别的 AI,把它输出的 JSON 粘贴到下面。</p>
434
+ {st.data?.llm && <button className="btn primary" disabled={!!busy} onClick={gen}><Sparkles size={14} />{busy === 'gen' ? '生成中(约 1–2 分钟)…' : '让服务器上的 AI 直接生成'}</button>}
435
+ <textarea className="textarea rk-mt" rows={6} value={paste} onChange={e => setPaste(e.target.value)} placeholder="把 AI 输出的总纲 JSON 粘贴在这里" />
436
+ <div className="row end"><button className="btn" disabled={!paste.trim() || !!busy} onClick={savePaste}><ClipboardPaste size={14} />保存总纲</button></div>
437
+ </section>}
438
+ {r && <PlanResult r={r} />}
439
+ {r && <div className="row gap rk-mt">
440
+ {plan.project_id
441
+ ? <button className="btn primary" onClick={() => go(`book/${plan.project_id}/about`)}><BookPlus size={14} />打开作品</button>
442
+ : <button className="btn primary" disabled={!!busy} onClick={mk}><BookPlus size={14} />{busy === 'proj' ? '创建中…' : '用这份总纲新建作品'}</button>}
443
+ <button className="btn ghost" onClick={async () => { await copyText(JSON.stringify(r, null, 2)); toast('总纲 JSON 已复制', 'ok') }}><Copy size={14} />复制总纲</button>
444
+ <span className="muted small-note">{plan.by ? `由 ${plan.by} 完成` : ''}</span>
445
+ </div>}
446
+ </div>
447
+ )
448
+ }
449
+ const arr = (v: any) => (Array.isArray(v) ? v : [])
450
+ function PlanResult({ r }: { r: any }) {
451
+ return (
452
+ <div className="rk-res">
453
+ <section className="sheet">
454
+ <h2 className="rk-res-title serif">《{r.title}》</h2>
455
+ {arr(r.alt_titles).length > 0 && <div className="muted small-note">备选:{arr(r.alt_titles).join(' / ')}</div>}
456
+ <div className="m2-tags rk-mt">{r.genre && <Tag tone="accent">{r.genre}</Tag>}{arr(r.tags).map((t: string) => <Tag key={t}>{t}</Tag>)}{r.target_words && <Tag>{Math.round(r.target_words / 10000)} 万字</Tag>}{r.pov && <Tag>{r.pov}</Tag>}</div>
457
+ {r.logline && <p className="rk-logline serif">{r.logline}</p>}
458
+ {r.blurb && <div className="rk-blurb">{r.blurb}</div>}
459
+ </section>
460
+ <div className="rk-grid2">
461
+ {arr(r.why).length > 0 && <section className="sheet"><h3 className="sheet-title serif">选题依据</h3><ul className="rk-ul">{arr(r.why).map((x: string, i: number) => <li key={i}>{x}</li>)}</ul></section>}
462
+ {arr(r.differentiation).length > 0 && <section className="sheet"><h3 className="sheet-title serif">差异化</h3><ul className="rk-ul">{arr(r.differentiation).map((x: string, i: number) => <li key={i}>{x}</li>)}</ul></section>}
463
+ </div>
464
+ <section className="sheet">
465
+ <h3 className="sheet-title serif">故事核心</h3>
466
+ {[['内核', r.story_core], ['主线', r.main_plot], ['结局', r.ending_direction], ['追更期待', r.reader_expectation]].filter(x => x[1]).map(([k, v]) => <div key={k} className="rk-kv"><span>{k}</span><p>{v}</p></div>)}
467
+ </section>
468
+ {arr(r.characters).length > 0 && <section className="sheet"><h3 className="sheet-title serif">人物</h3>
469
+ <div className="rk-chars">{arr(r.characters).map((c: any, i: number) => (
470
+ <div key={i} className="rk-char"><b>{c.name}</b> <span className="muted small-note">{c.role}</span>
471
+ {c.goal && <div className="small-note">目标:{c.goal}</div>}{c.fear && <div className="small-note">恐惧:{c.fear}</div>}{c.secret && <div className="small-note">秘密:{c.secret}</div>}</div>))}</div>
472
+ {arr(r.relationships).length > 0 && <ul className="rk-ul rk-mt">{arr(r.relationships).map((x: any, i: number) => <li key={i}><b>{x.from} → {x.to}</b>:{x.relation}{x.change && <span className="muted">({x.change})</span>}</li>)}</ul>}
473
+ </section>}
474
+ {arr(r.settings).length > 0 && <section className="sheet"><h3 className="sheet-title serif">设定</h3><ul className="rk-ul">{arr(r.settings).map((x: any, i: number) => <li key={i}>{typeof x === 'string' ? x : JSON.stringify(x)}</li>)}</ul></section>}
475
+ {arr(r.three_act).length > 0 && <section className="sheet"><h3 className="sheet-title serif">三幕结构</h3>
476
+ <div className="rk-acts">{arr(r.three_act).map((x: any, i: number) => <div key={i} className="rk-act"><b>{x.act}</b><div className="small-note">{x.goal}</div>{x.turning_point && <div className="small-note">转折:{x.turning_point}</div>}{x.ending && <div className="small-note muted">收束:{x.ending}</div>}</div>)}</div></section>}
477
+ {arr(r.volumes).length > 0 && <section className="sheet"><h3 className="sheet-title serif">分卷</h3>
478
+ <ol className="rk-vols">{arr(r.volumes).map((v: any, i: number) => <li key={i}><b>第 {v.volume ?? i + 1} 卷 · {v.title}</b><div>{v.goal}</div>{v.conflict && <div className="muted small-note">冲突:{v.conflict}</div>}{v.ending && <div className="muted small-note">卷末:{v.ending}</div>}</li>)}</ol></section>}
479
+ {arr(r.chapters).length > 0 && <section className="sheet"><h3 className="sheet-title serif">章纲(前 {arr(r.chapters).length} 章)</h3>
480
+ <div className="rk-chs">{arr(r.chapters).map((c: any, i: number) => <div key={i} className={cx('rk-ch', i < 3 && 'gold')}><span className="rk-no">{c.number ?? i + 1}</span><div><b>{c.title}</b><div className="small-note">{c.goal}</div>{c.hook && <div className="small-note rk-hook">钩子:{c.hook}</div>}</div></div>)}</div></section>}
481
+ <div className="rk-grid2">
482
+ {arr(r.foreshadowing).length > 0 && <section className="sheet"><h3 className="sheet-title serif">伏笔</h3><ul className="rk-ul">{arr(r.foreshadowing).map((f: any, i: number) => <li key={i}><b>{f.id}</b> 埋:{f.plant} → 收:{f.payoff}</li>)}</ul></section>}
483
+ {(arr(r.risks).length > 0 || arr(r.safety_rules).length > 0) && <section className="sheet"><h3 className="sheet-title serif">风险与红线</h3><ul className="rk-ul">{[...arr(r.risks), ...arr(r.safety_rules)].map((x: string, i: number) => <li key={i}>{x}</li>)}</ul></section>}
484
+ </div>
485
+ {arr(r.style_rules).length > 0 && <section className="sheet"><h3 className="sheet-title serif">文风</h3><ul className="rk-ul">{arr(r.style_rules).map((x: string, i: number) => <li key={i}>{x}</li>)}</ul></section>}
486
+ </div>
487
+ )
488
+ }
ui-src/src/styles.css CHANGED
@@ -1133,3 +1133,83 @@ select.input { appearance: none; padding-right: 28px; background-image: linear-g
1133
  .m2-rej summary { cursor: pointer; font-weight: 500; }
1134
  .m2-rej-row { display: flex; flex-direction: column; gap: 2px; padding: 8px 0; border-bottom: 1px dashed var(--line); cursor: pointer; font-size: 13px; }
1135
  @media (max-width: 720px) { .m2-fr { flex-direction: column; gap: 2px; } .m2-fl { padding-top: 0; } .m2-acts li { flex-direction: column; } .m2-act-meta { max-width: none; justify-content: flex-start; } }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1133
  .m2-rej summary { cursor: pointer; font-weight: 500; }
1134
  .m2-rej-row { display: flex; flex-direction: column; gap: 2px; padding: 8px 0; border-bottom: 1px dashed var(--line); cursor: pointer; font-size: 13px; }
1135
  @media (max-width: 720px) { .m2-fr { flex-direction: column; gap: 2px; } .m2-fl { padding-top: 0; } .m2-acts li { flex-direction: column; } .m2-act-meta { max-width: none; justify-content: flex-start; } }
1136
+
1137
+ /* ---------- 番茄热榜 ---------- */
1138
+ .rk .room-head { display: flex; justify-content: space-between; gap: 16px; align-items: flex-start; }
1139
+ .rk-scrape { display: flex; flex-direction: column; align-items: flex-end; gap: 6px; min-width: 180px; flex-shrink: 0; }
1140
+ .rk-prog { width: 220px; }
1141
+ .rk-bar { margin: 4px 0 6px; flex-wrap: wrap; }
1142
+ .rk-mt { margin-top: 14px; }
1143
+ .rk-sort { font-size: 12px; color: var(--ink-3); margin-bottom: 10px; }
1144
+ .rk-table-wrap { overflow-x: auto; }
1145
+ .rk-table { width: 100%; border-collapse: collapse; font-size: 13px; }
1146
+ .rk-table th { text-align: left; font-weight: 500; color: var(--ink-3); font-size: 12px; padding: 6px 8px; border-bottom: 1px solid var(--line); white-space: nowrap; }
1147
+ .rk-table td { padding: 7px 8px; border-bottom: 1px dashed var(--line); vertical-align: middle; white-space: nowrap; }
1148
+ .rk-table td.rk-top { white-space: normal; max-width: 220px; }
1149
+ .rk-table b.ok { color: var(--ok); } .rk-table b.warn { color: var(--warn); }
1150
+ .rk-sharecell { min-width: 120px; font-variant-numeric: tabular-nums; }
1151
+ .rk-share { height: 6px; background: var(--bg-2); border-radius: 3px; overflow: hidden; margin-bottom: 3px; }
1152
+ .rk-share i { display: block; height: 100%; background: var(--accent); }
1153
+ .rk-share.fresh i { background: var(--ok); }
1154
+ .rk-trend { display: inline-flex; align-items: center; font-size: 11px; margin-left: 6px; }
1155
+ .rk-trend.up { color: var(--ok); } .rk-trend.down { color: var(--err, #c44); }
1156
+ .rk-grid2 { display: grid; grid-template-columns: 1fr 1fr; gap: 0 18px; }
1157
+ .rk-tagrow { grid-template-columns: 90px 1fr 44px 50px; }
1158
+ .rk-rise { display: flex; flex-direction: column; gap: 4px; font-size: 13px; }
1159
+ .rk-rise-row { display: grid; grid-template-columns: 1fr auto 52px; gap: 10px; padding: 3px 0; border-bottom: 1px dashed var(--line); }
1160
+ .rk-rise-row .ok, .ok { color: var(--ok); }
1161
+ .rk-fresh-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(240px, 1fr)); gap: 10px; }
1162
+ .rk-fresh { padding: 10px 12px; border: 1px solid var(--line); border-radius: var(--r); background: var(--bg); font-size: 13px; display: flex; flex-direction: column; gap: 4px; }
1163
+ .rk-fresh-b { display: flex; gap: 6px; align-items: baseline; cursor: pointer; }
1164
+ .rk-fresh-b:hover .rk-ft { color: var(--accent); }
1165
+ .rk-ft { flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
1166
+ .rk-no { display: inline-block; min-width: 18px; color: var(--ink-3); font-variant-numeric: tabular-nums; font-size: 12px; }
1167
+ .rk-ai { background: var(--surface); border: 1px solid var(--accent-soft); border-left: 3px solid var(--accent); border-radius: var(--r-l); padding: 16px 20px; margin: 6px 0 14px; }
1168
+ .rk-ai.empty { display: flex; gap: 10px; align-items: flex-start; border-left-color: var(--line); }
1169
+ .rk-ai-sum { font-size: 15.5px; line-height: 1.85; margin: 8px 0 10px; }
1170
+ .rk-ai-secs { display: grid; grid-template-columns: repeat(auto-fill, minmax(280px, 1fr)); gap: 12px; }
1171
+ .rk-ai-sec h4, .rk-ideas h4 { font-size: 13.5px; margin-bottom: 4px; }
1172
+ .rk-ai-sec p { font-size: 13px; line-height: 1.75; color: var(--ink-2); margin: 2px 0; }
1173
+ .rk-ideas { margin-top: 12px; display: flex; flex-direction: column; gap: 8px; }
1174
+ .rk-idea { padding: 8px 12px; background: var(--bg); border-radius: var(--r-s); display: flex; flex-direction: column; gap: 3px; line-height: 1.7; }
1175
+ .rk-idea .tag { margin-left: 4px; }
1176
+ .rk-tagf { align-items: center; }
1177
+ .rk-books { display: flex; flex-direction: column; gap: 6px; }
1178
+ .rk-book { display: flex; gap: 12px; padding: 10px 14px; border: 1px solid var(--line); border-radius: var(--r); background: var(--surface); cursor: pointer; }
1179
+ .rk-book:hover { border-color: var(--accent); }
1180
+ .rk-pos { flex: 0 0 30px; font-size: 18px; font-weight: 600; color: var(--ink-3); text-align: center; font-variant-numeric: tabular-nums; }
1181
+ .rk-pos.top { color: var(--accent); }
1182
+ .rk-book-main { flex: 1; min-width: 0; display: flex; flex-direction: column; gap: 4px; }
1183
+ .rk-abs { font-size: 13px; color: var(--ink-2); line-height: 1.65; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; }
1184
+ .rk-book-num { flex: 0 0 110px; display: flex; flex-direction: column; align-items: flex-end; font-size: 12px; gap: 1px; }
1185
+ .rk-book-num b { font-size: 15px; }
1186
+ .rk-bd { display: flex; flex-direction: column; gap: 10px; }
1187
+ .rk-bd-abs { white-space: pre-wrap; line-height: 1.85; font-size: 14px; }
1188
+ .rk-seen { display: flex; flex-wrap: wrap; gap: 6px; }
1189
+ .rk-catcard { margin-top: 6px; padding: 8px 12px; background: var(--bg); border-radius: var(--r-s); }
1190
+ .rk-pack { margin-top: 12px; } .rk-pack summary { cursor: pointer; font-size: 13px; color: var(--ink-3); }
1191
+ .rk-pack .pre { max-height: 420px; }
1192
+ .rk-plans { display: grid; grid-template-columns: 260px 1fr; gap: 18px; align-items: start; }
1193
+ .rk-plan-list { display: flex; flex-direction: column; gap: 6px; position: sticky; top: 12px; }
1194
+ .rk-plan-item { display: flex; flex-direction: column; gap: 2px; text-align: left; padding: 10px 12px; border: 1px solid var(--line); border-radius: var(--r); background: var(--surface); }
1195
+ .rk-plan-item.on { border-color: var(--accent); box-shadow: var(--shadow-s); }
1196
+ .rk-plan-main { min-width: 0; }
1197
+ .rk-res-title { font-size: 26px; }
1198
+ .rk-logline { font-size: 16px; line-height: 1.8; margin: 12px 0 8px; }
1199
+ .rk-blurb { white-space: pre-wrap; line-height: 1.85; font-size: 14px; color: var(--ink-2); background: var(--bg); padding: 12px 14px; border-radius: var(--r-s); }
1200
+ .rk-ul { padding-left: 18px; display: flex; flex-direction: column; gap: 5px; line-height: 1.75; font-size: 13.5px; }
1201
+ .rk-kv { display: grid; grid-template-columns: 70px 1fr; gap: 10px; padding: 6px 0; border-bottom: 1px dashed var(--line); }
1202
+ .rk-kv span { color: var(--ink-3); font-size: 12.5px; padding-top: 3px; }
1203
+ .rk-kv p { line-height: 1.8; font-size: 14px; margin: 0; }
1204
+ .rk-chars { display: grid; grid-template-columns: repeat(auto-fill, minmax(240px, 1fr)); gap: 10px; }
1205
+ .rk-char { padding: 10px 12px; background: var(--bg); border-radius: var(--r-s); line-height: 1.7; }
1206
+ .rk-acts { display: grid; grid-template-columns: repeat(3, 1fr); gap: 10px; }
1207
+ .rk-act { padding: 10px 12px; background: var(--bg); border-radius: var(--r-s); line-height: 1.7; display: flex; flex-direction: column; gap: 2px; }
1208
+ .rk-vols { padding-left: 0; list-style: none; display: flex; flex-direction: column; gap: 10px; line-height: 1.75; font-size: 14px; }
1209
+ .rk-vols li { padding-left: 12px; border-left: 2px solid var(--accent-soft); }
1210
+ .rk-chs { display: flex; flex-direction: column; gap: 6px; }
1211
+ .rk-ch { display: flex; gap: 10px; padding: 6px 0; border-bottom: 1px dashed var(--line); line-height: 1.7; }
1212
+ .rk-ch.gold .rk-no { color: var(--accent); font-weight: 600; }
1213
+ .rk-hook { color: var(--accent); }
1214
+ @media (max-width: 860px) { .rk-grid2, .rk-plans, .rk-acts { grid-template-columns: 1fr; } .rk .room-head { flex-direction: column; } .rk-scrape { align-items: flex-start; } .rk-plan-list { position: static; } }
1215
+ @media (max-width: 600px) { .rk-book-num { flex-basis: 70px; } .rk-abs { -webkit-line-clamp: 3; } }