perf(web): improve frontend table rendering and pinned columns/UI table (#5405)
* refactor(web): centralize data table implementation - route all TanStack table setup through a shared data-table hook to remove repeated state and row model wiring. - move table rendering, static table wrappers, empty states, and primitive exports behind the data-table module. - update feature tables and configuration editors to share the same table UX while preserving their existing workflows. * refactor(web): trim data table public API - remove unused data-table exports and dead static table helper types. - keep internal table header, skeleton, empty state, and faceted filter helpers private to the data-table module. - route feature imports through the data-table barrel to avoid subpath coupling. * refactor(web): unify table rendering components - centralize static table headers, bodies, empty states, and shared class names behind the data-table package. - migrate settings, pricing, channel, key, subscription, and model tables to the shared table APIs. - remove data-table exports for low-level table primitives so feature code uses one supported abstraction. * perf(web): keep list tables fixed within page content - make shared data table pages fill available height and scroll row data inside the table body. - add a fixed content layout mode so selected list pages avoid page-level scrolling. - apply the fixed table behavior to keys, logs, channels, models, users, redemptions, and subscriptions. * perf(web): refine table pagination controls - show total row counts instead of redundant page range text. - tighten visible page buttons so pagination fits constrained table widths. - align pagination controls and tune text hierarchy for clearer scanning. * perf(web): stabilize model pricing table columns - keep model pricing columns at fixed widths so headers do not collapse in narrow layouts. - truncate long model names and pricing summaries within their cells instead of squeezing adjacent columns. * refactor(web): simplify data table rendering internals - split table body rendering into focused helpers for loading, empty, and row states. - extract static table row and cell class resolution to reduce branching in the main component. - reuse a single pagination page-size option list to avoid duplicated constants. * perf(pricing): reduce dynamic pricing table render work - reuse dynamic pricing field metadata instead of rebuilding it inside table columns. - precompute formatted dynamic prices per tier and group to avoid repeated entry mapping for each cell. - simplify select option construction in related dialogs while preserving the same choices. * refactor(web): streamline pricing table rendering - reuse translated endpoint select options between trigger data and menu items. - precompute dynamic pricing maps per group so table cells only resolve formatted values. - add local dynamic pricing type aliases to keep helper signatures readable. * refactor(web): merge pricing table imports * refactor(web): merge upstream ratio table imports * refactor(web): merge channel selector table imports * refactor(web): simplify tiered pricing select items * refactor(web): reuse model ratio row state * refactor(web): rely on table view row defaults * refactor(web): reuse pagination state values * refactor(web): hoist pagination size select items * refactor(web): clarify static table body rows * refactor(web): extract table page pagination rendering * fix(web): remove direct hast type dependency - rely on Shiki transformer contextual typing for line nodes. - allow frontend typecheck to pass without an undeclared hast package. * refactor(web): trim data table hook return API - return only the TanStack table instance from useDataTable. - keep internal state handling private because callers do not consume it directly. * refactor(web): keep static table empty row private - stop exporting the internal StaticDataTableEmptyRow helper. - keep the public static table API focused on the table component and column type. * refactor(web): hide data table view props from barrel * refactor(web): remove stale long text lint override * fix(web): keep pinned table columns opaque - apply pinned column background classes after custom column classes. - use an opaque hover background so scrolled content cannot show through fixed cells. * refactor(data-table): organize shared table components - group table primitives, page composition, toolbar controls, static tables, and hooks by responsibility. - split shared view types, row rendering, header rendering, and pinned-column styling out of the main table view. - keep the public data-table barrel stable while documenting the new ownership boundaries. * fix(web): stabilize split table column sizing - derive default colgroup widths from visible columns when split headers or header sizing are enabled. - apply a fixed table layout with computed minimum width so header and body columns stay aligned. - keep split-header containers from leaking horizontal overflow and avoid extra pinned-column borders. * fix(web): set stable table utility column widths - assign fixed widths to selection columns so shared colgroup sizing keeps checkbox cells compact. - size id columns in redemption and user tables to keep split headers aligned with body rows. * fix(web): align model metadata icon cells - render compact provider avatars in the metadata icon column instead of wide wordmarks. - position icons in a fixed-size wrapper so they line up with the existing icon header alignment. * fix(status-badge): hide status dot by default * fix(web): prevent user invite info overlap - give the invite info and created-at columns explicit widths so table sizing reserves enough space. - allow invite badges to wrap within the cell instead of spilling into adjacent columns. * perf(data-table): cache pinned column class resolution - reuse the pinned column lookup while table props stay stable to reduce repeated per-render work. - share the resolved column class handler across unified and split-header table layouts. - localize page-number screen reader labels so pagination remains accessible in every locale. * refactor(data-table): tighten static table modes - make StaticDataTable distinguish data-driven and children-only usage through explicit prop shapes. - remove unsupported columns-without-data fallback after confirming no repository callers rely on it. - default manual table modes away from unused local row models to reduce repeated table work. * fix(data-table): make pinned edit column opaque - use an opaque muted background for the active action column so sticky cells do not reveal scrolled content underneath. * fix(data-table): prevent narrow column overlap - apply stable header sizing to remaining desktop data table pages so constrained layouts scroll instead of compressing cells. - add explicit widths for key, quota, badge, and timestamp columns that contain fixed-format content. - constrain masked values and timestamp cells with truncation to keep content inside its assigned column. * fix(table): align table cell content with headers - remove extra inline padding from masked table text buttons so values start at the cell edge. - tag status badges and offset leading badges inside table cells to match header text alignment. * fix(table): prevent admin list column overflow - widen redemption and subscription table columns so masked codes, timestamps, and localized headers fit. - localize subscription ID headers and add Received amount translations across supported locales. * fix(provider-badge): unify provider icon spacing - add a shared provider badge component for icon and status label layout. - reuse it in channel type and model vendor columns so OpenAI icons align consistently.
This commit is contained in:
@@ -0,0 +1,393 @@
|
||||
/*
|
||||
Copyright (C) 2023-2026 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
import * as React from 'react'
|
||||
import { useState, type ReactNode } from 'react'
|
||||
import { type Table } from '@tanstack/react-table'
|
||||
import { ChevronDown, Loader2, X as Cross2Icon } from 'lucide-react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { useDebounce } from '@/hooks'
|
||||
import { cn } from '@/lib/utils'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { DataTableFacetedFilter } from './faceted-filter'
|
||||
import { DataTableViewOptions } from './view-options'
|
||||
|
||||
type FilterDef = {
|
||||
columnId: string
|
||||
title: string
|
||||
options: {
|
||||
label: string
|
||||
value: string
|
||||
icon?: React.ComponentType<{ className?: string }>
|
||||
iconNode?: React.ReactNode
|
||||
count?: number
|
||||
}[]
|
||||
singleSelect?: boolean
|
||||
}
|
||||
|
||||
export type DataTableToolbarProps<TData> = {
|
||||
table: Table<TData>
|
||||
/**
|
||||
* Placeholder for the default search input. Defaults to `t('Filter...')`.
|
||||
*/
|
||||
searchPlaceholder?: string
|
||||
/**
|
||||
* Delay committing the default search input. Defaults to immediate updates.
|
||||
*/
|
||||
searchDebounceMs?: number
|
||||
/**
|
||||
* Column id to filter on. When provided, the search input filters
|
||||
* a specific column. When omitted, the search input updates the
|
||||
* table's `globalFilter`.
|
||||
*/
|
||||
searchKey?: string
|
||||
/**
|
||||
* Column-level filter chips (faceted multi-select / single-select).
|
||||
*/
|
||||
filters?: FilterDef[]
|
||||
/**
|
||||
* Replaces the default search input entirely. Use when the primary
|
||||
* "search" is something custom — e.g. a date-time range picker.
|
||||
*/
|
||||
customSearch?: ReactNode
|
||||
/**
|
||||
* Extra inputs/selects displayed in the primary row alongside the
|
||||
* search input and filter chips.
|
||||
*/
|
||||
additionalSearch?: ReactNode
|
||||
/**
|
||||
* Whether non-table filters (e.g. `additionalSearch` or `expandable`
|
||||
* inputs) are currently active. Controls Reset button visibility
|
||||
* when no column filters are set.
|
||||
*/
|
||||
hasAdditionalFilters?: boolean
|
||||
/**
|
||||
* Callback invoked when the user clicks Reset.
|
||||
*/
|
||||
onReset?: () => void
|
||||
/**
|
||||
* Additional filter inputs hidden behind an Expand/Collapse toggle.
|
||||
* Inputs flow inline with the primary row when expanded.
|
||||
*/
|
||||
expandable?: ReactNode
|
||||
/**
|
||||
* When `expandable` is collapsed, highlights the toggle if any of
|
||||
* the expandable inputs currently hold a value.
|
||||
*/
|
||||
hasExpandedActiveFilters?: boolean
|
||||
/**
|
||||
* Custom action buttons rendered BEFORE the built-in
|
||||
* Reset / Search / View buttons.
|
||||
*/
|
||||
preActions?: ReactNode
|
||||
/**
|
||||
* Explicit "Search" / "Apply" callback. When provided the toolbar
|
||||
* shows a primary Search button. Filters are committed only on click
|
||||
* (form-mode workflow).
|
||||
*/
|
||||
onSearch?: () => void
|
||||
/**
|
||||
* Loading state for the explicit Search button.
|
||||
*/
|
||||
searchLoading?: boolean
|
||||
/**
|
||||
* Hide the View Options (column visibility) dropdown.
|
||||
*/
|
||||
hideViewOptions?: boolean
|
||||
/**
|
||||
* Content rendered on the LEFT side of the secondary action row. When
|
||||
* provided the toolbar splits into two visual rows:
|
||||
* Row 1: search inputs / filter chips …… Expand
|
||||
* Row 2: expanded filters
|
||||
* Row 3: leftActions …… Reset / Search / ViewOptions
|
||||
*/
|
||||
leftActions?: ReactNode
|
||||
/**
|
||||
* Outer wrapper className override.
|
||||
*/
|
||||
className?: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Unified data-table filter panel — Ant Design Pro inspired.
|
||||
*
|
||||
* Layout (single flex-wrap row):
|
||||
* - Filters (search input + additional inputs + filter chips + expandable
|
||||
* inputs) flow horizontally and wrap as needed.
|
||||
* - The action cluster (Reset / Search / View / Expand) hugs the right
|
||||
* edge via `ms-auto`. When filters fill a row, the cluster naturally
|
||||
* wraps to the next line — still right-aligned — matching the
|
||||
* collapsed/expanded states from the user's reference design.
|
||||
*
|
||||
* No background panel, no row separators — relies on whitespace and the
|
||||
* adjacent table border for visual hierarchy.
|
||||
*/
|
||||
export function DataTableToolbar<TData>(props: DataTableToolbarProps<TData>) {
|
||||
const { t } = useTranslation()
|
||||
const [expanded, setExpanded] = useState(false)
|
||||
const isSearchComposingRef = React.useRef(false)
|
||||
const lastCommittedSearchValueRef = React.useRef('')
|
||||
|
||||
const filters = props.filters ?? []
|
||||
const hasExpandable = props.expandable != null
|
||||
const hasSearch = props.onSearch != null
|
||||
|
||||
const isFiltered =
|
||||
props.table.getState().columnFilters.length > 0 ||
|
||||
!!props.table.getState().globalFilter ||
|
||||
!!props.hasAdditionalFilters
|
||||
|
||||
const placeholder = props.searchPlaceholder ?? t('Filter...')
|
||||
const currentSearchValue = props.searchKey
|
||||
? ((props.table.getColumn(props.searchKey)?.getFilterValue() as string) ??
|
||||
'')
|
||||
: ((props.table.getState().globalFilter as string | undefined) ?? '')
|
||||
|
||||
const [searchValue, setSearchValue] = useState(currentSearchValue)
|
||||
const [pendingSearchValue, setPendingSearchValue] =
|
||||
useState(currentSearchValue)
|
||||
const searchDebounceMs = Math.max(0, props.searchDebounceMs ?? 0)
|
||||
const debouncedSearchValue = useDebounce(
|
||||
pendingSearchValue,
|
||||
searchDebounceMs
|
||||
)
|
||||
|
||||
React.useEffect(() => {
|
||||
lastCommittedSearchValueRef.current = currentSearchValue
|
||||
if (!isSearchComposingRef.current) {
|
||||
setSearchValue(currentSearchValue)
|
||||
}
|
||||
setPendingSearchValue(currentSearchValue)
|
||||
}, [currentSearchValue])
|
||||
|
||||
const commitSearchValue = React.useCallback(
|
||||
(value: string) => {
|
||||
if (value === lastCommittedSearchValueRef.current) {
|
||||
return
|
||||
}
|
||||
|
||||
lastCommittedSearchValueRef.current = value
|
||||
|
||||
if (props.searchKey) {
|
||||
props.table.getColumn(props.searchKey)?.setFilterValue(value)
|
||||
return
|
||||
}
|
||||
|
||||
props.table.setGlobalFilter(value)
|
||||
},
|
||||
[props.searchKey, props.table]
|
||||
)
|
||||
|
||||
React.useEffect(() => {
|
||||
if (
|
||||
searchDebounceMs <= 0 ||
|
||||
isSearchComposingRef.current ||
|
||||
debouncedSearchValue !== pendingSearchValue
|
||||
) {
|
||||
return
|
||||
}
|
||||
|
||||
commitSearchValue(debouncedSearchValue)
|
||||
}, [
|
||||
commitSearchValue,
|
||||
debouncedSearchValue,
|
||||
pendingSearchValue,
|
||||
searchDebounceMs,
|
||||
])
|
||||
|
||||
const queueSearchValue = (value: string) => {
|
||||
setPendingSearchValue(value)
|
||||
|
||||
if (searchDebounceMs <= 0) {
|
||||
commitSearchValue(value)
|
||||
}
|
||||
}
|
||||
|
||||
const handleSearchChange = (event: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const value = event.target.value
|
||||
setSearchValue(value)
|
||||
|
||||
if (!isSearchComposingRef.current) {
|
||||
queueSearchValue(value)
|
||||
}
|
||||
}
|
||||
|
||||
const handleSearchCompositionStart = () => {
|
||||
isSearchComposingRef.current = true
|
||||
}
|
||||
|
||||
const handleSearchCompositionEnd = (
|
||||
event: React.CompositionEvent<HTMLInputElement>
|
||||
) => {
|
||||
isSearchComposingRef.current = false
|
||||
const value = event.currentTarget.value
|
||||
setSearchValue(value)
|
||||
queueSearchValue(value)
|
||||
}
|
||||
|
||||
const searchInput = props.searchKey ? (
|
||||
<Input
|
||||
placeholder={placeholder}
|
||||
value={searchValue}
|
||||
onChange={handleSearchChange}
|
||||
onCompositionStart={handleSearchCompositionStart}
|
||||
onCompositionEnd={handleSearchCompositionEnd}
|
||||
className='w-full sm:w-[200px] lg:w-[240px]'
|
||||
/>
|
||||
) : (
|
||||
<Input
|
||||
placeholder={placeholder}
|
||||
value={searchValue}
|
||||
onChange={handleSearchChange}
|
||||
onCompositionStart={handleSearchCompositionStart}
|
||||
onCompositionEnd={handleSearchCompositionEnd}
|
||||
className='w-full sm:w-[200px] lg:w-[240px]'
|
||||
/>
|
||||
)
|
||||
|
||||
const filterChips = filters.map((filter) => {
|
||||
const column = props.table.getColumn(filter.columnId)
|
||||
if (!column) return null
|
||||
return (
|
||||
<DataTableFacetedFilter
|
||||
key={filter.columnId}
|
||||
column={column}
|
||||
title={filter.title}
|
||||
options={filter.options}
|
||||
singleSelect={filter.singleSelect}
|
||||
/>
|
||||
)
|
||||
})
|
||||
|
||||
const handleReset = () => {
|
||||
isSearchComposingRef.current = false
|
||||
setSearchValue('')
|
||||
setPendingSearchValue('')
|
||||
lastCommittedSearchValueRef.current = ''
|
||||
props.table.resetColumnFilters()
|
||||
props.table.setGlobalFilter('')
|
||||
props.onReset?.()
|
||||
}
|
||||
|
||||
// Reset: outline text-only for form mode (always visible, disabled when
|
||||
// nothing to reset); ghost text + X for filter-as-you-type mode (only
|
||||
// visible when active filters exist).
|
||||
const resetButton = hasSearch ? (
|
||||
<Button variant='outline' onClick={handleReset} disabled={!isFiltered}>
|
||||
{t('Reset')}
|
||||
</Button>
|
||||
) : isFiltered ? (
|
||||
<Button
|
||||
variant='ghost'
|
||||
onClick={handleReset}
|
||||
className='text-muted-foreground hover:text-foreground gap-1 px-2'
|
||||
>
|
||||
{t('Reset')}
|
||||
<Cross2Icon />
|
||||
</Button>
|
||||
) : null
|
||||
|
||||
const searchButton = hasSearch ? (
|
||||
<Button onClick={props.onSearch} disabled={props.searchLoading}>
|
||||
{props.searchLoading && <Loader2 className='animate-spin' />}
|
||||
{t('Search')}
|
||||
</Button>
|
||||
) : null
|
||||
|
||||
const viewOptionsNode = !props.hideViewOptions ? (
|
||||
<DataTableViewOptions table={props.table} />
|
||||
) : null
|
||||
|
||||
const expandToggle = hasExpandable ? (
|
||||
<Button
|
||||
variant='ghost'
|
||||
onClick={() => setExpanded((p) => !p)}
|
||||
aria-expanded={expanded}
|
||||
className={cn(
|
||||
'text-muted-foreground hover:text-foreground gap-1 px-2',
|
||||
props.hasExpandedActiveFilters &&
|
||||
!expanded &&
|
||||
'text-primary hover:text-primary'
|
||||
)}
|
||||
>
|
||||
{expanded ? t('Collapse') : t('Expand')}
|
||||
<ChevronDown
|
||||
className={cn(
|
||||
'size-3.5 transition-transform duration-200',
|
||||
expanded && 'rotate-180'
|
||||
)}
|
||||
/>
|
||||
</Button>
|
||||
) : null
|
||||
|
||||
const hasLeftActions = props.leftActions != null
|
||||
|
||||
if (hasLeftActions) {
|
||||
return (
|
||||
<div className={cn('flex flex-col gap-2', props.className)}>
|
||||
<div className='flex flex-wrap items-center gap-2 sm:gap-3'>
|
||||
{props.customSearch !== undefined ? props.customSearch : searchInput}
|
||||
{props.additionalSearch}
|
||||
{filterChips}
|
||||
<div className='ms-auto flex shrink-0 items-center gap-1.5 sm:gap-2'>
|
||||
{expandToggle}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{expanded && hasExpandable && (
|
||||
<div className='flex flex-wrap items-center gap-2 sm:gap-3'>
|
||||
{props.expandable}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className='flex flex-wrap items-center gap-2 sm:gap-3'>
|
||||
{props.leftActions}
|
||||
<div className='ms-auto flex shrink-0 items-center gap-1.5 sm:gap-2'>
|
||||
{props.preActions}
|
||||
{resetButton}
|
||||
{searchButton}
|
||||
{viewOptionsNode}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
'flex flex-wrap items-center gap-2 sm:gap-3',
|
||||
props.className
|
||||
)}
|
||||
>
|
||||
{props.customSearch !== undefined ? props.customSearch : searchInput}
|
||||
{props.additionalSearch}
|
||||
{filterChips}
|
||||
{expanded && hasExpandable && props.expandable}
|
||||
|
||||
<div className='ms-auto flex shrink-0 items-center gap-1.5 sm:gap-2'>
|
||||
{props.preActions}
|
||||
{resetButton}
|
||||
{searchButton}
|
||||
{viewOptionsNode}
|
||||
{expandToggle}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
Reference in New Issue
Block a user