所有交互状态(展开哪一行、正在改哪条备注、草稿文字)原先全挂在 NotesTable 上,于是 **点开一条作品的趋势图 = 131 行全部重渲染一遍**。抖音任务有一百多条作品,点开就卡; 小红书那条只有一行,所以一直没感觉。 拆法: * `NoteRow` 独立成组件并 memo。备注编辑状态(editing/draft/cancel)**下放到行内** —— 它本来就不关别的行的事,放父级等于每敲一个字重渲染整张表。 * 展开状态留在父级(保持「同时只开一个」),行只拿一个 isOpen 布尔量。 * 三个回调用 useCallback 固定身份 —— **这是 memo 能不能生效的关键**。其中 `saveNoteAlias` 不能拿 `useMutation` 返回的对象当依赖(那个对象每次渲染都是新的, 等于没加 useCallback),所以经 ref 取 mutate。 为什么 memo 用默认的浅比较就够:同一个渲染周期里 `note` 是**同一个对象引用** (`groups` 那个 useMemo 的依赖没变),isOpen 是布尔量,回调身份固定 —— 其余 130 行 props 全等,直接跳过。 顺带 `MetricCell` / `METRIC_COLUMNS` / `COLUMN_COUNT` 挪进 metricColumns.tsx, 免得 NoteRow 反过来 import NotesTable 成环。 **没做**:每 5 秒的轮询仍会让整表重渲染(`note` 对象是新解析出来的)。要跳过它得写 自定义比较函数,而那东西一旦漏比一个字段,界面就会**静默显示旧值** —— 不划算, 先留着。
386 lines
16 KiB
TypeScript
386 lines
16 KiB
TypeScript
import { Fragment, useCallback, useMemo, useRef, useState } from 'react'
|
||
import { ChevronDown, ChevronRight, ExternalLink, Pencil, Users } from 'lucide-react'
|
||
|
||
import { useMonitorNotes, useSetCreatorAlias, useSetNoteAlias } from '@/hooks/useMonitor'
|
||
import { formatCount, formatDateTime } from '@/lib/monitorFormat'
|
||
import type { MonitorCreator, MonitorNote } from '@/types/monitor'
|
||
import { METRIC_COLUMNS, MetricCell } from './metricColumns'
|
||
import { NoteRow } from './NoteRow'
|
||
import { NoteTagPicker } from './NoteTagPicker'
|
||
|
||
interface NotesTableProps {
|
||
taskId: number | null
|
||
onlyNew: boolean
|
||
/** 按标签筛。空数组 = 不筛。命中的是**任意一个**选中的标签。 */
|
||
tagIds?: number[]
|
||
}
|
||
|
||
/**
|
||
* 账号级指标那几个字段。
|
||
*
|
||
* 作品的 payload 和博主的 payload 都带这一组,值也一样(同一次采集写的同一行),
|
||
* 所以组件只认字段、不认来源。
|
||
*/
|
||
type AccountStats = Pick<
|
||
MonitorCreator,
|
||
'creator_fans' | 'creator_total_favorited' | 'creator_works' | 'creator_stats_at'
|
||
>
|
||
|
||
/**
|
||
* 博主的**账号级**指标:粉丝 / 总获赞 / 作品数。
|
||
*
|
||
* 作品列表给不了这个 —— 那几列说的是「这条作品涨了多少赞」,这里说的是「这个人整个
|
||
* 账号在涨还是在掉」。**一个都没采到时整块不画**:画成「粉丝 0」比不画糟得多,那是
|
||
* 一句假话。
|
||
*/
|
||
function CreatorStats({ stats }: { stats: AccountStats }) {
|
||
const parts = [
|
||
stats.creator_fans !== null && `粉丝 ${formatCount(stats.creator_fans)}`,
|
||
stats.creator_total_favorited !== null && `获赞 ${formatCount(stats.creator_total_favorited)}`,
|
||
stats.creator_works !== null && `${formatCount(stats.creator_works)} 作品`,
|
||
].filter(Boolean) as string[]
|
||
|
||
if (parts.length === 0) return null
|
||
|
||
return (
|
||
<span
|
||
className="text-cyber-text-muted flex-shrink-0"
|
||
title={`账号指标采集于 ${formatDateTime(stats.creator_stats_at)}`}
|
||
>
|
||
{parts.join(' · ')}
|
||
</span>
|
||
)
|
||
}
|
||
|
||
/**
|
||
* 一个博主名下所有作品的指标合计。
|
||
*
|
||
* **全为 null 时结果是 null 而不是 0** —— 与项目一贯的口径一致:「0」是真实值,
|
||
* 「null」是不知道。合计成 0 会让"还没采到"看起来像"互动为零"。
|
||
*/
|
||
function sumMetrics(notes: MonitorNote[]) {
|
||
const values: Record<string, number | null> = {}
|
||
const deltas: Record<string, number | null> = {}
|
||
|
||
for (const column of METRIC_COLUMNS) {
|
||
let sum = 0
|
||
let sawValue = false
|
||
let deltaSum = 0
|
||
let sawDelta = false
|
||
|
||
for (const note of notes) {
|
||
const value = note.metrics[column.key]
|
||
if (value !== null && value !== undefined) {
|
||
sum += value
|
||
sawValue = true
|
||
}
|
||
const delta = note.deltas[column.key]
|
||
if (delta !== null && delta !== undefined) {
|
||
deltaSum += delta
|
||
sawDelta = true
|
||
}
|
||
}
|
||
|
||
values[column.key] = sawValue ? sum : null
|
||
deltas[column.key] = sawDelta ? deltaSum : null
|
||
}
|
||
return { values, deltas }
|
||
}
|
||
|
||
/**
|
||
* 作品表,**按博主分组**。
|
||
*
|
||
* 一个任务可以配多个博主,平铺的话根本看不出哪篇是谁的。分组键是
|
||
* `creator_hash` —— 爬虫刻意不落原始 user_id,所以这是唯一稳定的创作者标识;
|
||
* 显示名是已脱敏的昵称(张***三)。两者都认不出来时才退回"未知博主"。
|
||
*/
|
||
export function NotesTable({ taskId, onlyNew, tagIds = [] }: NotesTableProps) {
|
||
const { data, isLoading } = useMonitorNotes(taskId, onlyNew, tagIds)
|
||
const notes = data?.notes
|
||
const creators = data?.creators
|
||
const [expandedNote, setExpandedNote] = useState<string | null>(null)
|
||
// 折叠状态按博主记。默认全展开 —— 藏起来的数据比多滚两屏更糟。
|
||
const [collapsed, setCollapsed] = useState<Set<string>>(new Set())
|
||
// 正在改备注的那个博主(creator_hash);null = 没在改。
|
||
const [editingCreator, setEditingCreator] = useState<string | null>(null)
|
||
const [aliasDraft, setAliasDraft] = useState('')
|
||
// 按 Escape 是「取消」,而失焦是「保存」—— 取消时得让紧接着那次失焦闭嘴,
|
||
// 否则它会把你刚放弃的内容存进去。
|
||
const aliasCancelled = useRef(false)
|
||
const setAlias = useSetCreatorAlias()
|
||
const setNoteAlias = useSetNoteAlias()
|
||
// 正在贴标签的那条作品。null = 对话框没开。
|
||
const [taggingNote, setTaggingNote] = useState<MonitorNote | null>(null)
|
||
|
||
const commitAlias = (creatorHash: string) => {
|
||
if (aliasCancelled.current) {
|
||
aliasCancelled.current = false
|
||
setEditingCreator(null)
|
||
return
|
||
}
|
||
setEditingCreator(null)
|
||
setAlias.mutate({ creatorHash, alias: aliasDraft })
|
||
}
|
||
|
||
// 下面三个回调是 NoteRow 的 props,**身份必须稳定** —— 一变 memo 就全失效,一次点击
|
||
// 又变回重渲染 131 行。
|
||
const toggleNote = useCallback(
|
||
(rowKey: string) => setExpandedNote((prev) => (prev === rowKey ? null : rowKey)),
|
||
[],
|
||
)
|
||
const tagNote = useCallback((note: MonitorNote) => setTaggingNote(note), [])
|
||
// `useMutation` 返回的那个**对象**每次渲染都是新的,所以不能拿它当依赖(那样等于
|
||
// 没加 useCallback)。mutate 函数经 ref 取用,这个回调就永远不变。
|
||
const aliasMutate = useRef(setNoteAlias.mutate)
|
||
aliasMutate.current = setNoteAlias.mutate
|
||
const saveNoteAlias = useCallback(
|
||
(noteId: string, alias: string) => aliasMutate.current({ noteId, alias }),
|
||
[],
|
||
)
|
||
|
||
const groups = useMemo(() => {
|
||
type Group = {
|
||
key: string
|
||
name: string
|
||
alias: string
|
||
/** 主页链接。空串就是不画那个按钮(见 MonitorCreator.creator_url)。 */
|
||
url: string
|
||
/** 服务端说的这条博主名下有多少作品 —— 列表被 `onlyNew` 滤过时和 `notes.length` 不等。 */
|
||
totalNotes: number
|
||
stats: MonitorCreator | null
|
||
notes: MonitorNote[]
|
||
}
|
||
const byCreator = new Map<string, Group>()
|
||
|
||
// **先放博主,不是先放作品。** 「一条作品都没有的博主」在作品里根本推不出来 ——
|
||
// 目标加了、资料也采到了、粉丝数就躺在库里,可界面上什么都看不见。而他恰恰是最该
|
||
// 看见的一个:还在涨粉,只是最近没发东西。
|
||
for (const creator of creators ?? []) {
|
||
const key = creator.creator_hash || '__unknown__'
|
||
const existing = byCreator.get(key)
|
||
if (existing) {
|
||
// 同一个博主可能挂在多个任务下(服务端按 任务×博主 给),合并成一组。
|
||
existing.totalNotes += creator.note_count
|
||
if (!existing.stats?.creator_stats_at && creator.creator_stats_at) {
|
||
existing.stats = creator
|
||
}
|
||
existing.name ||= creator.creator_name
|
||
// 备注按 (platform, creator_hash) 存,所以跨任务就是同一条,取到即可。
|
||
existing.alias ||= creator.creator_alias
|
||
existing.url ||= creator.creator_url
|
||
continue
|
||
}
|
||
byCreator.set(key, {
|
||
key,
|
||
name: creator.creator_name || '',
|
||
alias: creator.creator_alias || '',
|
||
url: creator.creator_url || '',
|
||
totalNotes: creator.note_count,
|
||
stats: creator,
|
||
notes: [],
|
||
})
|
||
}
|
||
|
||
for (const note of notes ?? []) {
|
||
// 作品模式下每条作品都会带 creator_hash;真丢了也要有个兜底分组,
|
||
// 否则那些作品会凭空消失。
|
||
const key = note.creator_hash || '__unknown__'
|
||
let group = byCreator.get(key)
|
||
if (!group) {
|
||
group = {
|
||
key,
|
||
name: note.creator_name || '',
|
||
alias: note.creator_alias || '',
|
||
url: '',
|
||
totalNotes: 0,
|
||
stats: null,
|
||
notes: [],
|
||
}
|
||
byCreator.set(key, group)
|
||
}
|
||
group.notes.push(note)
|
||
group.name ||= note.creator_name || ''
|
||
group.alias ||= note.creator_alias || ''
|
||
}
|
||
|
||
return [...byCreator.values()]
|
||
}, [notes, creators])
|
||
|
||
if (isLoading) {
|
||
return <p className="py-8 text-center text-[11px] font-mono text-cyber-text-muted">加载中…</p>
|
||
}
|
||
|
||
// 博主有、作品没有也是**要画**的:那正是「这个号还没被删,只是没发东西」。
|
||
if (groups.length === 0) {
|
||
return (
|
||
<p className="py-8 text-center text-[11px] font-mono text-cyber-text-muted">
|
||
{taskId === null
|
||
? '请先选择一个监控任务'
|
||
: onlyNew
|
||
? '最近一轮没有新增作品'
|
||
: '还没有采集到作品,运行一次任务后即可看到'}
|
||
</p>
|
||
)
|
||
}
|
||
|
||
const toggleCreator = (key: string) =>
|
||
setCollapsed((prev) => {
|
||
const next = new Set(prev)
|
||
if (next.has(key)) next.delete(key)
|
||
else next.add(key)
|
||
return next
|
||
})
|
||
|
||
return (
|
||
<div className="overflow-x-auto terminal-scroll">
|
||
<table className="w-full text-xs font-mono">
|
||
<thead className="sticky top-0 bg-cyber-bg-tertiary">
|
||
<tr className="text-cyber-text-secondary text-[10px]">
|
||
<th className="w-6" />
|
||
<th className="text-left font-normal py-2 px-2">作品</th>
|
||
{METRIC_COLUMNS.map((column) => (
|
||
<th key={column.key} className="text-right font-normal py-2 px-2">
|
||
{column.label}
|
||
</th>
|
||
))}
|
||
<th className="text-right font-normal py-2 px-2">发布日期</th>
|
||
<th className="text-right font-normal py-2 px-2">首次发现</th>
|
||
</tr>
|
||
</thead>
|
||
<tbody>
|
||
{groups.map((group) => {
|
||
const isCollapsed = collapsed.has(group.key)
|
||
const totals = sumMetrics(group.notes)
|
||
return (
|
||
<Fragment key={group.key}>
|
||
{/* 组头与数据行**列对齐**:每个指标列给出该博主的合计,下面再带本轮增量。
|
||
折叠之后如果什么都看不到,那折叠就只是把信息藏起来了。 */}
|
||
<tr
|
||
onClick={() => toggleCreator(group.key)}
|
||
className="border-t border-cyber-border-subtle bg-cyber-bg-tertiary/50 cursor-pointer hover:bg-cyber-bg-elevated/50"
|
||
>
|
||
<td className="py-1.5 px-1 text-cyber-text-muted">
|
||
{isCollapsed ? (
|
||
<ChevronRight className="w-3 h-3" />
|
||
) : (
|
||
<ChevronDown className="w-3 h-3" />
|
||
)}
|
||
</td>
|
||
<td className="py-1.5 px-2">
|
||
{editingCreator === group.key ? (
|
||
<input
|
||
autoFocus
|
||
value={aliasDraft}
|
||
placeholder="备注,比如「竞品A」"
|
||
onClick={(event) => event.stopPropagation()}
|
||
onChange={(event) => setAliasDraft(event.target.value)}
|
||
onKeyDown={(event) => {
|
||
event.stopPropagation()
|
||
if (event.key === 'Enter') commitAlias(group.key)
|
||
if (event.key === 'Escape') {
|
||
aliasCancelled.current = true
|
||
setEditingCreator(null)
|
||
}
|
||
}}
|
||
onBlur={() => commitAlias(group.key)}
|
||
className="w-full rounded border border-cyber-neon-cyan/40 bg-cyber-bg-tertiary px-1.5 py-0.5 text-[11px] font-mono text-cyber-text-primary outline-none"
|
||
/>
|
||
) : (
|
||
<span className="flex items-center gap-1.5">
|
||
<Users className="w-3 h-3 text-cyber-neon-cyan flex-shrink-0" />
|
||
<span className="text-cyber-text-primary truncate">
|
||
{group.alias || group.name || '未知博主'}
|
||
</span>
|
||
{/* 起了备注之后,平台昵称降成副标题 —— 它仍是有用的对照。 */}
|
||
{group.alias && group.name && (
|
||
<span className="text-cyber-text-muted truncate">{group.name}</span>
|
||
)}
|
||
{/* 跳到他主页。链接是采集时从资料接口带回来的(哈希拼不出地址),
|
||
拿不到就整块不画 —— 一个点开 404 的按钮比没有按钮糟。 */}
|
||
{group.url && (
|
||
<a
|
||
href={group.url}
|
||
target="_blank"
|
||
rel="noopener noreferrer"
|
||
onClick={(event) => event.stopPropagation()}
|
||
title="打开博主主页"
|
||
className="text-cyber-text-muted hover:text-cyber-neon-cyan flex-shrink-0"
|
||
>
|
||
<ExternalLink className="w-3 h-3" />
|
||
</a>
|
||
)}
|
||
<span className="text-cyber-text-muted flex-shrink-0">
|
||
{/* 被 onlyNew 滤过时,把「显示了几篇 / 一共几篇」都说出来,
|
||
否则「1 篇」会让人以为这个号只发过一条。 */}
|
||
{group.notes.length}
|
||
{group.totalNotes > group.notes.length && `/${group.totalNotes}`} 篇
|
||
</span>
|
||
{group.stats && <CreatorStats stats={group.stats} />}
|
||
{/* 博主在、作品一条都没有 —— 说清楚,别让人以为列表挂了。 */}
|
||
{group.notes.length === 0 && (
|
||
<span className="text-cyber-text-muted/70 flex-shrink-0">
|
||
暂无作品
|
||
</span>
|
||
)}
|
||
<button
|
||
onClick={(event) => {
|
||
event.stopPropagation()
|
||
setAliasDraft(group.alias)
|
||
setEditingCreator(group.key)
|
||
}}
|
||
title="给这个博主起个备注"
|
||
className="text-cyber-text-muted hover:text-cyber-neon-cyan flex-shrink-0"
|
||
>
|
||
<Pencil className="w-3 h-3" />
|
||
</button>
|
||
</span>
|
||
)}
|
||
</td>
|
||
{METRIC_COLUMNS.map((column) => (
|
||
<td key={column.key} className="py-1.5 px-2">
|
||
<MetricCell
|
||
value={totals.values[column.key]}
|
||
delta={totals.deltas[column.key]}
|
||
/>
|
||
</td>
|
||
))}
|
||
<td />
|
||
<td />
|
||
</tr>
|
||
|
||
{!isCollapsed &&
|
||
group.notes.map((note) => {
|
||
const rowKey = `${note.task_id}:${note.note_id}`
|
||
return (
|
||
<NoteRow
|
||
key={rowKey}
|
||
note={note}
|
||
isOpen={expandedNote === rowKey}
|
||
onToggle={toggleNote}
|
||
onTag={tagNote}
|
||
onSaveAlias={saveNoteAlias}
|
||
/>
|
||
)
|
||
})}
|
||
</Fragment>
|
||
)
|
||
})}
|
||
</tbody>
|
||
</table>
|
||
|
||
{/* 对话框挂在表格**外面** —— 放在 tbody 里会因为表格的布局规则出问题。 */}
|
||
{taggingNote && (
|
||
<NoteTagPicker
|
||
noteId={taggingNote.note_id}
|
||
noteTitle={taggingNote.title}
|
||
current={taggingNote.tags}
|
||
open={taggingNote !== null}
|
||
onOpenChange={(open) => {
|
||
if (!open) setTaggingNote(null)
|
||
}}
|
||
/>
|
||
)}
|
||
</div>
|
||
)
|
||
}
|