Skip to content

Commit 409fb39

Browse files
committed
refac
1 parent 86efecd commit 409fb39

9 files changed

Lines changed: 374 additions & 98 deletions

File tree

backend/open_webui/models/chats.py

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1722,17 +1722,21 @@ async def get_all_chats_by_folder_id(
17221722
folder_id: str,
17231723
skip: int = 0,
17241724
limit: int = 60,
1725+
sort_by: str = 'updated_at',
1726+
sort_dir: str = 'desc',
17251727
db: AsyncSession | None = None,
17261728
) -> list[dict]:
17271729
"""Get chats in a folder across ALL users. Returns dicts with user_id."""
17281730
async with get_async_db_context(db) as session:
1731+
sort_column = Chat.title if sort_by == 'title' else Chat.updated_at
1732+
order_clause = sort_column.asc() if sort_dir == 'asc' else sort_column.desc()
17291733
stmt = (
17301734
select(Chat.id, Chat.title, Chat.user_id, Chat.updated_at, Chat.created_at, Chat.last_read_at)
17311735
.filter_by(folder_id=folder_id)
17321736
.filter(or_(Chat.pinned == False, Chat.pinned == None))
17331737
.filter_by(archived=False)
17341738
.where(Chat.meta['internal'].as_boolean().is_not(True))
1735-
.order_by(Chat.updated_at.desc(), Chat.id)
1739+
.order_by(order_clause, Chat.id)
17361740
)
17371741

17381742
if skip:
@@ -1754,6 +1758,22 @@ async def get_all_chats_by_folder_id(
17541758
for chat in all_chats
17551759
]
17561760

1761+
async def count_all_chats_by_folder_id(
1762+
self,
1763+
folder_id: str,
1764+
db: AsyncSession | None = None,
1765+
) -> int:
1766+
async with get_async_db_context(db) as session:
1767+
stmt = (
1768+
select(func.count(Chat.id))
1769+
.filter_by(folder_id=folder_id)
1770+
.filter(or_(Chat.pinned == False, Chat.pinned == None))
1771+
.filter_by(archived=False)
1772+
.where(Chat.meta['internal'].as_boolean().is_not(True))
1773+
)
1774+
result = await session.execute(stmt)
1775+
return result.scalar_one()
1776+
17571777
async def get_chats_by_folder_ids_and_user_id(
17581778
self, folder_ids: list[str], user_id: str, db: AsyncSession | None = None
17591779
) -> list[ChatModel]:

backend/open_webui/routers/folders.py

Lines changed: 19 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
from pathlib import Path
77
from typing import Optional
88

9-
from fastapi import APIRouter, Depends, File, HTTPException, Request, UploadFile, status
9+
from fastapi import APIRouter, Depends, File, HTTPException, Query, Request, UploadFile, status
1010
from fastapi.responses import FileResponse, StreamingResponse
1111
from open_webui.config import UPLOAD_DIR
1212
from open_webui.constants import ERROR_MESSAGES
@@ -482,6 +482,9 @@ async def update_folder_access_by_id(
482482
async def get_shared_folder_chats(
483483
request: Request,
484484
id: str,
485+
page: int | None = Query(None, ge=1),
486+
sort_by: str = Query('updated_at'),
487+
sort_dir: str = Query('desc'),
485488
user=Depends(get_verified_user),
486489
db: AsyncSession = Depends(get_async_session),
487490
):
@@ -505,7 +508,17 @@ async def get_shared_folder_chats(
505508
detail=ERROR_MESSAGES.ACCESS_PROHIBITED,
506509
)
507510

508-
chats = await Chats.get_all_chats_by_folder_id(id, db=db)
511+
limit = 10
512+
skip = (page - 1) * limit if page is not None else 0
513+
chats = await Chats.get_all_chats_by_folder_id(
514+
id,
515+
skip=skip,
516+
limit=limit if page is not None else 60,
517+
sort_by=sort_by,
518+
sort_dir=sort_dir,
519+
db=db,
520+
)
521+
total = await Chats.count_all_chats_by_folder_id(id, db=db) if page is not None else len(chats)
509522

510523
# Resolve owner names for display (avatar URLs are constructed client-side)
511524
owner_cache: dict[str, str] = {}
@@ -516,10 +529,13 @@ async def get_shared_folder_chats(
516529
owner_cache[uid] = u.name if u else 'Unknown'
517530
chat['owner_name'] = owner_cache[uid]
518531

519-
return {
532+
response = {
520533
'chats': [{**chat, 'readonly': chat['user_id'] != user.id} for chat in chats],
521534
'folder_permission': 'write' if has_write else 'read',
522535
}
536+
if page is not None:
537+
response.update({'total': total, 'has_more': skip + limit < total})
538+
return response
523539

524540

525541
############################

src/lib/apis/folders/index.ts

Lines changed: 31 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -290,17 +290,40 @@ export const getSharedFolders = async (token: string) => {
290290
return res;
291291
};
292292

293-
export const getSharedFolderChats = async (token: string, folderId: string) => {
293+
export const getSharedFolderChats = async (
294+
token: string,
295+
folderId: string,
296+
params: {
297+
page?: number | null;
298+
sortBy?: 'title' | 'updated_at';
299+
sortDir?: 'asc' | 'desc';
300+
} = {}
301+
) => {
294302
let error = null;
295303

296-
const res = await fetch(`${WEBUI_API_BASE_URL}/folders/${folderId}/shared/chats`, {
297-
method: 'GET',
298-
headers: {
299-
Accept: 'application/json',
300-
'Content-Type': 'application/json',
301-
authorization: `Bearer ${token}`
304+
const searchParams = new URLSearchParams();
305+
if (params.page !== undefined && params.page !== null) {
306+
searchParams.append('page', `${params.page}`);
307+
}
308+
if (params.sortBy) {
309+
searchParams.append('sort_by', params.sortBy);
310+
}
311+
if (params.sortDir) {
312+
searchParams.append('sort_dir', params.sortDir);
313+
}
314+
const query = searchParams.toString();
315+
316+
const res = await fetch(
317+
`${WEBUI_API_BASE_URL}/folders/${folderId}/shared/chats${query ? `?${query}` : ''}`,
318+
{
319+
method: 'GET',
320+
headers: {
321+
Accept: 'application/json',
322+
'Content-Type': 'application/json',
323+
authorization: `Bearer ${token}`
324+
}
302325
}
303-
})
326+
)
304327
.then(async (res) => {
305328
if (!res.ok) throw await res.json();
306329
return res.json();

src/lib/components/chat/Chat.svelte

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1177,7 +1177,7 @@
11771177
}
11781178
11791179
const pageSubscribe = page.subscribe(async (p) => {
1180-
if (p.url.pathname === '/') {
1180+
if (p.url.pathname === '/' || p.url.pathname.startsWith('/folders/')) {
11811181
await tick();
11821182
initNewChat();
11831183
}

src/lib/components/chat/Placeholder/ChatList.svelte

Lines changed: 87 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -1,27 +1,35 @@
11
<script lang="ts">
2-
import { getContext, onMount } from 'svelte';
3-
const i18n = getContext('i18n');
2+
import { getContext } from 'svelte';
3+
import type { Writable } from 'svelte/store';
4+
5+
const i18n: Writable<any> = getContext('i18n');
46
57
import dayjs from 'dayjs';
68
import localizedFormat from 'dayjs/plugin/localizedFormat';
79
import { getTimeRange } from '$lib/utils';
810
import ChevronUp from '$lib/components/icons/ChevronUp.svelte';
911
import ChevronDown from '$lib/components/icons/ChevronDown.svelte';
10-
import Loader from '$lib/components/common/Loader.svelte';
11-
import Spinner from '$lib/components/common/Spinner.svelte';
12+
import ChevronLeft from '$lib/components/icons/ChevronLeft.svelte';
13+
import ChevronRight from '$lib/components/icons/ChevronRight.svelte';
1214
import Tooltip from '$lib/components/common/Tooltip.svelte';
1315
1416
dayjs.extend(localizedFormat);
1517
16-
export let chats = [];
18+
export let chats: any[] = [];
1719
1820
export let chatListLoading = false;
19-
export let allChatsLoaded = false;
20-
21-
export let loadHandler: Function = null;
2221
export let showOwnerInfo = false;
23-
24-
let chatList = null;
22+
export let page = 1;
23+
export let total = 0;
24+
export let perPage = 10;
25+
export let orderBy: 'title' | 'updated_at' = 'updated_at';
26+
export let direction: 'asc' | 'desc' = 'desc';
27+
export let onPageChange: Function = () => {};
28+
export let onSort: Function = () => {};
29+
30+
let chatList: any[] | null = null;
31+
let totalPages = 1;
32+
let pages: (number | 'ellipsis')[] = [];
2533
2634
const init = async () => {
2735
if (chats.length === 0) {
@@ -31,34 +39,43 @@
3139
...chat,
3240
time_range: getTimeRange(chat.updated_at)
3341
}));
34-
35-
chatList.sort((a, b) => {
36-
if (direction === 'asc') {
37-
return a[orderBy] > b[orderBy] ? 1 : -1;
38-
} else {
39-
return a[orderBy] < b[orderBy] ? 1 : -1;
40-
}
41-
});
4242
}
4343
};
4444
45-
const setSortKey = (key) => {
46-
if (orderBy === key) {
47-
direction = direction === 'asc' ? 'desc' : 'asc';
48-
} else {
49-
orderBy = key;
50-
direction = 'asc';
45+
const setSortKey = (key: 'title' | 'updated_at') => {
46+
onSort(key);
47+
};
48+
49+
const buildPages = (currentPage: number, pageCount: number): (number | 'ellipsis')[] => {
50+
if (pageCount <= 7) {
51+
return Array.from({ length: pageCount }, (_, i) => i + 1);
5152
}
5253
53-
init();
54-
};
54+
const items: (number | 'ellipsis')[] = [1];
55+
if (currentPage > 3) {
56+
items.push('ellipsis');
57+
}
5558
56-
let orderBy = 'updated_at';
57-
let direction = 'desc'; // 'asc' or 'desc'
59+
const start = Math.max(2, currentPage - 1);
60+
const end = Math.min(pageCount - 1, currentPage + 1);
61+
for (let i = start; i <= end; i++) {
62+
items.push(i);
63+
}
64+
65+
if (currentPage < pageCount - 2) {
66+
items.push('ellipsis');
67+
}
68+
items.push(pageCount);
69+
70+
return items;
71+
};
5872
5973
$: if (chats) {
6074
init();
6175
}
76+
77+
$: totalPages = Math.max(1, Math.ceil(total / perPage));
78+
$: pages = buildPages(page, totalPages);
6279
</script>
6380

6481
{#if chatList}
@@ -153,7 +170,6 @@
153170
class=" w-full flex justify-between items-center rounded-lg text-sm py-2 px-3 hover:bg-gray-50 dark:hover:bg-gray-850"
154171
draggable="false"
155172
href={`/c/${chat.id}`}
156-
on:click={() => (show = false)}
157173
>
158174
<div class="text-ellipsis line-clamp-1 w-full sm:basis-3/5">
159175
{chat?.title}
@@ -177,19 +193,48 @@
177193
</a>
178194
{/each}
179195

180-
{#if !allChatsLoaded && loadHandler}
181-
<Loader
182-
on:visible={(e) => {
183-
if (!chatListLoading) {
184-
loadHandler();
185-
}
186-
}}
187-
>
188-
<div class="w-full flex justify-center py-1 text-xs animate-pulse items-center gap-2">
189-
<Spinner className=" size-4" />
190-
<div class=" ">Loading...</div>
191-
</div>
192-
</Loader>
196+
{#if totalPages > 1}
197+
<div class="flex items-center justify-center gap-1.5 pt-2">
198+
<button
199+
class="inline-flex size-7 items-center justify-center rounded-lg text-xs font-medium text-gray-500 transition hover:bg-gray-50 hover:text-gray-700 disabled:cursor-not-allowed disabled:opacity-25 dark:text-gray-500 dark:hover:bg-gray-850 dark:hover:text-gray-300"
200+
disabled={chatListLoading || page <= 1}
201+
aria-label={$i18n.t('Previous page')}
202+
on:click={() => onPageChange(page - 1)}
203+
>
204+
<ChevronLeft className="size-3.5" strokeWidth="2" />
205+
</button>
206+
207+
{#each pages as item, index (item === 'ellipsis' ? `ellipsis-${index}` : item)}
208+
{#if item === 'ellipsis'}
209+
<span
210+
class="inline-flex size-7 items-center justify-center text-xs text-gray-400 select-none dark:text-gray-600"
211+
>
212+
...
213+
</span>
214+
{:else}
215+
<button
216+
class="inline-flex size-7 items-center justify-center rounded-lg text-xs font-medium transition hover:bg-gray-50 hover:text-gray-700 dark:hover:bg-gray-850 dark:hover:text-gray-300 {item ===
217+
page
218+
? 'bg-gray-50 text-gray-800 dark:bg-gray-850 dark:text-gray-100'
219+
: 'text-gray-500 dark:text-gray-500'}"
220+
aria-label={`Page ${item}`}
221+
aria-current={item === page ? 'page' : undefined}
222+
on:click={() => onPageChange(item)}
223+
>
224+
{item}
225+
</button>
226+
{/if}
227+
{/each}
228+
229+
<button
230+
class="inline-flex size-7 items-center justify-center rounded-lg text-xs font-medium text-gray-500 transition hover:bg-gray-50 hover:text-gray-700 disabled:cursor-not-allowed disabled:opacity-25 dark:text-gray-500 dark:hover:bg-gray-850 dark:hover:text-gray-300"
231+
disabled={chatListLoading || page >= totalPages}
232+
aria-label={$i18n.t('Next page')}
233+
on:click={() => onPageChange(page + 1)}
234+
>
235+
<ChevronRight className="size-3.5" strokeWidth="2" />
236+
</button>
237+
</div>
193238
{/if}
194239
</div>
195240
{/if}

0 commit comments

Comments
 (0)