Files
beavergram/frontend/src/lib/stores/chat-picker.svelte.ts
T

44 lines
934 B
TypeScript

import { listChats } from "$lib/api/endpoints";
import type { Chat } from "$lib/api/types";
const DEBOUNCE_MS = 250;
const LIMIT = 40;
export function createChatPicker() {
let results = $state<Chat[]>([]);
let timer: ReturnType<typeof setTimeout> | null = null;
let seq = 0;
async function run(query: string, current: number) {
try {
const found = await listChats({
limit: LIMIT,
search: query || undefined,
});
if (current === seq) {
results = found;
}
} catch {
if (current === seq) {
results = [];
}
}
}
return {
get results(): Chat[] {
return results;
},
search(query: string) {
seq += 1;
const current = seq;
if (timer !== null) {
clearTimeout(timer);
}
timer = setTimeout(() => {
run(query.trim(), current).catch(() => undefined);
}, DEBOUNCE_MS);
},
};
}