mirror of
https://github.com/chenyme/grok2api.git
synced 2026-12-05 08:01:07 +00:00
refactor: standardize pagination and batch ID normalization across services
This commit is contained in:
1 parent
6d3b43b8a9
commit
d10d6496da
21 files changed
+234
-146
No files matched your search
@@ -440,7 +440,7 @@ func oneOf(value string, allowed ...string) bool {
|
||||
return false
|
||||
}
|
||||
|
||||
// BatchUpdate 对一组账号应用同一组路由参数,单次最多处理 500 个账号。
|
||||
// BatchUpdate 对一组账号应用同一组路由参数,单次最多处理一个管理端最大分页。
|
||||
func (s *Service) BatchUpdate(ctx context.Context, ids []uint64, input UpdateInput) (int64, error) {
|
||||
ids, err := normalizeBatchIDs(ids)
|
||||
if err != nil {
|
||||
@@ -2539,20 +2539,11 @@ func (s *Service) credentialFromSeed(seed provider.CredentialSeed) (accountdomai
|
||||
}
|
||||
|
||||
func normalizePage(page, pageSize int) (int, int) {
|
||||
if page < 1 {
|
||||
page = 1
|
||||
}
|
||||
if pageSize < 1 {
|
||||
pageSize = 20
|
||||
}
|
||||
if pageSize > 100 {
|
||||
pageSize = 100
|
||||
}
|
||||
return page, pageSize
|
||||
return repository.NormalizePage(page, pageSize, repository.DefaultPageSize)
|
||||
}
|
||||
|
||||
func normalizeBatchIDs(ids []uint64) ([]uint64, error) {
|
||||
return normalizeIDs(ids, 500)
|
||||
return normalizeIDs(ids, repository.MaxPageSize)
|
||||
}
|
||||
|
||||
func normalizeIDs(ids []uint64, limit int) ([]uint64, error) {
|
||||
|
||||
@@ -166,15 +166,7 @@ func (s *Service) Close(ctx context.Context) error {
|
||||
}
|
||||
|
||||
func (s *Service) List(ctx context.Context, page, pageSize int) ([]auditdomain.Record, int64, error) {
|
||||
if page < 1 {
|
||||
page = 1
|
||||
}
|
||||
if pageSize < 1 {
|
||||
pageSize = 20
|
||||
}
|
||||
if pageSize > 100 {
|
||||
pageSize = 100
|
||||
}
|
||||
page, pageSize = repository.NormalizePage(page, pageSize, repository.DefaultPageSize)
|
||||
return s.audits.List(ctx, (page-1)*pageSize, pageSize)
|
||||
}
|
||||
|
||||
@@ -208,12 +200,7 @@ type auditCursorPayload struct {
|
||||
|
||||
// ListCursor 使用复合游标读取审计,适合持续增长且支持多字段排序的大数据列表。
|
||||
func (s *Service) ListCursor(ctx context.Context, rawCursor string, pageSize int, search, rawPeriod string, filter ListFilter) (CursorResult, error) {
|
||||
if pageSize < 1 {
|
||||
pageSize = 50
|
||||
}
|
||||
if pageSize > 100 {
|
||||
pageSize = 100
|
||||
}
|
||||
_, pageSize = repository.NormalizePage(1, pageSize, repository.DefaultCursorPageSize)
|
||||
if filter.Sort.Field == "" && filter.Sort.Direction == "" {
|
||||
filter.Sort = repository.SortQuery{Field: "createdAt", Direction: repository.SortDescending}
|
||||
}
|
||||
|
||||
@@ -365,24 +365,15 @@ func (s *Service) CleanupExpiredBilling(ctx context.Context, limit int) (int, er
|
||||
}
|
||||
|
||||
func normalizePage(page, pageSize int) (int, int) {
|
||||
if page < 1 {
|
||||
page = 1
|
||||
}
|
||||
if pageSize < 1 {
|
||||
pageSize = 20
|
||||
}
|
||||
if pageSize > 100 {
|
||||
pageSize = 100
|
||||
}
|
||||
return page, pageSize
|
||||
return repository.NormalizePage(page, pageSize, repository.DefaultPageSize)
|
||||
}
|
||||
|
||||
func normalizeBatchIDs(ids []uint64) ([]uint64, error) {
|
||||
if len(ids) == 0 {
|
||||
return nil, invalidInput("至少选择一个 Key")
|
||||
}
|
||||
if len(ids) > 500 {
|
||||
return nil, invalidInput("单次最多处理 500 个 Key")
|
||||
if len(ids) > repository.MaxPageSize {
|
||||
return nil, invalidInput(fmt.Sprintf("单次最多处理 %d 个 Key", repository.MaxPageSize))
|
||||
}
|
||||
seen := make(map[uint64]struct{}, len(ids))
|
||||
result := make([]uint64, 0, len(ids))
|
||||
|
||||
@@ -336,15 +336,7 @@ func (s *Service) deleteVideoAsset(ctx context.Context, assetID string) error {
|
||||
}
|
||||
|
||||
func mediaPageQuery(page, pageSize int, search string, sort repository.SortQuery) repository.PageQuery {
|
||||
if page < 1 {
|
||||
page = 1
|
||||
}
|
||||
if pageSize < 1 {
|
||||
pageSize = 20
|
||||
}
|
||||
if pageSize > 100 {
|
||||
pageSize = 100
|
||||
}
|
||||
page, pageSize = repository.NormalizePage(page, pageSize, repository.DefaultPageSize)
|
||||
return repository.PageQuery{Offset: (page - 1) * pageSize, Limit: pageSize, Search: strings.TrimSpace(search), Sort: sort}
|
||||
}
|
||||
|
||||
|
||||
@@ -478,24 +478,15 @@ func (s *Service) markCapabilitySyncFailed(accountID uint64, attemptedAt time.Ti
|
||||
}
|
||||
|
||||
func normalizePage(page, pageSize int) (int, int) {
|
||||
if page < 1 {
|
||||
page = 1
|
||||
}
|
||||
if pageSize < 1 {
|
||||
pageSize = 20
|
||||
}
|
||||
if pageSize > 100 {
|
||||
pageSize = 100
|
||||
}
|
||||
return page, pageSize
|
||||
return repository.NormalizePage(page, pageSize, repository.DefaultPageSize)
|
||||
}
|
||||
|
||||
func normalizeBatchIDs(ids []uint64) ([]uint64, error) {
|
||||
if len(ids) == 0 {
|
||||
return nil, invalidInput("至少选择一个模型")
|
||||
}
|
||||
if len(ids) > 500 {
|
||||
return nil, invalidInput("单次最多处理 500 个模型")
|
||||
if len(ids) > repository.MaxPageSize {
|
||||
return nil, invalidInput(fmt.Sprintf("单次最多处理 %d 个模型", repository.MaxPageSize))
|
||||
}
|
||||
seen := make(map[uint64]struct{}, len(ids))
|
||||
result := make([]uint64, 0, len(ids))
|
||||
|
||||
@@ -2,6 +2,35 @@ package repository
|
||||
|
||||
import "time"
|
||||
|
||||
const (
|
||||
// DefaultPageSize is the default size for admin list endpoints.
|
||||
DefaultPageSize = 20
|
||||
// MaxPageSize bounds an individual admin query. It is intentionally finite
|
||||
// so large page requests cannot turn into unbounded database or JSON work.
|
||||
MaxPageSize = 2000
|
||||
// DefaultCursorPageSize is the default batch size for cursor-based audit reads.
|
||||
DefaultCursorPageSize = 50
|
||||
)
|
||||
|
||||
// NormalizePage applies the common bounded pagination contract used by all
|
||||
// admin list endpoints. Keeping this in one place prevents transport and
|
||||
// application layers from returning different effective page sizes.
|
||||
func NormalizePage(page, pageSize, defaultPageSize int) (int, int) {
|
||||
if page < 1 {
|
||||
page = 1
|
||||
}
|
||||
if defaultPageSize < 1 || defaultPageSize > MaxPageSize {
|
||||
defaultPageSize = DefaultPageSize
|
||||
}
|
||||
if pageSize < 1 {
|
||||
pageSize = defaultPageSize
|
||||
}
|
||||
if pageSize > MaxPageSize {
|
||||
pageSize = MaxPageSize
|
||||
}
|
||||
return page, pageSize
|
||||
}
|
||||
|
||||
type SortDirection string
|
||||
|
||||
const (
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
package repository
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestNormalizePageBoundsAdminPageSize(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
pageSize int
|
||||
wantPage, wantSize int
|
||||
}{
|
||||
{name: "invalid page and size", pageSize: 0, wantPage: 1, wantSize: DefaultPageSize},
|
||||
{name: "supported large page", pageSize: 2000, wantPage: 1, wantSize: 2000},
|
||||
{name: "caps oversized page", pageSize: 5000, wantPage: 1, wantSize: MaxPageSize},
|
||||
}
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
page, size := NormalizePage(0, test.pageSize, DefaultPageSize)
|
||||
if page != test.wantPage || size != test.wantSize {
|
||||
t.Fatalf("NormalizePage() = (%d, %d), want (%d, %d)", page, size, test.wantPage, test.wantSize)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestNormalizePageSanitizesInvalidDefault(t *testing.T) {
|
||||
_, size := NormalizePage(1, 0, MaxPageSize+1)
|
||||
if size != DefaultPageSize {
|
||||
t.Fatalf("NormalizePage() default size = %d, want %d", size, DefaultPageSize)
|
||||
}
|
||||
}
|
||||
@@ -1201,16 +1201,7 @@ func newBillingResponse(value accountdomain.Billing) billingResponse {
|
||||
func pagination(c *gin.Context) (int, int) {
|
||||
page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
|
||||
size, _ := strconv.Atoi(c.DefaultQuery("pageSize", "20"))
|
||||
if page < 1 {
|
||||
page = 1
|
||||
}
|
||||
if size < 1 {
|
||||
size = 20
|
||||
}
|
||||
if size > 100 {
|
||||
size = 100
|
||||
}
|
||||
return page, size
|
||||
return repository.NormalizePage(page, size, repository.DefaultPageSize)
|
||||
}
|
||||
|
||||
func pathID(c *gin.Context) (uint64, bool) {
|
||||
|
||||
@@ -105,15 +105,7 @@ func (h *Handler) list(c *gin.Context) {
|
||||
}
|
||||
page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
|
||||
pageSize, _ := strconv.Atoi(c.DefaultQuery("pageSize", "20"))
|
||||
if page < 1 {
|
||||
page = 1
|
||||
}
|
||||
if pageSize < 1 {
|
||||
pageSize = 20
|
||||
}
|
||||
if pageSize > 100 {
|
||||
pageSize = 100
|
||||
}
|
||||
page, pageSize = repository.NormalizePage(page, pageSize, repository.DefaultPageSize)
|
||||
values, total, err := h.service.List(c.Request.Context(), page, pageSize)
|
||||
if err != nil {
|
||||
response.Error(c, http.StatusInternalServerError, "auditListFailed", "读取审计记录失败")
|
||||
@@ -128,6 +120,7 @@ func (h *Handler) list(c *gin.Context) {
|
||||
|
||||
func (h *Handler) listCursor(c *gin.Context) {
|
||||
pageSize, _ := strconv.Atoi(c.DefaultQuery("pageSize", "50"))
|
||||
_, pageSize = repository.NormalizePage(1, pageSize, repository.DefaultCursorPageSize)
|
||||
result, err := h.service.ListCursor(c.Request.Context(), c.Query("cursor"), pageSize, c.Query("search"), c.Query("period"), newListFilter(c))
|
||||
if errors.Is(err, auditapp.ErrInvalidCursor) {
|
||||
response.Error(c, http.StatusBadRequest, "invalidCursor", err.Error())
|
||||
|
||||
@@ -281,14 +281,5 @@ func pathID(c *gin.Context) (uint64, bool) {
|
||||
func pagination(c *gin.Context) (int, int) {
|
||||
page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
|
||||
size, _ := strconv.Atoi(c.DefaultQuery("pageSize", "20"))
|
||||
if page < 1 {
|
||||
page = 1
|
||||
}
|
||||
if size < 1 {
|
||||
size = 20
|
||||
}
|
||||
if size > 100 {
|
||||
size = 100
|
||||
}
|
||||
return page, size
|
||||
return repository.NormalizePage(page, size, repository.DefaultPageSize)
|
||||
}
|
||||
@@ -236,14 +236,5 @@ func (h *Handler) deleteVideos(c *gin.Context) {
|
||||
func parsePagination(c *gin.Context) (int, int) {
|
||||
page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
|
||||
pageSize, _ := strconv.Atoi(c.DefaultQuery("pageSize", "20"))
|
||||
if page < 1 {
|
||||
page = 1
|
||||
}
|
||||
if pageSize < 1 {
|
||||
pageSize = 20
|
||||
}
|
||||
if pageSize > 100 {
|
||||
pageSize = 100
|
||||
}
|
||||
return page, pageSize
|
||||
return repository.NormalizePage(page, pageSize, repository.DefaultPageSize)
|
||||
}
|
||||
@@ -267,14 +267,5 @@ func parseIDs(values []string) ([]uint64, error) {
|
||||
func pagination(c *gin.Context) (int, int) {
|
||||
page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
|
||||
pageSize, _ := strconv.Atoi(c.DefaultQuery("pageSize", "20"))
|
||||
if page < 1 {
|
||||
page = 1
|
||||
}
|
||||
if pageSize < 1 {
|
||||
pageSize = 20
|
||||
}
|
||||
if pageSize > 100 {
|
||||
pageSize = 100
|
||||
}
|
||||
return page, pageSize
|
||||
return repository.NormalizePage(page, pageSize, repository.DefaultPageSize)
|
||||
}
|
||||
@@ -2,11 +2,20 @@ import * as React from "react"
|
||||
|
||||
import { cn } from "@/shared/lib/cn"
|
||||
|
||||
const Table = React.forwardRef<
|
||||
HTMLTableElement,
|
||||
React.HTMLAttributes<HTMLTableElement>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<div className="relative w-full overflow-auto">
|
||||
type TableProps = React.HTMLAttributes<HTMLTableElement> & {
|
||||
viewportRows?: number
|
||||
rowHeight?: number
|
||||
}
|
||||
|
||||
const Table = React.forwardRef<HTMLTableElement, TableProps>(({ className, viewportRows, rowHeight, ...props }, ref) => (
|
||||
<div
|
||||
data-slot="table-scroll-container"
|
||||
className={cn(
|
||||
"relative w-full overflow-auto",
|
||||
viewportRows && "[&_thead]:sticky [&_thead]:top-0 [&_thead]:z-30 [&_thead]:bg-background"
|
||||
)}
|
||||
style={viewportRows && rowHeight ? { maxHeight: 36 + viewportRows * rowHeight } : undefined}
|
||||
>
|
||||
<table
|
||||
ref={ref}
|
||||
className={cn("w-full caption-bottom text-sm", className)}
|
||||
|
||||
@@ -28,6 +28,7 @@ import { DataTableShell } from "@/shared/components/data-table-shell";
|
||||
import { DataTableFilters } from "@/shared/components/data-table-filters";
|
||||
import { Pagination } from "@/shared/components/pagination";
|
||||
import { SortableTableHead } from "@/shared/components/sortable-table-head";
|
||||
import { VirtualTableBody } from "@/shared/components/virtual-table-body";
|
||||
import { useDebouncedValue } from "@/shared/hooks/use-debounced-value";
|
||||
import { cn } from "@/shared/lib/cn";
|
||||
import { formatDateTime, formatNumber } from "@/shared/lib/format";
|
||||
@@ -823,7 +824,7 @@ export function AccountsPage() {
|
||||
{accountsQuery.isError ? <ErrorState message={accountsQuery.error.message} onRetry={() => void accountsQuery.refetch()} /> : null}
|
||||
{result && result.items.length === 0 ? <EmptyState /> : null}
|
||||
{accountsQuery.isPending || (result && result.items.length > 0) ? (
|
||||
<Table className="table-fixed border-collapse min-w-[780px] xl:min-w-[960px] 2xl:min-w-[1080px]">
|
||||
<Table viewportRows={20} rowHeight={56} className="table-fixed border-collapse min-w-[780px] xl:min-w-[960px] 2xl:min-w-[1080px]">
|
||||
<colgroup>
|
||||
<col style={{ width: "3%" }} />
|
||||
<col style={{ width: "18%" }} />
|
||||
@@ -846,10 +847,15 @@ export function AccountsPage() {
|
||||
<TableActionHead />
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{accountsQuery.isPending ? <TableLoadingRow colSpan={provider === "grok_build" ? 8 : 7} /> : result?.items.map((account) => {
|
||||
return (
|
||||
<TableRow className="group [&>td]:py-1.5" key={account.id} data-state={selected.has(account.id) ? "selected" : undefined}>
|
||||
{accountsQuery.isPending ? (
|
||||
<TableBody><TableLoadingRow colSpan={provider === "grok_build" ? 8 : 7} /></TableBody>
|
||||
) : (
|
||||
<VirtualTableBody
|
||||
items={result?.items ?? []}
|
||||
colSpan={provider === "grok_build" ? 8 : 7}
|
||||
rowHeight={56}
|
||||
renderRow={(account) => (
|
||||
<TableRow className="group h-14 [&>td]:py-1.5" key={account.id} data-state={selected.has(account.id) ? "selected" : undefined}>
|
||||
<TableCell className="px-2"><Checkbox checked={selected.has(account.id)} onCheckedChange={(checked) => toggleAccount(account.id, checked === true)} aria-label={t("common.selectItem", { name: account.name })} /></TableCell>
|
||||
<TableCell className="min-w-0"><AccountNameCell account={account} /></TableCell>
|
||||
<TableCell className="text-center whitespace-nowrap">{provider === "grok_web" ? <WebAccountType tier={account.webTier} /> : provider === "grok_console" ? <AccountTypeText label={t("accountType.console")} variant="free" /> : <AccountType quota={account.quota} />}</TableCell>
|
||||
@@ -885,9 +891,9 @@ export function AccountsPage() {
|
||||
</DropdownMenu>
|
||||
</TableActionCell>
|
||||
</TableRow>
|
||||
);
|
||||
})}
|
||||
</TableBody>
|
||||
)}
|
||||
/>
|
||||
)}
|
||||
</Table>
|
||||
) : null}
|
||||
</DataTableShell>
|
||||
|
||||
@@ -18,6 +18,7 @@ import { CursorPagination } from "@/shared/components/pagination";
|
||||
import { PageHeader } from "@/shared/components/page-header";
|
||||
import { PeriodSelector } from "@/shared/components/period-selector";
|
||||
import { SortableTableHead } from "@/shared/components/sortable-table-head";
|
||||
import { VirtualTableBody } from "@/shared/components/virtual-table-body";
|
||||
import { useDebouncedValue } from "@/shared/hooks/use-debounced-value";
|
||||
import { cn } from "@/shared/lib/cn";
|
||||
import { formatDateTime, formatDuration, formatNumber } from "@/shared/lib/format";
|
||||
@@ -27,7 +28,7 @@ import { nextTableSort, type SortOrder, type TableSort } from "@/shared/lib/tabl
|
||||
export function RequestAuditsPage() {
|
||||
const { t, i18n } = useTranslation();
|
||||
const [cursors, setCursors] = useState<string[]>([""]);
|
||||
const [pageSize, setPageSize] = useState(50);
|
||||
const [pageSize, setPageSize] = useState(20);
|
||||
const [search, setSearch] = useState("");
|
||||
const [modelFilter, setModelFilter] = useState("");
|
||||
const [statusFilter, setStatusFilter] = useState("");
|
||||
@@ -159,7 +160,7 @@ export function RequestAuditsPage() {
|
||||
{auditsQuery.isError ? <ErrorState message={auditsQuery.error.message} onRetry={() => void auditsQuery.refetch()} /> : null}
|
||||
{result && result.items.length === 0 ? <EmptyState /> : null}
|
||||
{auditsQuery.isPending || (result && result.items.length > 0) ? (
|
||||
<Table className="min-w-[1136px] table-fixed text-xs">
|
||||
<Table viewportRows={20} rowHeight={72} className="min-w-[1136px] table-fixed text-xs">
|
||||
<colgroup>
|
||||
<col className="w-40" />
|
||||
<col className="w-44" />
|
||||
@@ -182,8 +183,10 @@ export function RequestAuditsPage() {
|
||||
<SortableTableHead field="createdAt" sortBy={sort.field} sortOrder={sort.order} initialOrder="desc" onSort={changeSort}>{t("audits.createdAt")}</SortableTableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{auditsQuery.isPending ? <TableLoadingRow colSpan={8} /> : result?.items.map((audit) => (
|
||||
{auditsQuery.isPending ? (
|
||||
<TableBody><TableLoadingRow colSpan={8} /></TableBody>
|
||||
) : (
|
||||
<VirtualTableBody items={result?.items ?? []} colSpan={8} rowHeight={72} renderRow={(audit) => (
|
||||
<TableRow className="h-[72px]" key={audit.id}>
|
||||
<TableCell><RequestValue audit={audit} /></TableCell>
|
||||
<TableCell>
|
||||
@@ -201,8 +204,8 @@ export function RequestAuditsPage() {
|
||||
<TableCell className="whitespace-nowrap text-xs tabular-nums">{formatDuration(audit.durationMs)}</TableCell>
|
||||
<TableCell className="whitespace-nowrap text-xs text-muted-foreground">{formatDateTime(audit.createdAt, i18n.language)}</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
)} />
|
||||
)}
|
||||
</Table>
|
||||
) : null}
|
||||
</DataTableShell>
|
||||
|
||||
@@ -29,6 +29,7 @@ import { DataTableFilters } from "@/shared/components/data-table-filters";
|
||||
import { DateTimePicker } from "@/shared/components/date-time-picker";
|
||||
import { Pagination } from "@/shared/components/pagination";
|
||||
import { SortableTableHead } from "@/shared/components/sortable-table-head";
|
||||
import { VirtualTableBody } from "@/shared/components/virtual-table-body";
|
||||
import { useDebouncedValue } from "@/shared/hooks/use-debounced-value";
|
||||
import { formatDateTime, toDateTimeLocal } from "@/shared/lib/format";
|
||||
import { nextTableSort, type SortOrder, type TableSort } from "@/shared/lib/table-sort";
|
||||
@@ -259,7 +260,7 @@ export function ClientKeysPage() {
|
||||
{keysQuery.isError ? <ErrorState message={keysQuery.error.message} onRetry={() => void keysQuery.refetch()} /> : null}
|
||||
{result && result.items.length === 0 ? <EmptyState /> : null}
|
||||
{keysQuery.isPending || (result && result.items.length > 0) ? (
|
||||
<Table className="min-w-[1120px] table-fixed text-xs">
|
||||
<Table viewportRows={20} rowHeight={56} className="min-w-[1120px] table-fixed text-xs">
|
||||
<colgroup>
|
||||
<col className="w-10" />
|
||||
<col className="w-36" />
|
||||
@@ -286,8 +287,10 @@ export function ClientKeysPage() {
|
||||
<TableActionHead />
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{keysQuery.isPending ? <TableLoadingRow colSpan={10} /> : result?.items.map((key) => (
|
||||
{keysQuery.isPending ? (
|
||||
<TableBody><TableLoadingRow colSpan={10} /></TableBody>
|
||||
) : (
|
||||
<VirtualTableBody items={result?.items ?? []} colSpan={10} rowHeight={56} renderRow={(key) => (
|
||||
<TableRow className="group h-14" key={key.id} data-state={selected.has(key.id) ? "selected" : undefined}>
|
||||
<TableCell><Checkbox checked={selected.has(key.id)} onCheckedChange={(checked) => toggleKey(key.id, checked === true)} aria-label={t("common.selectItem", { name: key.name })} /></TableCell>
|
||||
<TableCell className="min-w-0">
|
||||
@@ -326,8 +329,8 @@ export function ClientKeysPage() {
|
||||
</DropdownMenu>
|
||||
</TableActionCell>
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
)} />
|
||||
)}
|
||||
</Table>
|
||||
) : null}
|
||||
</DataTableShell>
|
||||
|
||||
@@ -177,7 +177,7 @@ function ImageCard({ image, locale, selectionMode, selected, onSelectedChange }:
|
||||
// 管理端图库与 API 同源,使用相对路径避免依赖未配置或仅对外可用的公共地址。
|
||||
const imageURL = `/v1/media/images/${encodeURIComponent(image.id)}`;
|
||||
return (
|
||||
<article className="group relative min-w-0">
|
||||
<article className="group relative min-w-0 [content-visibility:auto] [contain-intrinsic-size:0_280px]">
|
||||
<Checkbox
|
||||
checked={selected}
|
||||
onCheckedChange={(checked) => onSelectedChange(checked === true)}
|
||||
|
||||
@@ -21,6 +21,7 @@ import { DataTableShell } from "@/shared/components/data-table-shell";
|
||||
import { PageHeader } from "@/shared/components/page-header";
|
||||
import { Pagination } from "@/shared/components/pagination";
|
||||
import { SortableTableHead } from "@/shared/components/sortable-table-head";
|
||||
import { VirtualTableBody } from "@/shared/components/virtual-table-body";
|
||||
import { useDebouncedValue } from "@/shared/hooks/use-debounced-value";
|
||||
import { cn } from "@/shared/lib/cn";
|
||||
import { formatDateTime, formatNumber } from "@/shared/lib/format";
|
||||
@@ -163,7 +164,7 @@ export function VideoGalleryPage() {
|
||||
{videosQuery.isError ? <ErrorState message={videosQuery.error.message} onRetry={() => void videosQuery.refetch()} /> : null}
|
||||
{result && result.items.length === 0 ? <EmptyState message={t("media.videos.empty")} /> : null}
|
||||
{videosQuery.isPending || (result && result.items.length > 0) ? (
|
||||
<Table className="min-w-[1096px] table-fixed text-xs">
|
||||
<Table viewportRows={20} rowHeight={72} className="min-w-[1096px] table-fixed text-xs">
|
||||
<colgroup>
|
||||
<col className="w-10" />
|
||||
<col className="w-64" />
|
||||
@@ -186,8 +187,10 @@ export function VideoGalleryPage() {
|
||||
<TableActionHead />
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{videosQuery.isPending ? <TableLoadingRow colSpan={8} /> : result?.items.map((job) => (
|
||||
{videosQuery.isPending ? (
|
||||
<TableBody><TableLoadingRow colSpan={8} /></TableBody>
|
||||
) : (
|
||||
<VirtualTableBody items={result?.items ?? []} colSpan={8} rowHeight={72} renderRow={(job) => (
|
||||
<TableRow className="group h-[72px]" data-state={selected.has(job.id) ? "selected" : undefined} key={job.id}>
|
||||
<TableCell>
|
||||
<Checkbox checked={selected.has(job.id)} disabled={!isTerminalVideoJob(job)} onCheckedChange={(checked) => toggleVideo(job.id, checked === true)} aria-label={t("common.selectItem", { name: job.id })} />
|
||||
@@ -219,8 +222,8 @@ export function VideoGalleryPage() {
|
||||
) : null}
|
||||
</TableActionCell>
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
)} />
|
||||
)}
|
||||
</Table>
|
||||
) : null}
|
||||
</DataTableShell>
|
||||
|
||||
@@ -26,6 +26,7 @@ import { DataTableShell } from "@/shared/components/data-table-shell";
|
||||
import { DataTableFilters } from "@/shared/components/data-table-filters";
|
||||
import { Pagination } from "@/shared/components/pagination";
|
||||
import { SortableTableHead } from "@/shared/components/sortable-table-head";
|
||||
import { VirtualTableBody } from "@/shared/components/virtual-table-body";
|
||||
import { useDebouncedValue } from "@/shared/hooks/use-debounced-value";
|
||||
import { cn } from "@/shared/lib/cn";
|
||||
import { formatDateTime } from "@/shared/lib/format";
|
||||
@@ -35,7 +36,7 @@ export function ModelsPage() {
|
||||
const { t, i18n } = useTranslation();
|
||||
const queryClient = useQueryClient();
|
||||
const [page, setPage] = useState(1);
|
||||
const [pageSize, setPageSize] = useState(50);
|
||||
const [pageSize, setPageSize] = useState(20);
|
||||
const [search, setSearch] = useState("");
|
||||
const [statusFilter, setStatusFilter] = useState("");
|
||||
const [providerFilter, setProviderFilter] = useState<ModelRouteDTO["provider"] | "">("");
|
||||
@@ -246,7 +247,7 @@ export function ModelsPage() {
|
||||
{modelsQuery.isError ? <ErrorState message={modelsQuery.error.message} onRetry={() => void modelsQuery.refetch()} /> : null}
|
||||
{result && result.items.length === 0 ? <EmptyState /> : null}
|
||||
{modelsQuery.isPending || (result && result.items.length > 0) ? (
|
||||
<Table className="min-w-[1000px] table-fixed text-xs">
|
||||
<Table viewportRows={20} rowHeight={56} className="min-w-[1000px] table-fixed text-xs">
|
||||
<colgroup>
|
||||
<col className="w-10" />
|
||||
<col className="w-56" />
|
||||
@@ -269,8 +270,10 @@ export function ModelsPage() {
|
||||
<TableActionHead />
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{modelsQuery.isPending ? <TableLoadingRow colSpan={8} /> : result?.items.map((model) => (
|
||||
{modelsQuery.isPending ? (
|
||||
<TableBody><TableLoadingRow colSpan={8} /></TableBody>
|
||||
) : (
|
||||
<VirtualTableBody items={result?.items ?? []} colSpan={8} rowHeight={56} renderRow={(model) => (
|
||||
<TableRow className="group h-14" key={model.id} data-state={selected.has(model.id) ? "selected" : undefined}>
|
||||
<TableCell className="px-2 text-center"><Checkbox checked={selected.has(model.id)} onCheckedChange={(checked) => toggleModel(model.id, checked === true)} aria-label={t("common.selectItem", { name: model.publicId })} /></TableCell>
|
||||
<TableCell className="min-w-0">
|
||||
@@ -298,8 +301,8 @@ export function ModelsPage() {
|
||||
</DropdownMenu>
|
||||
</TableActionCell>
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
)} />
|
||||
)}
|
||||
</Table>
|
||||
) : null}
|
||||
</DataTableShell>
|
||||
|
||||
@@ -5,6 +5,8 @@ import { Button } from "@/components/ui/button";
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
|
||||
import { cn } from "@/shared/lib/cn";
|
||||
|
||||
const PAGE_SIZE_OPTIONS = [20, 100, 500, 1000, 2000] as const;
|
||||
|
||||
export function Pagination({ page, pageSize, total, onPageChange, onPageSizeChange, className }: { page: number; pageSize: number; total: number; onPageChange: (page: number) => void; onPageSizeChange?: (pageSize: number) => void; className?: string }) {
|
||||
const { t } = useTranslation();
|
||||
const pages = Math.max(1, Math.ceil(total / pageSize));
|
||||
@@ -47,7 +49,7 @@ function PageSizeSelector({ pageSize, onChange }: { pageSize: number; onChange:
|
||||
<Select value={String(pageSize)} onValueChange={(value) => onChange(Number(value))}>
|
||||
<SelectTrigger className="h-8 w-[76px] rounded-md bg-secondary px-3 text-xs shadow-none" aria-label={t("common.perPage")}><SelectValue /></SelectTrigger>
|
||||
<SelectContent align="end">
|
||||
{[20, 50, 100].map((value) => <SelectItem key={value} value={String(value)}>{value}</SelectItem>)}
|
||||
{PAGE_SIZE_OPTIONS.map((value) => <SelectItem key={value} value={String(value)}>{value}</SelectItem>)}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<span>{t("common.rows")}</span>
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
import { useCallback, useLayoutEffect, useRef, useState, type ReactNode } from "react";
|
||||
|
||||
import { TableBody, TableCell, TableRow } from "@/components/ui/table";
|
||||
|
||||
const DEFAULT_OVERSCAN = 12;
|
||||
const MIN_VIRTUALIZED_ROWS = 20;
|
||||
|
||||
type VirtualTableBodyProps<T> = {
|
||||
items: readonly T[];
|
||||
colSpan: number;
|
||||
rowHeight: number;
|
||||
renderRow: (item: T, index: number) => ReactNode;
|
||||
overscan?: number;
|
||||
};
|
||||
|
||||
type VisibleRange = { start: number; end: number };
|
||||
|
||||
// VirtualTableBody keeps the native table structure and an internal table
|
||||
// viewport while mounting only the visible rows. Fixed-height management tables
|
||||
// are a good fit and keep large page sizes from creating thousands of Radix
|
||||
// controls, tooltips, and menu triggers at once.
|
||||
export function VirtualTableBody<T>({ items, colSpan, rowHeight, renderRow, overscan = DEFAULT_OVERSCAN }: VirtualTableBodyProps<T>) {
|
||||
const bodyRef = useRef<HTMLTableSectionElement>(null);
|
||||
const frameRef = useRef<number | null>(null);
|
||||
const enabled = items.length > MIN_VIRTUALIZED_ROWS;
|
||||
const [range, setRange] = useState<VisibleRange>(() => ({ start: 0, end: enabled ? Math.min(items.length, 50) : items.length }));
|
||||
|
||||
const updateRange = useCallback(() => {
|
||||
if (!enabled || !bodyRef.current) {
|
||||
setRange((current) => current.start === 0 && current.end === items.length ? current : { start: 0, end: items.length });
|
||||
return;
|
||||
}
|
||||
const rect = bodyRef.current.getBoundingClientRect();
|
||||
const scrollContainer = bodyRef.current.closest<HTMLElement>("[data-slot=table-scroll-container]");
|
||||
const containerRect = scrollContainer?.getBoundingClientRect();
|
||||
const viewportTop = Math.max(0, containerRect?.top ?? 0);
|
||||
const viewportBottom = Math.min(window.innerHeight, containerRect?.bottom ?? window.innerHeight);
|
||||
const relativeTop = Math.max(0, viewportTop - rect.top);
|
||||
const relativeBottom = Math.min(rect.height, viewportBottom - rect.top);
|
||||
const start = Math.max(0, Math.floor(relativeTop / rowHeight) - overscan);
|
||||
const end = Math.min(items.length, Math.ceil(Math.max(relativeTop, relativeBottom) / rowHeight) + overscan);
|
||||
setRange((current) => current.start === start && current.end === end ? current : { start, end });
|
||||
}, [enabled, items.length, overscan, rowHeight]);
|
||||
|
||||
useLayoutEffect(() => {
|
||||
const scrollContainer = bodyRef.current?.closest<HTMLElement>("[data-slot=table-scroll-container]") ?? null;
|
||||
const scheduleUpdate = () => {
|
||||
if (frameRef.current !== null) return;
|
||||
frameRef.current = window.requestAnimationFrame(() => {
|
||||
frameRef.current = null;
|
||||
updateRange();
|
||||
});
|
||||
};
|
||||
scheduleUpdate();
|
||||
window.addEventListener("scroll", scheduleUpdate, { passive: true });
|
||||
window.addEventListener("resize", scheduleUpdate);
|
||||
scrollContainer?.addEventListener("scroll", scheduleUpdate, { passive: true });
|
||||
const observer = typeof ResizeObserver === "undefined" || !scrollContainer ? null : new ResizeObserver(scheduleUpdate);
|
||||
observer?.observe(scrollContainer);
|
||||
return () => {
|
||||
window.removeEventListener("scroll", scheduleUpdate);
|
||||
window.removeEventListener("resize", scheduleUpdate);
|
||||
scrollContainer?.removeEventListener("scroll", scheduleUpdate);
|
||||
observer?.disconnect();
|
||||
if (frameRef.current !== null) window.cancelAnimationFrame(frameRef.current);
|
||||
frameRef.current = null;
|
||||
};
|
||||
}, [updateRange]);
|
||||
|
||||
const safeStart = enabled && items.length > 0 ? Math.min(range.start, items.length - 1) : 0;
|
||||
const safeEnd = enabled && items.length > 0 ? Math.max(safeStart + 1, Math.min(items.length, range.end)) : 0;
|
||||
const visibleItems = enabled ? items.slice(safeStart, safeEnd) : items;
|
||||
const topHeight = enabled ? safeStart * rowHeight : 0;
|
||||
const bottomHeight = enabled ? Math.max(0, items.length - safeEnd) * rowHeight : 0;
|
||||
|
||||
return (
|
||||
<TableBody ref={bodyRef}>
|
||||
{topHeight > 0 ? <VirtualSpacer colSpan={colSpan} height={topHeight} /> : null}
|
||||
{visibleItems.map((item, index) => renderRow(item, safeStart + index))}
|
||||
{bottomHeight > 0 ? <VirtualSpacer colSpan={colSpan} height={bottomHeight} /> : null}
|
||||
</TableBody>
|
||||
);
|
||||
}
|
||||
|
||||
function VirtualSpacer({ colSpan, height }: { colSpan: number; height: number }) {
|
||||
return (
|
||||
<TableRow aria-hidden="true" className="pointer-events-none border-0 hover:bg-transparent">
|
||||
<TableCell colSpan={colSpan} className="p-0" style={{ height }} />
|
||||
</TableRow>
|
||||
);
|
||||
}
|
||||
Reference in new issue
Block a user