diff --git a/backend/internal/application/account/service.go b/backend/internal/application/account/service.go index 15756c84..ee279e1f 100644 --- a/backend/internal/application/account/service.go +++ b/backend/internal/application/account/service.go @@ -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) { diff --git a/backend/internal/application/audit/service.go b/backend/internal/application/audit/service.go index fff53abc..870aef45 100644 --- a/backend/internal/application/audit/service.go +++ b/backend/internal/application/audit/service.go @@ -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} } diff --git a/backend/internal/application/clientkey/service.go b/backend/internal/application/clientkey/service.go index f20b864b..3984b234 100644 --- a/backend/internal/application/clientkey/service.go +++ b/backend/internal/application/clientkey/service.go @@ -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)) diff --git a/backend/internal/application/media/service.go b/backend/internal/application/media/service.go index 3a42c365..20b7e9ac 100644 --- a/backend/internal/application/media/service.go +++ b/backend/internal/application/media/service.go @@ -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} } diff --git a/backend/internal/application/model/service.go b/backend/internal/application/model/service.go index 0eb99033..f7f68de8 100644 --- a/backend/internal/application/model/service.go +++ b/backend/internal/application/model/service.go @@ -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)) diff --git a/backend/internal/repository/list.go b/backend/internal/repository/list.go index dc7252e6..3cfc0070 100644 --- a/backend/internal/repository/list.go +++ b/backend/internal/repository/list.go @@ -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 ( diff --git a/backend/internal/repository/list_test.go b/backend/internal/repository/list_test.go new file mode 100644 index 00000000..1cfc4655 --- /dev/null +++ b/backend/internal/repository/list_test.go @@ -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) + } +} diff --git a/backend/internal/transport/http/account/handler.go b/backend/internal/transport/http/account/handler.go index f289606c..2769a2ec 100644 --- a/backend/internal/transport/http/account/handler.go +++ b/backend/internal/transport/http/account/handler.go @@ -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) { diff --git a/backend/internal/transport/http/audit/handler.go b/backend/internal/transport/http/audit/handler.go index b3af6d03..7b13457e 100644 --- a/backend/internal/transport/http/audit/handler.go +++ b/backend/internal/transport/http/audit/handler.go @@ -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()) diff --git a/backend/internal/transport/http/clientkey/handler.go b/backend/internal/transport/http/clientkey/handler.go index 7e425c46..44e0824d 100644 --- a/backend/internal/transport/http/clientkey/handler.go +++ b/backend/internal/transport/http/clientkey/handler.go @@ -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) } diff --git a/backend/internal/transport/http/media/handler.go b/backend/internal/transport/http/media/handler.go index 5426bdb8..b00e2bb6 100644 --- a/backend/internal/transport/http/media/handler.go +++ b/backend/internal/transport/http/media/handler.go @@ -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) } diff --git a/backend/internal/transport/http/model/handler.go b/backend/internal/transport/http/model/handler.go index 310e62e5..726c2182 100644 --- a/backend/internal/transport/http/model/handler.go +++ b/backend/internal/transport/http/model/handler.go @@ -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) } diff --git a/frontend/src/components/ui/table.tsx b/frontend/src/components/ui/table.tsx index ba303abf..e3abae9c 100644 --- a/frontend/src/components/ui/table.tsx +++ b/frontend/src/components/ui/table.tsx @@ -2,11 +2,20 @@ import * as React from "react" import { cn } from "@/shared/lib/cn" -const Table = React.forwardRef< - HTMLTableElement, - React.HTMLAttributes ->(({ className, ...props }, ref) => ( -
+type TableProps = React.HTMLAttributes & { + viewportRows?: number + rowHeight?: number +} + +const Table = React.forwardRef(({ className, viewportRows, rowHeight, ...props }, ref) => ( +
void accountsQuery.refetch()} /> : null} {result && result.items.length === 0 ? : null} {accountsQuery.isPending || (result && result.items.length > 0) ? ( -
+
@@ -846,10 +847,15 @@ export function AccountsPage() { - - {accountsQuery.isPending ? : result?.items.map((account) => { - return ( - + {accountsQuery.isPending ? ( + + ) : ( + ( + toggleAccount(account.id, checked === true)} aria-label={t("common.selectItem", { name: account.name })} /> {provider === "grok_web" ? : provider === "grok_console" ? : } @@ -885,9 +891,9 @@ export function AccountsPage() { - ); - })} - + )} + /> + )}
) : null} diff --git a/frontend/src/features/audits/request-audits-page.tsx b/frontend/src/features/audits/request-audits-page.tsx index 9df67113..cd907217 100644 --- a/frontend/src/features/audits/request-audits-page.tsx +++ b/frontend/src/features/audits/request-audits-page.tsx @@ -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([""]); - 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 ? void auditsQuery.refetch()} /> : null} {result && result.items.length === 0 ? : null} {auditsQuery.isPending || (result && result.items.length > 0) ? ( - +
@@ -182,8 +183,10 @@ export function RequestAuditsPage() { {t("audits.createdAt")} - - {auditsQuery.isPending ? : result?.items.map((audit) => ( + {auditsQuery.isPending ? ( + + ) : ( + ( @@ -201,8 +204,8 @@ export function RequestAuditsPage() { {formatDuration(audit.durationMs)} {formatDateTime(audit.createdAt, i18n.language)} - ))} - + )} /> + )}
) : null} diff --git a/frontend/src/features/client-keys/client-keys-page.tsx b/frontend/src/features/client-keys/client-keys-page.tsx index 62a47ae2..33031d1e 100644 --- a/frontend/src/features/client-keys/client-keys-page.tsx +++ b/frontend/src/features/client-keys/client-keys-page.tsx @@ -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 ? void keysQuery.refetch()} /> : null} {result && result.items.length === 0 ? : null} {keysQuery.isPending || (result && result.items.length > 0) ? ( - +
@@ -286,8 +287,10 @@ export function ClientKeysPage() { - - {keysQuery.isPending ? : result?.items.map((key) => ( + {keysQuery.isPending ? ( + + ) : ( + ( toggleKey(key.id, checked === true)} aria-label={t("common.selectItem", { name: key.name })} /> @@ -326,8 +329,8 @@ export function ClientKeysPage() { - ))} - + )} /> + )}
) : null} diff --git a/frontend/src/features/media/gallery-page.tsx b/frontend/src/features/media/gallery-page.tsx index 5436599f..00b5aea5 100644 --- a/frontend/src/features/media/gallery-page.tsx +++ b/frontend/src/features/media/gallery-page.tsx @@ -177,7 +177,7 @@ function ImageCard({ image, locale, selectionMode, selected, onSelectedChange }: // 管理端图库与 API 同源,使用相对路径避免依赖未配置或仅对外可用的公共地址。 const imageURL = `/v1/media/images/${encodeURIComponent(image.id)}`; return ( -
+
onSelectedChange(checked === true)} diff --git a/frontend/src/features/media/video-gallery-page.tsx b/frontend/src/features/media/video-gallery-page.tsx index de415561..f070f252 100644 --- a/frontend/src/features/media/video-gallery-page.tsx +++ b/frontend/src/features/media/video-gallery-page.tsx @@ -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 ? void videosQuery.refetch()} /> : null} {result && result.items.length === 0 ? : null} {videosQuery.isPending || (result && result.items.length > 0) ? ( - +
@@ -186,8 +187,10 @@ export function VideoGalleryPage() { - - {videosQuery.isPending ? : result?.items.map((job) => ( + {videosQuery.isPending ? ( + + ) : ( + ( toggleVideo(job.id, checked === true)} aria-label={t("common.selectItem", { name: job.id })} /> @@ -219,8 +222,8 @@ export function VideoGalleryPage() { ) : null} - ))} - + )} /> + )}
) : null} diff --git a/frontend/src/features/models/models-page.tsx b/frontend/src/features/models/models-page.tsx index ec9b515c..8bbefa71 100644 --- a/frontend/src/features/models/models-page.tsx +++ b/frontend/src/features/models/models-page.tsx @@ -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(""); @@ -246,7 +247,7 @@ export function ModelsPage() { {modelsQuery.isError ? void modelsQuery.refetch()} /> : null} {result && result.items.length === 0 ? : null} {modelsQuery.isPending || (result && result.items.length > 0) ? ( - +
@@ -269,8 +270,10 @@ export function ModelsPage() { - - {modelsQuery.isPending ? : result?.items.map((model) => ( + {modelsQuery.isPending ? ( + + ) : ( + ( toggleModel(model.id, checked === true)} aria-label={t("common.selectItem", { name: model.publicId })} /> @@ -298,8 +301,8 @@ export function ModelsPage() { - ))} - + )} /> + )}
) : null} diff --git a/frontend/src/shared/components/pagination.tsx b/frontend/src/shared/components/pagination.tsx index aa8eb504..b2830129 100644 --- a/frontend/src/shared/components/pagination.tsx +++ b/frontend/src/shared/components/pagination.tsx @@ -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: {t("common.rows")} diff --git a/frontend/src/shared/components/virtual-table-body.tsx b/frontend/src/shared/components/virtual-table-body.tsx new file mode 100644 index 00000000..1dcb3832 --- /dev/null +++ b/frontend/src/shared/components/virtual-table-body.tsx @@ -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 = { + 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({ items, colSpan, rowHeight, renderRow, overscan = DEFAULT_OVERSCAN }: VirtualTableBodyProps) { + const bodyRef = useRef(null); + const frameRef = useRef(null); + const enabled = items.length > MIN_VIRTUALIZED_ROWS; + const [range, setRange] = useState(() => ({ 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("[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("[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 ( + + {topHeight > 0 ? : null} + {visibleItems.map((item, index) => renderRow(item, safeStart + index))} + {bottomHeight > 0 ? : null} + + ); +} + +function VirtualSpacer({ colSpan, height }: { colSpan: number; height: number }) { + return ( + + ); +}