From ad92b5bc33f08c6c803f00af55bb70750dec733e Mon Sep 17 00:00:00 2001
From: butubb <1422726308@qq.com>
Date: Wed, 14 Oct 2026 08:45:41 +0800
Subject: [PATCH] =?UTF-8?q?perf(monitor):=20=E4=BD=9C=E5=93=81=E8=A1=8C?=
=?UTF-8?q?=E6=8B=86=E6=88=90=20memo=20=E7=BB=84=E4=BB=B6=20=E2=80=94?=
=?UTF-8?q?=E2=80=94=20=E7=82=B9=E5=BC=80=E8=B6=8B=E5=8A=BF=E5=9B=BE?=
=?UTF-8?q?=E4=B8=8D=E5=86=8D=E9=87=8D=E6=B8=B2=E6=9F=93=E6=95=B4=E5=BC=A0?=
=?UTF-8?q?=E8=A1=A8?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
所有交互状态(展开哪一行、正在改哪条备注、草稿文字)原先全挂在 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` 对象是新解析出来的)。要跳过它得写
自定义比较函数,而那东西一旦漏比一个字段,界面就会**静默显示旧值** —— 不划算,
先留着。
---
webui/src/components/monitor/NoteRow.tsx | 199 ++++++++++++
webui/src/components/monitor/NotesTable.tsx | 307 ++++--------------
.../src/components/monitor/metricColumns.tsx | 39 +++
3 files changed, 302 insertions(+), 243 deletions(-)
create mode 100644 webui/src/components/monitor/NoteRow.tsx
create mode 100644 webui/src/components/monitor/metricColumns.tsx
diff --git a/webui/src/components/monitor/NoteRow.tsx b/webui/src/components/monitor/NoteRow.tsx
new file mode 100644
index 0000000..a1b9954
--- /dev/null
+++ b/webui/src/components/monitor/NoteRow.tsx
@@ -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 (
+ <>
+
onToggle(rowKey)}
+ className="border-t border-cyber-border-subtle hover:bg-cyber-bg-elevated/50 cursor-pointer"
+ >
+ |
+
+
+
+ {/* min-w-0 so the title can actually truncate inside the flex row */}
+
+
+ {editing ? (
+ 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"
+ />
+ ) : (
+
+ {/* 标签放在这一行而不是标题行:标题行已经有 NEW、备注和跳转,
+ 再塞几个标签就糊成一团了。 */}
+ {note.tags.map((tag) => (
+
+ {tag.name}
+
+ ))}
+
+ {note.note_id} · {note.snapshot_count} 次快照
+
+
+
+
+ )}
+
+
+ |
+ {METRIC_COLUMNS.map((column) => (
+
+
+ |
+ ))}
+ {/* 发布日期和「首次发现」是两回事:把早就发过的作品加进监控时,
+ 前者是作者发的那天,后者是我们第一次看到它的那天。 */}
+
+ {formatDate(note.published_at)}
+ |
+
+ {formatRelative(note.first_seen_at)}
+ |
+
+ {isOpen && (
+
+ |
+
+ |
+
+ )}
+ >
+ )
+})
diff --git a/webui/src/components/monitor/NotesTable.tsx b/webui/src/components/monitor/NotesTable.tsx
index 8d0db1c..d4a7abb 100644
--- a/webui/src/components/monitor/NotesTable.tsx
+++ b/webui/src/components/monitor/NotesTable.tsx
@@ -1,21 +1,12 @@
-import { Fragment, useMemo, useRef, useState } from 'react'
-import { ChevronDown, ChevronRight, ExternalLink, Pencil, Tag, Users } from 'lucide-react'
+import { Fragment, useCallback, useMemo, useRef, useState } from 'react'
+import { ChevronDown, ChevronRight, ExternalLink, Pencil, Users } from 'lucide-react'
-import { Badge } from '@/components/ui/badge'
import { useMonitorNotes, useSetCreatorAlias, useSetNoteAlias } from '@/hooks/useMonitor'
-import {
- formatCount,
- formatDate,
- formatDateTime,
- 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 { 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'
-import { NoteTrendChart } from './NoteTrendChart'
interface NotesTableProps {
taskId: number | null
@@ -24,71 +15,6 @@ interface NotesTableProps {
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 (
-
-
{formatCount(value)}
- {deltaText && (
-
0 ? 'text-cyber-neon-green' : 'text-cyber-neon-pink'
- }`}
- >
- {deltaText}
-
- )}
-
- )
-}
-
-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 = {}
- const deltas: Record = {}
-
- 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 = {}
+ const deltas: Record = {}
+
+ 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 setAlias = useSetCreatorAlias()
- // 正在改备注的那条**作品**。和博主备注是两个互不干扰的编辑态。
- const [editingNote, setEditingNote] = useState(null)
- const [noteAliasDraft, setNoteAliasDraft] = useState('')
- const noteAliasCancelled = useRef(false)
const setNoteAlias = useSetNoteAlias()
// 正在贴标签的那条作品。null = 对话框没开。
const [taggingNote, setTaggingNote] = useState(null)
@@ -165,15 +122,21 @@ export function NotesTable({ taskId, onlyNew, tagIds = [] }: NotesTableProps) {
setAlias.mutate({ creatorHash, alias: aliasDraft })
}
- const commitNoteAlias = (noteId: string) => {
- if (noteAliasCancelled.current) {
- noteAliasCancelled.current = false
- setEditingNote(null)
- return
- }
- setEditingNote(null)
- setNoteAlias.mutate({ noteId, alias: noteAliasDraft })
- }
+ // 下面三个回调是 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 = {
@@ -388,157 +351,15 @@ export function NotesTable({ taskId, onlyNew, tagIds = [] }: NotesTableProps) {
{!isCollapsed &&
group.notes.map((note) => {
const rowKey = `${note.task_id}:${note.note_id}`
- const open = expandedNote === rowKey
return (
-
- setExpandedNote(open ? null : rowKey)}
- className="border-t border-cyber-border-subtle hover:bg-cyber-bg-elevated/50 cursor-pointer"
- >
- |
-
-
-
- {/* min-w-0 so the title can actually truncate inside the flex row */}
-
-
- {editingNote === rowKey ? (
- 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"
- />
- ) : (
-
- {/* 标签放在这一行而不是标题行:标题行已经有 NEW、备注
- 和跳转,再塞几个标签就糊成一团了。标签跟着 id 和
- 快照数走,是同一层的元信息。 */}
- {note.tags.map((tag) => (
-
- {tag.name}
-
- ))}
-
- {note.note_id} · {note.snapshot_count} 次快照
-
-
-
-
- )}
-
-
- |
- {METRIC_COLUMNS.map((column) => (
-
-
- |
- ))}
- {/* 发布日期和「首次发现」是两回事:把早就发过的作品加进监控时,
- 前者是作者发的那天,后者是我们第一次看到它的那天。 */}
-
- {formatDate(note.published_at)}
- |
-
- {formatRelative(note.first_seen_at)}
- |
-
- {open && (
-
- |
-
- |
-
- )}
-
+
)
})}
diff --git a/webui/src/components/monitor/metricColumns.tsx b/webui/src/components/monitor/metricColumns.tsx
new file mode 100644
index 0000000..8310c4a
--- /dev/null
+++ b/webui/src/components/monitor/metricColumns.tsx
@@ -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 (
+
+
{formatCount(value)}
+ {deltaText && (
+
0 ? 'text-cyber-neon-green' : 'text-cyber-neon-pink'
+ }`}
+ >
+ {deltaText}
+
+ )}
+
+ )
+}
+
+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