This commit is contained in:
Timothy Jaeryang Baek committed 2026-07-16 02:49:21 -04:00
1 parent 2e857a82d7
commit d7f33996ee
11 files changed
+10 -10

No files matched your search

+101
View File
@@ -0,0 +1,101 @@
import { get, readonly, writable } from 'svelte/store';
import { getChatList, getPinnedChatList } from '$lib/apis/chats';
type ChatListItem = {
id: string;
[key: string]: any;
};
const chatsStore = writable<ChatListItem[] | null>(null);
const pinnedChatsStore = writable<ChatListItem[]>([]);
export const chats = readonly(chatsStore);
export const pinnedChats = readonly(pinnedChatsStore);
let currentPage = 1;
let paginationReady = false;
let requestGeneration = 0;
let allLoaded = false;
let loadingNextPage = false;
type RefreshChatListOptions = {
refreshPinned?: boolean;
clearPinned?: boolean;
};
type ChatListResult = {
accepted: boolean;
allLoaded: boolean;
};
export const refreshChatList = async (
token: string = '',
options: RefreshChatListOptions = {}
): Promise<ChatListResult> => {
const generation = ++requestGeneration;
paginationReady = false;
loadingNextPage = false;
const [nextChats, nextPinnedChats] = await Promise.all([
getChatList(token, 1) as Promise<ChatListItem[]>,
options.refreshPinned && !options.clearPinned
? (getPinnedChatList(token) as Promise<ChatListItem[]>)
: Promise.resolve(undefined as ChatListItem[] | undefined)
]);
if (generation !== requestGeneration) {
return { accepted: false, allLoaded };
}
chatsStore.set(nextChats);
currentPage = 1;
allLoaded = nextChats.length === 0;
if (options.clearPinned) {
pinnedChatsStore.set([]);
} else if (options.refreshPinned) {
pinnedChatsStore.set(nextPinnedChats ?? []);
}
paginationReady = true;
return { accepted: true, allLoaded };
};
export const loadNextChatListPage = async (token: string = ''): Promise<ChatListResult> => {
if (!paginationReady || allLoaded || loadingNextPage) {
return { accepted: false, allLoaded };
}
const generation = requestGeneration;
const nextPage = currentPage + 1;
loadingNextPage = true;
try {
const nextChats = (await getChatList(token, nextPage)) as ChatListItem[];
if (generation !== requestGeneration) {
return { accepted: false, allLoaded };
}
allLoaded = nextChats.length === 0;
currentPage = nextPage;
const existingIds = new Set((get(chatsStore) ?? []).map((chat) => chat.id));
const uniqueChats = nextChats.filter((chat) => !existingIds.has(chat.id));
chatsStore.set([...(get(chatsStore) ?? []), ...uniqueChats]);
return { accepted: true, allLoaded };
} finally {
loadingNextPage = false;
}
};
export const resetChatListState = () => {
requestGeneration += 1;
currentPage = 1;
paginationReady = false;
allLoaded = false;
loadingNextPage = false;
chatsStore.set(null);
pinnedChatsStore.set([]);
};