import { daysAgo, parseTime } from './chatTime'
|
|
/**
|
* 把会话列表编排成侧边栏要显示的结构。
|
*
|
* 三条规则,顺序也是优先级:
|
*
|
* 1. **置顶且未分组** → 进「置顶」区(固定在列表最上方)
|
* 2. **有分组** → 进它自己的分组(哪怕它还置顶着 —— 用户既然把它
|
* 放进了文件夹,就不该再把它从文件夹里抽走;
|
* 置顶在这里体现为「排在该分组最前 + 带图钉」)
|
* 3. **其余** → 按今天 / 昨天 / 更早自动归类
|
*
|
* 也就是说自定义分组与时间分组是**互斥**的:进了文件夹就不再出现在
|
* 时间分组里,避免同一条对话在侧边栏出现两次(点哪个都会打开同一条,
|
* 但用户会以为有两份)。
|
*
|
* 组内顺序直接沿用后端返回的顺序(后端已按 pinned / pinned_at / updated_at
|
* 排好),这里只做分桶,不重排 —— 否则「前端排一遍、后端排一遍」
|
* 迟早会出现两边不一致,刷新一次顺序又跳回去。
|
*
|
* @param {Array} chats 后端返回的会话列表(已排序)
|
* @param {Array} groups 后端返回的分组列表(已按创建顺序)
|
* @param {Date} now 注入当前时间,便于测试
|
*/
|
export function buildSidebarSections(chats, groups, now = new Date()) {
|
const list = Array.isArray(chats) ? chats : []
|
const groupList = Array.isArray(groups) ? groups : []
|
|
const pinned = []
|
const buckets = new Map()
|
const today = []
|
const yesterday = []
|
const earlier = []
|
|
for (const group of groupList) {
|
buckets.set(group.id, [])
|
}
|
|
for (const chat of list) {
|
// 分组可能已被删除而会话还残留 group_id(并发/异常数据):
|
// 这时按「未分组」处理,宁可让它落到时间分组里,也不要它凭空消失
|
const bucket = chat.groupId != null ? buckets.get(chat.groupId) : undefined
|
|
if (bucket) {
|
bucket.push(chat)
|
continue
|
}
|
if (chat.pinned) {
|
pinned.push(chat)
|
continue
|
}
|
|
const ago = daysAgo(parseTime(chat.updatedAt || chat.createdAt), now)
|
if (ago <= 0) today.push(chat)
|
else if (ago === 1) yesterday.push(chat)
|
else earlier.push(chat)
|
}
|
|
const timeGroups = []
|
if (today.length) timeGroups.push({ key: 'today', label: '今天', chats: today })
|
if (yesterday.length) timeGroups.push({ key: 'yesterday', label: '昨天', chats: yesterday })
|
if (earlier.length) timeGroups.push({ key: 'earlier', label: '更早', chats: earlier })
|
|
return {
|
pinned,
|
// 空分组也要保留:用户刚建好还没放东西的文件夹应该看得见,
|
// 否则「我明明建了分组,怎么没了」
|
groups: groupList.map((group) => ({
|
id: group.id,
|
name: group.name,
|
chats: buckets.get(group.id) || []
|
})),
|
timeGroups
|
}
|
}
|