perf(monitor): 作品行拆成 memo 组件 —— 点开趋势图不再重渲染整张表
Deploy VitePress site to Pages / build (push) Canceled after 0s
Deploy VitePress site to Pages / Deploy (push) Canceled after 0s

所有交互状态(展开哪一行、正在改哪条备注、草稿文字)原先全挂在 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` 对象是新解析出来的)。要跳过它得写
自定义比较函数,而那东西一旦漏比一个字段,界面就会**静默显示旧值** —— 不划算,
先留着。
This commit is contained in:
2026-10-14 08:45:41 +08:00
parent 0a8f6e64c9
commit ad92b5bc33
3 changed files with 302 additions and 243 deletions
+199
View File
@@ -0,0 +1,199 @@
import { memo, useRef, useState } from 'react'
import { ExternalLink, Pencil, Tag } from 'lucide-react'
import { Badge } from '@/components/ui/badge'
import { cn } from '@/lib/utils'
import { tagColorClass } from '@/lib/tagColors'
import { formatDate, formatDateTime, formatRelative } from '@/lib/monitorFormat'
import type { MonitorNote } from '@/types/monitor'
import { COLUMN_COUNT, METRIC_COLUMNS, MetricCell } from './metricColumns'
import { NoteCover } from './NoteCover'
import { NoteTrendChart } from './NoteTrendChart'
/**
* 作品表里的一行。
*
* **单独抽出来 + memo,是为了不再「点一下重渲染整张表」。** 在这之前,展开状态、备注
* 编辑状态全都挂在 `NotesTable` 上,于是点开一条作品的趋势图,131 行全部重渲染一遍
* —— 抖音任务有一百多条,点开就卡(小红书那条只有一行,所以感觉不出来)。
*
* 现在:备注编辑状态是**行内自己的**,展开状态虽然还在父级(保持「同时只开一个」),
* 但靠 memo 把其余 130 行挡掉。同一个渲染周期里 `note` 是同一个对象引用,所以默认的
* 浅比较就够用,不需要自定义比较函数。
*/
interface NoteRowProps {
note: MonitorNote
isOpen: boolean
/** 展开/收起这一行。父级持有展开状态,所以它得知道是哪一行。 */
onToggle: (rowKey: string) => void
/** 打开贴标签的对话框。 */
onTag: (note: MonitorNote) => void
/** 保存备注。父级持有 mutation,行只负责发命令。 */
onSaveAlias: (noteId: string, alias: string) => void
}
export const NoteRow = memo(function NoteRow({
note,
isOpen,
onToggle,
onTag,
onSaveAlias,
}: NoteRowProps) {
const rowKey = `${note.task_id}:${note.note_id}`
// 备注编辑是**行内状态**:放父级的话,每敲一个字整张表都要重渲染一遍。
const [editing, setEditing] = useState(false)
const [draft, setDraft] = useState('')
// 按 Escape 是「取消」,而失焦是「保存」—— 取消时得让紧接着那次失焦闭嘴,
// 否则它会把你刚放弃的内容存进去。
const cancelled = useRef(false)
const commit = () => {
if (cancelled.current) {
cancelled.current = false
setEditing(false)
return
}
setEditing(false)
onSaveAlias(note.note_id, draft)
}
return (
<>
<tr
onClick={() => onToggle(rowKey)}
className="border-t border-cyber-border-subtle hover:bg-cyber-bg-elevated/50 cursor-pointer"
>
<td />
<td className="py-2 px-2 max-w-[320px]">
<div className="flex items-center gap-2">
<NoteCover src={note.cover} size="md" />
{/* min-w-0 so the title can actually truncate inside the flex row */}
<div className="min-w-0">
<div className="flex items-center gap-1.5">
{note.is_new && (
<Badge variant="success" className="text-[9px] px-1 py-0 flex-shrink-0">
NEW
</Badge>
)}
{/* 备注是**加**在标题前面的一枚标记,不是替换 ——
标题才是这条作品本身,扫列表时两个都要看得见。 */}
{note.note_alias && (
<Badge variant="default" className="text-[9px] px-1 py-0 flex-shrink-0">
{note.note_alias}
</Badge>
)}
<span className="truncate text-cyber-text-primary" title={note.title}>
{note.title || note.note_id}
</span>
{/* 跳转紧跟在标题后面 —— 它属于**这条作品**,挂在整行最右边
时就脱离了它修饰的东西,眼睛得横穿整张表去找。
stopPropagation,否则点它会连带展开趋势图。 */}
{note.note_url && (
<a
href={note.note_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>
)}
</div>
{editing ? (
<input
autoFocus
value={draft}
placeholder="备注,比如「重点跟拍」"
onClick={(event) => event.stopPropagation()}
onChange={(event) => setDraft(event.target.value)}
onKeyDown={(event) => {
event.stopPropagation()
if (event.key === 'Enter') commit()
if (event.key === 'Escape') {
cancelled.current = true
setEditing(false)
}
}}
onBlur={commit}
className="mt-1 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"
/>
) : (
<div className="flex items-center gap-1.5 text-[9px] text-cyber-text-muted">
{/* 标签放在这一行而不是标题行:标题行已经有 NEW、备注和跳转,
再塞几个标签就糊成一团了。 */}
{note.tags.map((tag) => (
<span
key={tag.id}
className={cn(
'rounded border px-1 py-0 text-[9px] font-mono flex-shrink-0',
tagColorClass(tag.color),
)}
>
{tag.name}
</span>
))}
<span className="truncate">
{note.note_id} · {note.snapshot_count} 次快照
</span>
<button
onClick={(event) => {
event.stopPropagation()
setDraft(note.note_alias)
setEditing(true)
}}
title="给这条作品起个备注"
className="flex items-center gap-0.5 flex-shrink-0 text-cyber-text-muted hover:text-cyber-neon-cyan"
>
<Pencil className="w-2.5 h-2.5" />
{note.note_alias ? '改备注' : '备注'}
</button>
<button
onClick={(event) => {
event.stopPropagation()
onTag(note)
}}
title="给这条作品贴标签"
className="flex items-center gap-0.5 flex-shrink-0 text-cyber-text-muted hover:text-cyber-neon-cyan"
>
<Tag className="w-2.5 h-2.5" />
标签
</button>
</div>
)}
</div>
</div>
</td>
{METRIC_COLUMNS.map((column) => (
<td key={column.key} className="py-2 px-2">
<MetricCell value={note.metrics[column.key]} delta={note.deltas[column.key]} />
</td>
))}
{/* 发布日期和「首次发现」是两回事:把早就发过的作品加进监控时,
前者是作者发的那天,后者是我们第一次看到它的那天。 */}
<td
className="py-2 px-2 text-right text-[10px] text-cyber-text-muted whitespace-nowrap"
title={formatDateTime(note.published_at)}
>
{formatDate(note.published_at)}
</td>
<td className="py-2 px-2 text-right text-[10px] text-cyber-text-muted">
{formatRelative(note.first_seen_at)}
</td>
</tr>
{isOpen && (
<tr className="bg-cyber-bg-secondary/40">
<td colSpan={COLUMN_COUNT} className="px-4 py-3">
<NoteTrendChart
noteId={note.note_id}
taskId={note.task_id}
noteTitle={note.title}
/>
</td>
</tr>
)}
</>
)
})
+64 -243
View File
@@ -1,21 +1,12 @@
import { Fragment, useMemo, useRef, useState } from 'react' import { Fragment, useCallback, useMemo, useRef, useState } from 'react'
import { ChevronDown, ChevronRight, ExternalLink, Pencil, Tag, Users } from 'lucide-react' import { ChevronDown, ChevronRight, ExternalLink, Pencil, Users } from 'lucide-react'
import { Badge } from '@/components/ui/badge'
import { useMonitorNotes, useSetCreatorAlias, useSetNoteAlias } from '@/hooks/useMonitor' import { useMonitorNotes, useSetCreatorAlias, useSetNoteAlias } from '@/hooks/useMonitor'
import { import { formatCount, formatDateTime } from '@/lib/monitorFormat'
formatCount, import type { MonitorCreator, MonitorNote } from '@/types/monitor'
formatDate, import { METRIC_COLUMNS, MetricCell } from './metricColumns'
formatDateTime, import { NoteRow } from './NoteRow'
formatDelta,
formatRelative,
} from '@/lib/monitorFormat'
import { cn } from '@/lib/utils'
import { tagColorClass } from '@/lib/tagColors'
import type { MonitorCreator, MonitorNote, NoteMetrics } from '@/types/monitor'
import { NoteCover } from './NoteCover'
import { NoteTagPicker } from './NoteTagPicker' import { NoteTagPicker } from './NoteTagPicker'
import { NoteTrendChart } from './NoteTrendChart'
interface NotesTableProps { interface NotesTableProps {
taskId: number | null taskId: number | null
@@ -24,71 +15,6 @@ interface NotesTableProps {
tagIds?: number[] tagIds?: number[]
} }
/** A metric with its change vs the previous run underneath. */
function MetricCell({ value, delta }: { value: number | null; delta: number | null }) {
const deltaText = formatDelta(delta)
return (
<div className="text-right">
<div className="font-mono text-xs text-cyber-text-primary">{formatCount(value)}</div>
{deltaText && (
<div
className={`font-mono text-[9px] ${
(delta ?? 0) > 0 ? 'text-cyber-neon-green' : 'text-cyber-neon-pink'
}`}
>
{deltaText}
</div>
)}
</div>
)
}
const METRIC_COLUMNS: Array<{ key: keyof NoteMetrics; label: string }> = [
{ key: 'liked_count', label: '点赞' },
{ key: 'comment_count', label: '评论' },
{ key: 'collected_count', label: '收藏' },
{ key: 'share_count', label: '分享' },
]
/**
* 一个博主名下所有作品的指标合计。
*
* **全为 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 }
}
// 多出来的那几列:展开箭头、作品、发布日期、首次发现;分组表头会跨掉整行。
// 作品的跳转链接**不算一列** —— 它跟在标题后面,见下面的行渲染。
const COLUMN_COUNT = METRIC_COLUMNS.length + 4
/** /**
* 账号级指标那几个字段。 * 账号级指标那几个字段。
* *
@@ -126,6 +52,41 @@ function CreatorStats({ stats }: { stats: AccountStats }) {
) )
} }
/**
* 一个博主名下所有作品的指标合计。
*
* **全为 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 }
}
/** /**
* 作品表,**按博主分组**。 * 作品表,**按博主分组**。
* *
@@ -147,10 +108,6 @@ export function NotesTable({ taskId, onlyNew, tagIds = [] }: NotesTableProps) {
// 否则它会把你刚放弃的内容存进去。 // 否则它会把你刚放弃的内容存进去。
const aliasCancelled = useRef(false) const aliasCancelled = useRef(false)
const setAlias = useSetCreatorAlias() const setAlias = useSetCreatorAlias()
// 正在改备注的那条**作品**。和博主备注是两个互不干扰的编辑态。
const [editingNote, setEditingNote] = useState<string | null>(null)
const [noteAliasDraft, setNoteAliasDraft] = useState('')
const noteAliasCancelled = useRef(false)
const setNoteAlias = useSetNoteAlias() const setNoteAlias = useSetNoteAlias()
// 正在贴标签的那条作品。null = 对话框没开。 // 正在贴标签的那条作品。null = 对话框没开。
const [taggingNote, setTaggingNote] = useState<MonitorNote | null>(null) const [taggingNote, setTaggingNote] = useState<MonitorNote | null>(null)
@@ -165,15 +122,21 @@ export function NotesTable({ taskId, onlyNew, tagIds = [] }: NotesTableProps) {
setAlias.mutate({ creatorHash, alias: aliasDraft }) setAlias.mutate({ creatorHash, alias: aliasDraft })
} }
const commitNoteAlias = (noteId: string) => { // 下面三个回调是 NoteRow 的 props,**身份必须稳定** —— 一变 memo 就全失效,一次点击
if (noteAliasCancelled.current) { // 又变回重渲染 131 行。
noteAliasCancelled.current = false const toggleNote = useCallback(
setEditingNote(null) (rowKey: string) => setExpandedNote((prev) => (prev === rowKey ? null : rowKey)),
return [],
} )
setEditingNote(null) const tagNote = useCallback((note: MonitorNote) => setTaggingNote(note), [])
setNoteAlias.mutate({ noteId, alias: noteAliasDraft }) // `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(() => { const groups = useMemo(() => {
type Group = { type Group = {
@@ -388,157 +351,15 @@ export function NotesTable({ taskId, onlyNew, tagIds = [] }: NotesTableProps) {
{!isCollapsed && {!isCollapsed &&
group.notes.map((note) => { group.notes.map((note) => {
const rowKey = `${note.task_id}:${note.note_id}` const rowKey = `${note.task_id}:${note.note_id}`
const open = expandedNote === rowKey
return ( return (
<Fragment key={rowKey}> <NoteRow
<tr key={rowKey}
onClick={() => setExpandedNote(open ? null : rowKey)} note={note}
className="border-t border-cyber-border-subtle hover:bg-cyber-bg-elevated/50 cursor-pointer" isOpen={expandedNote === rowKey}
> onToggle={toggleNote}
<td /> onTag={tagNote}
<td className="py-2 px-2 max-w-[320px]"> onSaveAlias={saveNoteAlias}
<div className="flex items-center gap-2"> />
<NoteCover src={note.cover} size="md" />
{/* min-w-0 so the title can actually truncate inside the flex row */}
<div className="min-w-0">
<div className="flex items-center gap-1.5">
{note.is_new && (
<Badge
variant="success"
className="text-[9px] px-1 py-0 flex-shrink-0"
>
NEW
</Badge>
)}
{/* 备注是**加**在标题前面的一枚标记,不是替换 ——
标题才是这条作品本身,扫列表时两个都要看得见。 */}
{note.note_alias && (
<Badge
variant="default"
className="text-[9px] px-1 py-0 flex-shrink-0"
>
{note.note_alias}
</Badge>
)}
<span
className="truncate text-cyber-text-primary"
title={note.title}
>
{note.title || note.note_id}
</span>
{/* 跳转紧跟在标题后面 —— 它属于**这条作品**,挂在整行最右边
时就脱离了它修饰的东西,眼睛得横穿整张表去找。
stopPropagation,否则点它会连带展开趋势图。 */}
{note.note_url && (
<a
href={note.note_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>
)}
</div>
{editingNote === rowKey ? (
<input
autoFocus
value={noteAliasDraft}
placeholder="备注,比如「重点跟拍」"
onClick={(event) => event.stopPropagation()}
onChange={(event) => setNoteAliasDraft(event.target.value)}
onKeyDown={(event) => {
event.stopPropagation()
if (event.key === 'Enter') commitNoteAlias(note.note_id)
if (event.key === 'Escape') {
noteAliasCancelled.current = true
setEditingNote(null)
}
}}
onBlur={() => commitNoteAlias(note.note_id)}
className="mt-1 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"
/>
) : (
<div className="flex items-center gap-1.5 text-[9px] text-cyber-text-muted">
{/* 标签放在这一行而不是标题行:标题行已经有 NEW、备注
和跳转,再塞几个标签就糊成一团了。标签跟着 id 和
快照数走,是同一层的元信息。 */}
{note.tags.map((tag) => (
<span
key={tag.id}
className={cn(
'rounded border px-1 py-0 text-[9px] font-mono flex-shrink-0',
tagColorClass(tag.color),
)}
>
{tag.name}
</span>
))}
<span className="truncate">
{note.note_id} · {note.snapshot_count} 次快照
</span>
<button
onClick={(event) => {
event.stopPropagation()
setNoteAliasDraft(note.note_alias)
setEditingNote(rowKey)
}}
title="给这条作品起个备注"
className="flex items-center gap-0.5 flex-shrink-0 text-cyber-text-muted hover:text-cyber-neon-cyan"
>
<Pencil className="w-2.5 h-2.5" />
{note.note_alias ? '改备注' : '备注'}
</button>
<button
onClick={(event) => {
event.stopPropagation()
setTaggingNote(note)
}}
title="给这条作品贴标签"
className="flex items-center gap-0.5 flex-shrink-0 text-cyber-text-muted hover:text-cyber-neon-cyan"
>
<Tag className="w-2.5 h-2.5" />
标签
</button>
</div>
)}
</div>
</div>
</td>
{METRIC_COLUMNS.map((column) => (
<td key={column.key} className="py-2 px-2">
<MetricCell
value={note.metrics[column.key]}
delta={note.deltas[column.key]}
/>
</td>
))}
{/* 发布日期和「首次发现」是两回事:把早就发过的作品加进监控时,
前者是作者发的那天,后者是我们第一次看到它的那天。 */}
<td
className="py-2 px-2 text-right text-[10px] text-cyber-text-muted whitespace-nowrap"
title={formatDateTime(note.published_at)}
>
{formatDate(note.published_at)}
</td>
<td className="py-2 px-2 text-right text-[10px] text-cyber-text-muted">
{formatRelative(note.first_seen_at)}
</td>
</tr>
{open && (
<tr className="bg-cyber-bg-secondary/40">
<td colSpan={COLUMN_COUNT} className="px-4 py-3">
<NoteTrendChart
noteId={note.note_id}
taskId={note.task_id}
noteTitle={note.title}
/>
</td>
</tr>
)}
</Fragment>
) )
})} })}
</Fragment> </Fragment>
@@ -0,0 +1,39 @@
import { formatCount, formatDelta } from '@/lib/monitorFormat'
import type { NoteMetrics } from '@/types/monitor'
/**
* 四项指标列 + 单元格。
*
* 单独一个模块,是因为**表格和行都要用它** —— 行已经拆成独立的 `NoteRow`,而它再去
* 从 `NotesTable` 里 import 就成环了。
*/
/** A metric with its change vs the previous run underneath. */
export function MetricCell({ value, delta }: { value: number | null; delta: number | null }) {
const deltaText = formatDelta(delta)
return (
<div className="text-right">
<div className="font-mono text-xs text-cyber-text-primary">{formatCount(value)}</div>
{deltaText && (
<div
className={`font-mono text-[9px] ${
(delta ?? 0) > 0 ? 'text-cyber-neon-green' : 'text-cyber-neon-pink'
}`}
>
{deltaText}
</div>
)}
</div>
)
}
export const METRIC_COLUMNS: Array<{ key: keyof NoteMetrics; label: string }> = [
{ key: 'liked_count', label: '点赞' },
{ key: 'comment_count', label: '评论' },
{ key: 'collected_count', label: '收藏' },
{ key: 'share_count', label: '分享' },
]
// 多出来的那几列:展开箭头、作品、发布日期、首次发现;分组表头会跨掉整行。
// 作品的跳转链接**不算一列** —— 它跟在标题后面。
export const COLUMN_COUNT = METRIC_COLUMNS.length + 4