-
-
Notifications
You must be signed in to change notification settings - Fork 11.3k
/
Copy pathtopic.ts
86 lines (67 loc) · 2.33 KB
/
topic.ts
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
import dayjs from 'dayjs';
import isToday from 'dayjs/plugin/isToday';
import isYesterday from 'dayjs/plugin/isYesterday';
import { ChatTopic, GroupedTopic, TimeGroupId } from '@/types/topic';
// 初始化 dayjs 插件
dayjs.extend(isToday);
dayjs.extend(isYesterday);
const getTopicGroupId = (timestamp: number): TimeGroupId => {
const date = dayjs(timestamp);
const now = dayjs();
if (date.isToday()) {
return 'today';
}
if (date.isYesterday()) {
return 'yesterday';
}
// 7天内(不包括今天和昨天)
const weekAgo = now.subtract(7, 'day');
if (date.isAfter(weekAgo) && !date.isToday() && !date.isYesterday()) {
return 'week';
}
// 当前月份(不包括前面已经分组的日期)
// 使用原生的月份和年份比较
if (date.month() === now.month() && date.year() === now.year()) {
return 'month';
}
// 当年的其他月份
if (date.year() === now.year()) {
return `${date.year()}-${(date.month() + 1).toString().padStart(2, '0')}`;
}
// 更早的年份
return `${date.year()}`;
};
// 确保分组的排序
const sortGroups = (groups: GroupedTopic[]): GroupedTopic[] => {
const orderMap = new Map<string, number>();
// 设置固定分组的顺序
orderMap.set('today', 0);
orderMap.set('yesterday', 1);
orderMap.set('week', 2);
orderMap.set('month', 3);
return groups.sort((a, b) => {
const orderA = orderMap.get(a.id) ?? Number.MAX_SAFE_INTEGER;
const orderB = orderMap.get(b.id) ?? Number.MAX_SAFE_INTEGER;
if (orderA !== Number.MAX_SAFE_INTEGER || orderB !== Number.MAX_SAFE_INTEGER) {
return orderA - orderB;
}
// 对于年月格式和年份格式的分组,按时间倒序排序
return b.id.localeCompare(a.id);
});
};
// 时间分组的具体实现
export const groupTopicsByTime = (topics: ChatTopic[]): GroupedTopic[] => {
if (!topics.length) return [];
const sortedTopics = [...topics].sort((a, b) => b.createdAt - a.createdAt);
const groupsMap = new Map<TimeGroupId, ChatTopic[]>();
sortedTopics.forEach((topic) => {
const groupId = getTopicGroupId(topic.createdAt);
const existingGroup = groupsMap.get(groupId) || [];
groupsMap.set(groupId, [...existingGroup, topic]);
});
const result = Array.from(groupsMap.entries()).map(([id, children]) => ({
children,
id,
}));
return sortGroups(result);
};