Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

✨ feat(topic): add sort by updated time option for topic sidebar (#12774)

YuTengjing32b83b8c0ae6
diff --git a/locales/en-US/topic.json b/locales/en-US/topic.json
index 42e625a5b0d..f3c9c113334 100644
--- a/locales/en-US/topic.json
+++ b/locales/en-US/topic.json
@@ -17,7 +17,8 @@
"duplicateSuccess": "Topic Copied Successfully",
"favorite": "Favorite",
"groupMode.ascMessages": "Sort by Total Messages Ascending",
- "groupMode.byTime": "Group by Time",
+ "groupMode.byTime": "Group by Created Time",
+ "groupMode.byUpdatedTime": "Group by Updated Time",
"groupMode.descMessages": "Sort by Total Messages Descending",
"groupMode.flat": "No Grouping",
"groupTitle.byTime.month": "This Month",
diff --git a/locales/zh-CN/topic.json b/locales/zh-CN/topic.json
index 2f1a72f2da9..a792be3722d 100644
--- a/locales/zh-CN/topic.json
+++ b/locales/zh-CN/topic.json
@@ -17,7 +17,8 @@
"duplicateSuccess": "话题复制成功",
"favorite": "收藏",
"groupMode.ascMessages": "按消息总数顺序",
- "groupMode.byTime": "按时间分组",
+ "groupMode.byTime": "按创建时间分组",
+ "groupMode.byUpdatedTime": "按编辑时间分组",
"groupMode.descMessages": "按消息总数倒序",
"groupMode.flat": "不分组",
"groupTitle.byTime.month": "本月",
diff --git a/packages/const/src/user.ts b/packages/const/src/user.ts
index b83e670b557..3be643aaa1a 100644
--- a/packages/const/src/user.ts
+++ b/packages/const/src/user.ts
@@ -16,6 +16,6 @@ export const DEFAULT_PREFERENCE: UserPreference = {
lab: {
enableInputMarkdown: true,
},
- topicDisplayMode: TopicDisplayMode.ByTime,
+ topicDisplayMode: TopicDisplayMode.ByCreatedTime,
useCmdEnterToSend: false,
};
diff --git a/packages/database/src/models/message.ts b/packages/database/src/models/message.ts
index 130e744741f..0bae4963cbc 100644
--- a/packages/database/src/models/message.ts
+++ b/packages/database/src/models/message.ts
@@ -62,8 +62,9 @@ import {
messageTranslates,
messageTTS,
threads,
+ topics,
} from '../schemas';
-import type { LobeChatDatabase } from '../type';
+import type { LobeChatDatabase, Transaction } from '../type';
import { genEndDateWhere, genRangeWhere, genStartDateWhere, genWhere } from '../utils/genWhere';
import { idGenerator } from '../utils/idGenerator';
@@ -102,6 +103,17 @@ export class MessageModel {
this.db = db;
}
+ /**
+ * Touch topics' updatedAt timestamp within a transaction
+ */
+ private async touchTopicUpdatedAt(trx: Transaction, topicIds: string[]) {
+ if (topicIds.length === 0) return;
+ await trx
+ .update(topics)
+ .set({ updatedAt: new Date() })
+ .where(and(inArray(topics.id, topicIds), eq(topics.userId, this.userId)));
+ }
+
// **************** Query *************** //
/**
@@ -1287,6 +1299,11 @@ export class MessageModel {
);
}
+ // Touch topic's updatedAt when creating a message in a topic
+ if (message.topicId) {
+ await this.touchTopicUpdatedAt(trx, [message.topicId]);
+ }
+
return item;
});
};
@@ -1297,7 +1314,15 @@ export class MessageModel {
return { ...m, role: m.role as any, userId: this.userId };
});
- return this.db.insert(messages).values(messagesToInsert);
+ const topicIds = [...new Set(newMessages.map((m) => m.topicId).filter(Boolean))] as string[];
+
+ return this.db.transaction(async (trx) => {
+ const result = await trx.insert(messages).values(messagesToInsert);
+
+ await this.touchTopicUpdatedAt(trx, topicIds);
+
+ return result;
+ });
};
createMessageQuery = async (params: NewMessageQueryParams) => {
@@ -1335,10 +1360,16 @@ export class MessageModel {
mergedMetadata = merge(existingMessage?.metadata || {}, metadata);
}
- await trx
+ const [updated] = await trx
.update(messages)
.set({ ...message, ...(mergedMetadata && { metadata: mergedMetadata }) })
- .where(and(eq(messages.id, id), eq(messages.userId, this.userId)));
+ .where(and(eq(messages.id, id), eq(messages.userId, this.userId)))
+ .returning({ topicId: messages.topicId });
+
+ // Touch topic's updatedAt when updating a message
+ if (updated?.topicId) {
+ await this.touchTopicUpdatedAt(trx, [updated.topicId]);
+ }
});
return { success: true };
diff --git a/packages/types/src/topic/topic.ts b/packages/types/src/topic/topic.ts
index 9198565c8a2..add457b4e01 100644
--- a/packages/types/src/topic/topic.ts
+++ b/packages/types/src/topic/topic.ts
@@ -12,7 +12,8 @@ export type TimeGroupId =
| `${number}`;
export enum TopicDisplayMode {
- ByTime = 'byTime',
+ ByCreatedTime = 'byTime',
+ ByUpdatedTime = 'byUpdatedTime',
Flat = 'flat',
// AscMessages = 'ascMessages',
// DescMessages = 'descMessages',
diff --git a/packages/utils/src/client/topic.ts b/packages/utils/src/client/topic.ts
index cb0a0d18084..a039cff840a 100644
--- a/packages/utils/src/client/topic.ts
+++ b/packages/utils/src/client/topic.ts
@@ -64,18 +64,25 @@ const sortGroups = (groups: GroupedTopic[]): GroupedTopic[] => {
});
};
-// Specific implementation of time grouping
-export const groupTopicsByTime = (topics: ChatTopic[]): GroupedTopic[] => {
+// Generic time-based grouping parameterized by field
+const groupTopicsByField = (
+ topics: ChatTopic[],
+ field: 'createdAt' | 'updatedAt',
+): GroupedTopic[] => {
if (!topics.length) return [];
- const sortedTopics = [...topics].sort((a, b) => b.createdAt - a.createdAt);
+ const sortedTopics = [...topics].sort((a, b) => b[field] - a[field]);
const groupsMap = new Map<TimeGroupId, ChatTopic[]>();
- sortedTopics.forEach((topic) => {
- const groupId = getTopicGroupId(topic.createdAt);
- const existingGroup = groupsMap.get(groupId) || [];
- groupsMap.set(groupId, [...existingGroup, topic]);
- });
+ for (const topic of sortedTopics) {
+ const groupId = getTopicGroupId(topic[field]);
+ const existing = groupsMap.get(groupId);
+ if (existing) {
+ existing.push(topic);
+ } else {
+ groupsMap.set(groupId, [topic]);
+ }
+ }
const result = Array.from(groupsMap.entries()).map(([id, children]) => ({
children,
@@ -84,3 +91,7 @@ export const groupTopicsByTime = (topics: ChatTopic[]): GroupedTopic[] => {
return sortGroups(result);
};
+
+export const groupTopicsByTime = (topics: ChatTopic[]) => groupTopicsByField(topics, 'createdAt');
+export const groupTopicsByUpdatedTime = (topics: ChatTopic[]) =>
+ groupTopicsByField(topics, 'updatedAt');
diff --git a/src/locales/default/topic.ts b/src/locales/default/topic.ts
index 5be2d1d4858..0e643297e00 100644
--- a/src/locales/default/topic.ts
+++ b/src/locales/default/topic.ts
@@ -18,7 +18,8 @@ export default {
'duplicateSuccess': 'Topic Copied Successfully',
'favorite': 'Favorite',
'groupMode.ascMessages': 'Sort by Total Messages Ascending',
- 'groupMode.byTime': 'Group by Time',
+ 'groupMode.byTime': 'Group by Created Time',
+ 'groupMode.byUpdatedTime': 'Group by Updated Time',
'groupMode.descMessages': 'Sort by Total Messages Descending',
'groupMode.flat': 'No Grouping',
'groupTitle.byTime.month': 'This Month',
diff --git a/src/routes/(main)/agent/_layout/Sidebar/Topic/List/index.tsx b/src/routes/(main)/agent/_layout/Sidebar/Topic/List/index.tsx
index 2c757ee0539..a979968cdaa 100644
--- a/src/routes/(main)/agent/_layout/Sidebar/Topic/List/index.tsx
+++ b/src/routes/(main)/agent/_layout/Sidebar/Topic/List/index.tsx
@@ -49,7 +49,7 @@ const TopicList = memo(() => {
}}
/>
)}
- {topicDisplayMode === TopicDisplayMode.ByTime ? <ByTimeMode /> : <FlatMode />}
+ {topicDisplayMode === TopicDisplayMode.Flat ? <FlatMode /> : <ByTimeMode />}
<AllTopicsDrawer open={allTopicsDrawerOpen} onClose={closeAllTopicsDrawer} />
</>
);
diff --git a/src/routes/(main)/agent/_layout/Sidebar/Topic/TopicListContent/ByTimeMode/index.tsx b/src/routes/(main)/agent/_layout/Sidebar/Topic/TopicListContent/ByTimeMode/index.tsx
index 914ca93f868..a893c7f1def 100644
--- a/src/routes/(main)/agent/_layout/Sidebar/Topic/TopicListContent/ByTimeMode/index.tsx
+++ b/src/routes/(main)/agent/_layout/Sidebar/Topic/TopicListContent/ByTimeMode/index.tsx
@@ -3,7 +3,7 @@
import { Accordion, Flexbox } from '@lobehub/ui';
import isEqual from 'fast-deep-equal';
import { MoreHorizontal } from 'lucide-react';
-import React, { memo, useMemo } from 'react';
+import { memo, useEffect, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import NavItem from '@/features/NavPanel/components/NavItem';
@@ -12,12 +12,15 @@ import { useChatStore } from '@/store/chat';
import { topicSelectors } from '@/store/chat/selectors';
import { useGlobalStore } from '@/store/global';
import { systemStatusSelectors } from '@/store/global/selectors';
+import { useUserStore } from '@/store/user';
+import { preferenceSelectors } from '@/store/user/selectors';
import GroupItem from './GroupItem';
const ByTimeMode = memo(() => {
const { t } = useTranslation('topic');
const topicPageSize = useGlobalStore(systemStatusSelectors.topicPageSize);
+ const topicDisplayMode = useUserStore(preferenceSelectors.topicDisplayMode);
const [hasMore, isExpandingPageSize, openAllTopicsDrawer] = useChatStore((s) => [
topicSelectors.hasMoreTopics(s),
@@ -25,13 +28,23 @@ const ByTimeMode = memo(() => {
s.openAllTopicsDrawer,
]);
const [activeTopicId, activeThreadId] = useChatStore((s) => [s.activeTopicId, s.activeThreadId]);
- const groupTopics = useChatStore(topicSelectors.groupedTopicsForSidebar(topicPageSize), isEqual);
+
+ const groupSelector = useMemo(
+ () => topicSelectors.groupedTopicsForSidebar(topicPageSize, topicDisplayMode),
+ [topicPageSize, topicDisplayMode],
+ );
+ const groupTopics = useChatStore(groupSelector, isEqual);
const [topicGroupKeys, updateSystemStatus] = useGlobalStore((s) => [
systemStatusSelectors.topicGroupKeys(s),
s.updateSystemStatus,
]);
+ // Reset expanded keys when display mode changes so all groups start expanded
+ useEffect(() => {
+ updateSystemStatus({ expandTopicGroupKeys: undefined });
+ }, [topicDisplayMode, updateSystemStatus]);
+
const expandedKeys = useMemo(() => {
return topicGroupKeys || groupTopics.map((group) => group.id);
}, [topicGroupKeys, groupTopics]);
diff --git a/src/routes/(main)/agent/_layout/Sidebar/Topic/TopicListContent/index.tsx b/src/routes/(main)/agent/_layout/Sidebar/Topic/TopicListContent/index.tsx
index 9e2be916776..a1e9172e50e 100644
--- a/src/routes/(main)/agent/_layout/Sidebar/Topic/TopicListContent/index.tsx
+++ b/src/routes/(main)/agent/_layout/Sidebar/Topic/TopicListContent/index.tsx
@@ -47,7 +47,7 @@ const TopicListContent = memo(() => {
}}
/>
)}
- {topicDisplayMode === TopicDisplayMode.ByTime ? <ByTimeMode /> : <FlatMode />}
+ {topicDisplayMode === TopicDisplayMode.Flat ? <FlatMode /> : <ByTimeMode />}
</>
);
});
diff --git a/src/routes/(main)/group/_layout/Sidebar/Topic/List/index.tsx b/src/routes/(main)/group/_layout/Sidebar/Topic/List/index.tsx
index 61b09cf519a..9a100a7656c 100644
--- a/src/routes/(main)/group/_layout/Sidebar/Topic/List/index.tsx
+++ b/src/routes/(main)/group/_layout/Sidebar/Topic/List/index.tsx
@@ -47,7 +47,7 @@ const TopicList = memo(() => {
}}
/>
)}
- {topicDisplayMode === TopicDisplayMode.ByTime ? <ByTimeMode /> : <FlatMode />}
+ {topicDisplayMode === TopicDisplayMode.Flat ? <FlatMode /> : <ByTimeMode />}
<AllTopicsDrawer open={allTopicsDrawerOpen} onClose={closeAllTopicsDrawer} />
</>
);
diff --git a/src/routes/(main)/group/_layout/Sidebar/Topic/TopicListContent/ByTimeMode/index.tsx b/src/routes/(main)/group/_layout/Sidebar/Topic/TopicListContent/ByTimeMode/index.tsx
index 914ca93f868..a893c7f1def 100644
--- a/src/routes/(main)/group/_layout/Sidebar/Topic/TopicListContent/ByTimeMode/index.tsx
+++ b/src/routes/(main)/group/_layout/Sidebar/Topic/TopicListContent/ByTimeMode/index.tsx
@@ -3,7 +3,7 @@
import { Accordion, Flexbox } from '@lobehub/ui';
import isEqual from 'fast-deep-equal';
import { MoreHorizontal } from 'lucide-react';
-import React, { memo, useMemo } from 'react';
+import { memo, useEffect, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import NavItem from '@/features/NavPanel/components/NavItem';
@@ -12,12 +12,15 @@ import { useChatStore } from '@/store/chat';
import { topicSelectors } from '@/store/chat/selectors';
import { useGlobalStore } from '@/store/global';
import { systemStatusSelectors } from '@/store/global/selectors';
+import { useUserStore } from '@/store/user';
+import { preferenceSelectors } from '@/store/user/selectors';
import GroupItem from './GroupItem';
const ByTimeMode = memo(() => {
const { t } = useTranslation('topic');
const topicPageSize = useGlobalStore(systemStatusSelectors.topicPageSize);
+ const topicDisplayMode = useUserStore(preferenceSelectors.topicDisplayMode);
const [hasMore, isExpandingPageSize, openAllTopicsDrawer] = useChatStore((s) => [
topicSelectors.hasMoreTopics(s),
@@ -25,13 +28,23 @@ const ByTimeMode = memo(() => {
s.openAllTopicsDrawer,
]);
const [activeTopicId, activeThreadId] = useChatStore((s) => [s.activeTopicId, s.activeThreadId]);
- const groupTopics = useChatStore(topicSelectors.groupedTopicsForSidebar(topicPageSize), isEqual);
+
+ const groupSelector = useMemo(
+ () => topicSelectors.groupedTopicsForSidebar(topicPageSize, topicDisplayMode),
+ [topicPageSize, topicDisplayMode],
+ );
+ const groupTopics = useChatStore(groupSelector, isEqual);
const [topicGroupKeys, updateSystemStatus] = useGlobalStore((s) => [
systemStatusSelectors.topicGroupKeys(s),
s.updateSystemStatus,
]);
+ // Reset expanded keys when display mode changes so all groups start expanded
+ useEffect(() => {
+ updateSystemStatus({ expandTopicGroupKeys: undefined });
+ }, [topicDisplayMode, updateSystemStatus]);
+
const expandedKeys = useMemo(() => {
return topicGroupKeys || groupTopics.map((group) => group.id);
}, [topicGroupKeys, groupTopics]);
diff --git a/src/routes/(main)/group/_layout/Sidebar/Topic/TopicListContent/index.tsx b/src/routes/(main)/group/_layout/Sidebar/Topic/TopicListContent/index.tsx
index fe14417ff83..404d01a1234 100644
--- a/src/routes/(main)/group/_layout/Sidebar/Topic/TopicListContent/index.tsx
+++ b/src/routes/(main)/group/_layout/Sidebar/Topic/TopicListContent/index.tsx
@@ -47,7 +47,7 @@ const TopicListContent = memo(() => {
}}
/>
)}
- {topicDisplayMode === TopicDisplayMode.ByTime ? <ByTimeMode /> : <FlatMode />}
+ {topicDisplayMode === TopicDisplayMode.Flat ? <FlatMode /> : <ByTimeMode />}
</>
);
});
diff --git a/src/store/chat/slices/aiChat/actions/__tests__/conversationLifecycle.test.ts b/src/store/chat/slices/aiChat/actions/__tests__/conversationLifecycle.test.ts
index 0e7ec79e96c..d5571009a89 100644
--- a/src/store/chat/slices/aiChat/actions/__tests__/conversationLifecycle.test.ts
+++ b/src/store/chat/slices/aiChat/actions/__tests__/conversationLifecycle.test.ts
@@ -7,7 +7,7 @@ import { messageMapKey } from '@/store/chat/utils/messageMapKey';
import { getSessionStoreState } from '@/store/session';
import { useChatStore } from '../../../../store';
-import { createMockMessage,TEST_CONTENT, TEST_IDS } from './fixtures';
+import { createMockMessage, TEST_CONTENT, TEST_IDS } from './fixtures';
import { resetTestEnvironment, setupMockSelectors, spyOnMessageService } from './helpers';
// Keep zustand mock as it's needed globally
@@ -355,6 +355,71 @@ describe('ConversationLifecycle actions', () => {
});
});
+ describe('optimistic topic updatedAt', () => {
+ it('should optimistically update topic updatedAt when sending message to existing topic', async () => {
+ const { result } = renderHook(() => useChatStore());
+ const topicId = TEST_IDS.TOPIC_ID;
+
+ const dispatchTopicSpy = vi.spyOn(result.current, 'internal_dispatchTopic');
+
+ vi.spyOn(aiChatService, 'sendMessageInServer').mockResolvedValue({
+ messages: [
+ createMockMessage({ id: TEST_IDS.USER_MESSAGE_ID, role: 'user', topicId }),
+ createMockMessage({ id: TEST_IDS.ASSISTANT_MESSAGE_ID, role: 'assistant', topicId }),
+ ],
+ assistantMessageId: TEST_IDS.ASSISTANT_MESSAGE_ID,
+ userMessageId: TEST_IDS.USER_MESSAGE_ID,
+ } as any);
+
+ await act(async () => {
+ await result.current.sendMessage({
+ message: TEST_CONTENT.USER_MESSAGE,
+ context: { agentId: TEST_IDS.SESSION_ID, topicId, threadId: null },
+ });
+ });
+
+ // Should call internal_dispatchTopic with updateTopic to touch updatedAt
+ expect(dispatchTopicSpy).toHaveBeenCalledWith(
+ expect.objectContaining({
+ type: 'updateTopic',
+ id: topicId,
+ value: { updatedAt: expect.any(Number) },
+ }),
+ );
+ });
+
+ it('should NOT optimistically update topic updatedAt when server returns topics (new topic)', async () => {
+ const { result } = renderHook(() => useChatStore());
+
+ const dispatchTopicSpy = vi.spyOn(result.current, 'internal_dispatchTopic');
+
+ vi.spyOn(aiChatService, 'sendMessageInServer').mockResolvedValue({
+ messages: [
+ createMockMessage({ id: TEST_IDS.USER_MESSAGE_ID, role: 'user' }),
+ createMockMessage({ id: TEST_IDS.ASSISTANT_MESSAGE_ID, role: 'assistant' }),
+ ],
+ topics: { items: [{ id: 'new-topic', title: 'New Topic' }], total: 1 },
+ topicId: 'new-topic',
+ isCreateNewTopic: true,
+ assistantMessageId: TEST_IDS.ASSISTANT_MESSAGE_ID,
+ userMessageId: TEST_IDS.USER_MESSAGE_ID,
+ } as any);
+
+ await act(async () => {
+ await result.current.sendMessage({
+ message: TEST_CONTENT.USER_MESSAGE,
+ context: createTestContext(),
+ });
+ });
+
+ // Should NOT call internal_dispatchTopic with updateTopic for updatedAt
+ const updateTopicCalls = dispatchTopicSpy.mock.calls.filter(
+ ([payload]) => payload.type === 'updateTopic' && 'updatedAt' in (payload.value || {}),
+ );
+ expect(updateTopicCalls).toHaveLength(0);
+ });
+ });
+
describe('new topic creation cleanup', () => {
it('should clear _new key data when new topic is created', async () => {
const { result } = renderHook(() => useChatStore());
diff --git a/src/store/chat/slices/aiChat/actions/conversationLifecycle.ts b/src/store/chat/slices/aiChat/actions/conversationLifecycle.ts
index 615f4d7dd89..e49a5ec7cd7 100644
--- a/src/store/chat/slices/aiChat/actions/conversationLifecycle.ts
+++ b/src/store/chat/slices/aiChat/actions/conversationLifecycle.ts
@@ -268,6 +268,13 @@ export class ConversationLifecycleActionImpl {
// Record the created topicId in metadata (not context)
this.#get().updateOperationMetadata(operationId, { createdTopicId: data.topicId });
+ } else if (operationContext.topicId) {
+ // Optimistically update topic's updatedAt so sidebar re-groups immediately
+ this.#get().internal_dispatchTopic({
+ type: 'updateTopic',
+ id: operationContext.topicId,
+ value: { updatedAt: Date.now() },
+ });
}
// Record created threadId in operation metadata
diff --git a/src/store/chat/slices/topic/selectors.test.ts b/src/store/chat/slices/topic/selectors.test.ts
index 3faaa675329..b4a2711c7a7 100644
--- a/src/store/chat/slices/topic/selectors.test.ts
+++ b/src/store/chat/slices/topic/selectors.test.ts
@@ -119,7 +119,7 @@ describe('topicSelectors', () => {
describe('groupedTopicsSelector', () => {
it('should return empty array if there are no topics', () => {
const state = merge(initialStore, { activeAgentId: 'test' });
- const grouped = topicSelectors.groupedTopicsSelector(state);
+ const grouped = topicSelectors.groupedTopicsSelector()(state);
expect(grouped).toEqual([]);
});
@@ -142,7 +142,7 @@ describe('topicSelectors', () => {
activeAgentId: 'test',
});
- const grouped = topicSelectors.groupedTopicsSelector(state);
+ const grouped = topicSelectors.groupedTopicsSelector()(state);
expect(grouped).toHaveLength(1); // One time-based group
expect(grouped[0].children).toEqual(topics);
});
@@ -167,7 +167,7 @@ describe('topicSelectors', () => {
activeAgentId: 'test',
});
- const grouped = topicSelectors.groupedTopicsSelector(state);
+ const grouped = topicSelectors.groupedTopicsSelector()(state);
expect(grouped).toHaveLength(2); // Favorite group + one time-based group
@@ -201,7 +201,7 @@ describe('topicSelectors', () => {
activeAgentId: 'test',
});
- const grouped = topicSelectors.groupedTopicsSelector(state);
+ const grouped = topicSelectors.groupedTopicsSelector()(state);
// Should not have a favorites group
expect(grouped.find((g) => g.id === 'favorite')).toBeUndefined();
diff --git a/src/store/chat/slices/topic/selectors.ts b/src/store/chat/slices/topic/selectors.ts
index 586d201e62a..2370fb9f1ba 100644
--- a/src/store/chat/slices/topic/selectors.ts
+++ b/src/store/chat/slices/topic/selectors.ts
@@ -1,7 +1,12 @@
import { t } from 'i18next';
-import { type ChatTopic, type ChatTopicSummary, type GroupedTopic } from '@/types/topic';
-import { groupTopicsByTime } from '@/utils/client/topic';
+import {
+ type ChatTopic,
+ type ChatTopicSummary,
+ type GroupedTopic,
+ TopicDisplayMode,
+} from '@/types/topic';
+import { groupTopicsByTime, groupTopicsByUpdatedTime } from '@/utils/client/topic';
import { type ChatStoreState } from '../../initialState';
import { topicMapKey } from '../../utils/topicMapKey';
@@ -32,9 +37,6 @@ const searchTopics = (s: ChatStoreState): ChatTopic[] => s.searchTopics;
const displayTopics = (s: ChatStoreState): ChatTopic[] | undefined => currentTopicsWithoutCron(s);
-const currentFavTopics = (s: ChatStoreState): ChatTopic[] =>
- currentTopicsWithoutCron(s)?.filter((s) => s.favorite) || [];
-
const currentUnFavTopics = (s: ChatStoreState): ChatTopic[] =>
currentTopicsWithoutCron(s)?.filter((s) => !s.favorite) || [];
@@ -93,12 +95,18 @@ const displayTopicsForSidebar =
return topics.slice(0, pageSize);
};
-const groupedTopicsSelector = (s: ChatStoreState): GroupedTopic[] => {
- const topics = displayTopics(s);
+const getGroupFn = (displayMode: TopicDisplayMode) =>
+ displayMode === TopicDisplayMode.ByUpdatedTime ? groupTopicsByUpdatedTime : groupTopicsByTime;
- if (!topics) return [];
- const favTopics = currentFavTopics(s);
- const unfavTopics = currentUnFavTopics(s);
+/**
+ * Build grouped topics from a topic list, splitting favorites into a separate group
+ */
+const buildGroupedTopics = (
+ topics: ChatTopic[],
+ groupFn: typeof groupTopicsByTime,
+): GroupedTopic[] => {
+ const favTopics = topics.filter((topic) => topic.favorite);
+ const unfavTopics = topics.filter((topic) => !topic.favorite);
return favTopics.length > 0
? [
@@ -107,31 +115,25 @@ const groupedTopicsSelector = (s: ChatStoreState): GroupedTopic[] => {
id: 'favorite',
title: t('favorite', { ns: 'topic' }),
},
- ...groupTopicsByTime(unfavTopics),
+ ...groupFn(unfavTopics),
]
- : groupTopicsByTime(topics);
+ : groupFn(topics);
};
-// Limit grouped topics for sidebar
+const groupedTopicsSelector =
+ (groupFn: typeof groupTopicsByTime = groupTopicsByTime) =>
+ (s: ChatStoreState): GroupedTopic[] => {
+ const topics = displayTopics(s);
+ if (!topics) return [];
+ return buildGroupedTopics(topics, groupFn);
+ };
+
const groupedTopicsForSidebar =
- (pageSize: number) =>
+ (pageSize: number, displayMode: TopicDisplayMode = TopicDisplayMode.ByCreatedTime) =>
(s: ChatStoreState): GroupedTopic[] => {
const limitedTopics = displayTopicsForSidebar(pageSize)(s);
if (!limitedTopics) return [];
-
- const favTopics = limitedTopics.filter((t) => t.favorite);
- const unfavTopics = limitedTopics.filter((t) => !t.favorite);
-
- return favTopics.length > 0
- ? [
- {
- children: favTopics,
- id: 'favorite',
- title: t('favorite', { ns: 'topic' }),
- },
- ...groupTopicsByTime(unfavTopics),
- ]
- : groupTopicsByTime(limitedTopics);
+ return buildGroupedTopics(limitedTopics, getGroupFn(displayMode));
};
const hasMoreTopics = (s: ChatStoreState): boolean => currentTopicData(s)?.hasMore ?? false;