Files
new-api/web/default/src/features/system-settings/models/channel-selector-dialog.tsx
T
QuentinHsu 6f415428d3 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.
2026-06-11 02:36:41 +08:00

351 lines
10 KiB
TypeScript
Vendored

/*
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 { useCallback, useEffect, useMemo, useState } from 'react'
import { type ColumnDef, type RowSelectionState } from '@tanstack/react-table'
import { Search } from 'lucide-react'
import { useTranslation } from 'react-i18next'
import { Button } from '@/components/ui/button'
import { Checkbox } from '@/components/ui/checkbox'
import { Input } from '@/components/ui/input'
import {
Select,
SelectContent,
SelectGroup,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/components/ui/select'
import {
DataTablePagination,
DataTableView,
useDataTable,
} from '@/components/data-table'
import { Dialog } from '@/components/dialog'
import { StatusBadge } from '@/components/status-badge'
import type { UpstreamChannel } from '../types'
import {
CHANNEL_STATUS_CONFIG,
DEFAULT_ENDPOINT,
ENDPOINT_OPTIONS,
MODELS_DEV_PRESET_ID,
OFFICIAL_CHANNEL_ID,
} from './constants'
type ChannelSelectorDialogProps = {
open: boolean
onOpenChange: (open: boolean) => void
channels: UpstreamChannel[]
selectedChannelIds: number[]
onSelectedChannelIdsChange: (ids: number[]) => void
channelEndpoints: Record<number, string>
onChannelEndpointsChange: (endpoints: Record<number, string>) => void
onConfirm: (selectedIds: number[]) => void
}
// Synthesized presets from `controller/ratio_sync.go` always carry stable
// negative IDs, so matching by ID alone is reliable and self-documenting.
function isOfficialChannel(channel: UpstreamChannel): boolean {
return (
channel.id === OFFICIAL_CHANNEL_ID || channel.id === MODELS_DEV_PRESET_ID
)
}
export function ChannelSelectorDialog({
open,
onOpenChange,
channels,
selectedChannelIds,
onSelectedChannelIdsChange,
channelEndpoints,
onChannelEndpointsChange,
onConfirm,
}: ChannelSelectorDialogProps) {
const { t } = useTranslation()
const [search, setSearch] = useState('')
const [rowSelection, setRowSelection] = useState<RowSelectionState>({})
useEffect(() => {
if (!selectedChannelIds.length) {
setRowSelection({})
return
}
const availableChannelIds = new Set(channels.map((channel) => channel.id))
const newSelection: RowSelectionState = {}
selectedChannelIds.forEach((id) => {
if (availableChannelIds.has(id)) {
newSelection[id.toString()] = true
}
})
setRowSelection(newSelection)
}, [selectedChannelIds, channels])
const updateEndpoint = useCallback(
(channelId: number, endpoint: string) => {
onChannelEndpointsChange({
...channelEndpoints,
[channelId]: endpoint,
})
},
[channelEndpoints, onChannelEndpointsChange]
)
const getEndpointType = (endpoint: string) => {
const option = ENDPOINT_OPTIONS.find((opt) => opt.value === endpoint)
return option ? endpoint : 'custom'
}
const columns = useMemo<ColumnDef<UpstreamChannel>[]>(
() => [
{
id: 'select',
header: ({ table }) => (
<Checkbox
checked={table.getIsAllPageRowsSelected()}
indeterminate={table.getIsSomePageRowsSelected()}
onCheckedChange={(value) =>
table.toggleAllPageRowsSelected(!!value)
}
aria-label='Select all'
/>
),
cell: ({ row }) => (
<Checkbox
checked={row.getIsSelected()}
onCheckedChange={(value) => row.toggleSelected(!!value)}
aria-label='Select row'
/>
),
enableSorting: false,
enableHiding: false,
},
{
accessorKey: 'name',
header: t('Name'),
cell: ({ row }) => {
const name = row.getValue('name') as string
const channel = row.original
const isOfficial = isOfficialChannel(channel)
return (
<div className='flex items-center gap-2'>
<span className='font-medium'>{name}</span>
{isOfficial && (
<StatusBadge
label={t('Official')}
variant='success'
size='sm'
copyable={false}
/>
)}
</div>
)
},
},
{
accessorKey: 'base_url',
header: t('Base URL'),
cell: ({ row }) => {
const url = row.getValue('base_url') as string
return (
<span
className='text-muted-foreground block max-w-xs truncate font-mono text-xs'
title={url}
>
{url}
</span>
)
},
},
{
accessorKey: 'status',
header: t('Status'),
cell: ({ row }) => {
const status = row.getValue('status') as number
const config =
CHANNEL_STATUS_CONFIG[status as keyof typeof CHANNEL_STATUS_CONFIG]
if (!config) {
return (
<StatusBadge
label={t('Unknown')}
variant='neutral'
size='sm'
copyable={false}
/>
)
}
return (
<StatusBadge
label={config.label}
variant={config.variant}
size='sm'
copyable={false}
/>
)
},
},
{
id: 'endpoint',
header: t('Sync Endpoint'),
cell: ({ row }) => {
const channel = row.original
const currentEndpoint =
channelEndpoints[channel.id] || DEFAULT_ENDPOINT
const endpointType = getEndpointType(currentEndpoint)
const handleTypeChange = (value: string) => {
if (value === 'custom') {
updateEndpoint(channel.id, '')
} else {
updateEndpoint(channel.id, value)
}
}
return (
<div className='flex items-center gap-2'>
<Select
items={[
...ENDPOINT_OPTIONS.map((option) => ({
value: option.value,
label: option.label,
})),
]}
value={endpointType}
onValueChange={(v) => v !== null && handleTypeChange(v)}
>
<SelectTrigger className='h-8 w-32'>
<SelectValue />
</SelectTrigger>
<SelectContent alignItemWithTrigger={false}>
<SelectGroup>
{ENDPOINT_OPTIONS.map((option) => (
<SelectItem key={option.value} value={option.value}>
{option.label}
</SelectItem>
))}
</SelectGroup>
</SelectContent>
</Select>
{endpointType === 'custom' && (
<Input
value={currentEndpoint}
onChange={(e) => updateEndpoint(channel.id, e.target.value)}
placeholder={t('/your/endpoint')}
className='h-8 w-40 font-mono text-xs'
/>
)}
</div>
)
},
},
],
[channelEndpoints, t, updateEndpoint]
)
const filteredChannels = useMemo(() => {
if (!search.trim()) return channels
const searchLower = search.toLowerCase()
return channels.filter(
(ch) =>
ch.name.toLowerCase().includes(searchLower) ||
ch.base_url.toLowerCase().includes(searchLower)
)
}, [channels, search])
const sortedChannels = useMemo(() => {
return [...filteredChannels].sort((a, b) => {
const aIsOfficial = isOfficialChannel(a)
const bIsOfficial = isOfficialChannel(b)
if (aIsOfficial && !bIsOfficial) return -1
if (!aIsOfficial && bIsOfficial) return 1
return 0
})
}, [filteredChannels])
const { table } = useDataTable({
data: sortedChannels,
columns,
rowSelection,
getRowId: (row) => row.id.toString(),
enableRowSelection: true,
onRowSelectionChange: setRowSelection,
initialPagination: { pageIndex: 0, pageSize: 10 },
withSortedRowModel: false,
withFacetedRowModel: false,
})
const handleConfirm = () => {
const selectedRows = table.getSelectedRowModel().rows
const selectedIds = selectedRows.map((row) => row.original.id)
onSelectedChannelIdsChange(selectedIds)
onOpenChange(false)
onConfirm(selectedIds)
}
return (
<Dialog
open={open}
onOpenChange={onOpenChange}
title={t('Select Sync Channels')}
description={t(
'Choose channels to sync upstream ratio configurations from'
)}
contentClassName='flex max-h-[90vh] max-w-[calc(100%-2rem)] flex-col sm:max-w-[90vw] xl:max-w-[1400px]'
contentHeight='min(72vh, 720px)'
bodyClassName='space-y-4'
footer={
<>
<Button variant='outline' onClick={() => onOpenChange(false)}>
{t('Cancel')}
</Button>
<Button onClick={handleConfirm}>{t('Confirm Selection')}</Button>
</>
}
>
<div className='flex flex-1 flex-col gap-4 overflow-hidden'>
<div className='flex items-center gap-2'>
<div className='relative flex-1'>
<Search className='text-muted-foreground absolute top-1/2 left-2 h-4 w-4 -translate-y-1/2' />
<Input
placeholder={t('Search by name or URL...')}
value={search}
onChange={(e) => setSearch(e.target.value)}
className='ps-8'
/>
</div>
</div>
<DataTableView
table={table}
containerClassName='flex-1 overflow-auto rounded-md'
emptyContent={t('No channels found')}
emptyCellClassName='h-24 text-center'
/>
<DataTablePagination table={table} />
</div>
</Dialog>
)
}