kongdeqiang
2026-10-12 ed3c2513c35efa714f2a377aef55501dd15d1fec
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
/**
 * 消息树前端工具函数。
 *
 * 后端返回的是嵌套树(根节点数组,节点内嵌 children)。
 * 但「渲染当前对话」需要的是**一条线性路径**:
 * 根 → 用户第一条 → AI 回复 → 用户第二条 → ...
 *
 * 原因:消息树可能因为「重新生成 / 编辑」而产生分支,
 * 而任一时刻用户只看得到其中一条分支。何时切换分支由用户决定。
 *
 * 因此这里的工作流是:
 *   1. 用 flattenTree 建立 id -> 节点 的索引
 *   2. 用 activeChildId 映射记录「每个父节点当前选中哪个子节点」
 *   3. 用 buildPath 沿着选择走出一条线性路径用于渲染
 */
 
/**
 * 把嵌套树压平成 Map,便于 O(1) 查找任意节点。
 *
 * @param {Array} tree 根节点数组
 * @returns {Map<number, object>}
 */
export function flattenTree(tree) {
  const map = new Map()
 
  const walk = (nodes) => {
    if (!Array.isArray(nodes)) return
    for (const node of nodes) {
      map.set(node.id, node)
      walk(node.children)
    }
  }
 
  walk(tree)
  return map
}
 
/**
 * 从后端返回的树中提取初始的「活跃分支」选择。
 *
 * 后端会为每个多分支节点计算 activeChildId(默认是最后生成的子节点),
 * 即用户上次实际在看的那个分支。
 *
 * @param {Array} tree
 * @returns {Record<number, number>} parentId -> 选中的 childId
 */
export function extractActiveChildIds(tree) {
  const selections = {}
 
  const walk = (nodes) => {
    if (!Array.isArray(nodes)) return
    for (const node of nodes) {
      if (node.children?.length > 0) {
        // 后端给的 activeChildId 优先;缺失时回退到最后一个子节点
        const fallback = node.children[node.children.length - 1].id
        selections[node.id] = node.activeChildId ?? fallback
      }
      walk(node.children)
    }
  }
 
  walk(tree)
  return selections
}
 
/**
 * 沿活跃分支走出一条线性路径。
 *
 * 容错:若 selections 指向的 childId 不在 children 里(例如刚删除了该分支),
 * 自动回退到最后一个子节点,避免渲染中断。
 *
 * @param {Array} tree
 * @param {Record<number, number>} selections parentId -> childId
 * @returns {Array} 按对话顺序排列的消息数组
 */
export function buildPath(tree, selections = {}) {
  const path = []
  if (!Array.isArray(tree) || tree.length === 0) return path
 
  // 根层也可能存在多个节点(异常数据下的「孤儿上浮」),
  // 这里取最后一个作为当前对话线的起点
  let current = tree[tree.length - 1]
 
  // guard 防止脏数据成环导致死循环
  let guard = 0
  const maxSteps = 10000
 
  while (current && guard++ < maxSteps) {
    path.push(current)
 
    const children = current.children
    if (!Array.isArray(children) || children.length === 0) {
      break
    }
 
    const selectedId = selections[current.id]
    let next = children.find((child) => child.id === selectedId)
 
    if (!next) {
      // 选择失效:回退到最后一个子节点,并修正映射
      next = children[children.length - 1]
      selections[current.id] = next.id
    }
 
    current = next
  }
 
  return path
}
 
/**
 * 切换某个消息下选中的子分支。
 *
 * @param {object} message 当前消息节点
 * @param {number} delta   +1 下一个分支,-1 上一个分支
 * @param {Record<number, number>} selections 会被就地修改
 * @returns {boolean} 是否真的发生了切换(false 表示已在首/末分支)
 */
export function switchBranch(message, delta, selections) {
  const children = message?.children
  if (!Array.isArray(children) || children.length <= 1) return false
 
  const currentId = selections[message.id] ?? children[children.length - 1].id
  let index = children.findIndex((child) => child.id === currentId)
  if (index === -1) index = children.length - 1
 
  const nextIndex = index + delta
  if (nextIndex < 0 || nextIndex >= children.length) return false
 
  selections[message.id] = children[nextIndex].id
  return true
}
 
/**
 * 计算某个多分支消息当前显示的是第几个分支。
 *
 * @returns {{index: number, total: number}} index 从 1 开始
 */
export function branchPosition(message, selections) {
  const children = message?.children ?? []
  const total = children.length
  if (total === 0) return { index: 0, total: 0 }
 
  const currentId = selections[message.id] ?? children[total - 1].id
  const found = children.findIndex((child) => child.id === currentId)
  return { index: found === -1 ? total : found + 1, total }
}
 
/**
 * 找到某个节点在树中的父节点。
 *
 * @param {Map<number, object>} nodeMap flattenTree 的结果
 * @param {number} nodeId
 * @returns {object|null}
 */
export function findParent(nodeMap, nodeId) {
  for (const node of nodeMap.values()) {
    if (node.children?.some((child) => child.id === nodeId)) {
      return node
    }
  }
  return null
}
 
/**
 * 判断一条消息是否应该显示「重新生成」按钮。
 *
 * 规则:只有 user 消息才触发重新生成,且该 user 消息必须已经有
 * 至少一个 assistant 子消息(否则是首轮未完成状态)。
 */
export function canRegenerate(message) {
  if (message?.role !== 'user') return false
  return Array.isArray(message.children) && message.children.length > 0
}