feat(clients): let the admin choose which table columns to show (#7080)

On a laptop-width screen the Clients table is wider than the window, and columns such as Speed or Attached inbounds take width even when they show nothing useful.

Add a Columns menu beside Filter that hides any column except the client itself. The choice is kept in localStorage, the menu stays open while several columns are ticked, and the table sizes to its visible columns instead of a fixed 1200px.
This commit is contained in:
Mohammad
2026-11-24 02:47:28 -08:00
committed by GitHub
parent 84d04c2d92
commit 5b71e534d2
19 changed files with 274 additions and 2 deletions
@@ -0,0 +1,58 @@
import { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Button, Checkbox, Dropdown } from 'antd';
import { TableOutlined } from '@ant-design/icons';
import type { ClientColumnOption, HideableClientColumn } from './columnVisibility';
interface ClientColumnPickerProps {
options: ClientColumnOption[];
hidden: HideableClientColumn[];
onChange: (hidden: HideableClientColumn[]) => void;
}
export default function ClientColumnPicker({ options, hidden, onChange }: ClientColumnPickerProps) {
const { t } = useTranslation();
const [open, setOpen] = useState(false);
const toggle = (key: string) => {
const option = options.find((o) => o.key === key);
if (!option) return;
onChange(
hidden.includes(option.key)
? hidden.filter((k) => k !== option.key)
: [...hidden, option.key],
);
};
return (
<Dropdown
trigger={['click']}
open={open}
autoFocus
// Ticking a column must not close the menu; only the trigger or an outside click does.
onOpenChange={(next, info) => {
if (next || info.source === 'trigger') setOpen(next);
}}
menu={{
items: options.map((o) => ({
key: o.key,
label: (
<Checkbox
checked={!hidden.includes(o.key)}
tabIndex={-1}
className="column-picker-check"
>
{o.label}
</Checkbox>
),
})),
onClick: ({ key }) => toggle(key),
}}
>
<Button icon={<TableOutlined aria-hidden />} aria-haspopup="menu" aria-expanded={open}>
{t('pages.clients.columns')}
</Button>
</Dropdown>
);
}
@@ -380,3 +380,8 @@
border-color: var(--ant-color-error-border);
background: var(--ant-color-error-bg);
}
/* The menu item owns the click, so the box only shows the state. */
.column-picker-check {
pointer-events: none;
}
+19 -2
View File
@@ -93,6 +93,8 @@ const BulkDetachInboundsModal = lazy(() => import('./BulkDetachInboundsModal'));
const TextModal = lazy(() => import('@/components/feedback/TextModal'));
const PromptModal = lazy(() => import('@/components/feedback/PromptModal'));
import { ClientInboundChips, ClientRowActions } from './RowCells';
import ClientColumnPicker from './ClientColumnPicker';
import { clientColumnOptions, hideClientColumns, useHiddenClientColumns } from './columnVisibility';
import { emptyFilters, activeFilterCount } from './filters';
import type { ClientFilters } from './filters';
import './ClientsPage.css';
@@ -1055,7 +1057,7 @@ export default function ClientsPage() {
if (pag?.pageSize) setPageSizeChoice(pag.pageSize);
};
const columns = useMemo<ColumnsType<ClientRecord>>(
const baseColumns = useMemo<ColumnsType<ClientRecord>>(
() => [
{
title: t('pages.clients.actions'),
@@ -1241,6 +1243,14 @@ export default function ClientsPage() {
],
);
const [hiddenColumns, setHiddenColumns] = useHiddenClientColumns();
const columnOptions = useMemo(() => clientColumnOptions(baseColumns), [baseColumns]);
const columns = useMemo(
() => hideClientColumns(baseColumns, hiddenColumns),
[baseColumns, hiddenColumns],
);
const rowClassName = useCallback(
(record: ClientRecord) => {
const bucket = clientBucket(record);
@@ -1568,6 +1578,13 @@ export default function ClientsPage() {
{!isMobile && t('filter')}
</Button>
</Badge>
{!isMobile && (
<ClientColumnPicker
options={columnOptions}
hidden={hiddenColumns}
onChange={setHiddenColumns}
/>
)}
<Select
value={sortValueFor(sortColumn, sortOrder)}
aria-label={t('sort')}
@@ -1721,7 +1738,7 @@ export default function ClientsPage() {
rowClassName={rowClassName}
pagination={tablePagination}
size="small"
scroll={{ x: 1200 }}
scroll={{ x: 'max-content' }}
onChange={onTableChange}
locale={{
emptyText: (
@@ -0,0 +1,69 @@
import { useCallback, useState } from 'react';
import type { ReactNode } from 'react';
import type { ColumnsType } from 'antd/es/table';
const HIDDEN_COLUMNS_KEY = 'clientsHiddenColumns';
// The client (email) column is deliberately absent: hiding it would leave rows
// with nothing to tell them apart.
const HIDEABLE_CLIENT_COLUMNS = [
'actions',
'enable',
'online',
'group',
'inboundIds',
'traffic',
'speed',
'remaining',
'expiryTime',
] as const;
export type HideableClientColumn = (typeof HIDEABLE_CLIENT_COLUMNS)[number];
function isHideableClientColumn(key: unknown): key is HideableClientColumn {
return (HIDEABLE_CLIENT_COLUMNS as readonly unknown[]).includes(key);
}
export interface ClientColumnOption {
key: HideableClientColumn;
label: ReactNode;
}
// A column already hidden for its own reason (Group with no groups defined) is
// not offered: toggling it would do nothing visible.
export function clientColumnOptions<T>(columns: ColumnsType<T>): ClientColumnOption[] {
return columns.flatMap((column) =>
isHideableClientColumn(column.key) && !column.hidden && typeof column.title !== 'function'
? [{ key: column.key, label: column.title }]
: [],
);
}
export function hideClientColumns<T>(
columns: ColumnsType<T>,
hidden: readonly HideableClientColumn[],
): ColumnsType<T> {
return columns.map((column) =>
isHideableClientColumn(column.key) && hidden.includes(column.key)
? { ...column, hidden: true }
: column,
);
}
function readHiddenClientColumns(): HideableClientColumn[] {
try {
const raw: unknown = JSON.parse(localStorage.getItem(HIDDEN_COLUMNS_KEY) || '[]');
return Array.isArray(raw) ? raw.filter(isHideableClientColumn) : [];
} catch {
return [];
}
}
export function useHiddenClientColumns() {
const [hidden, setHiddenState] = useState<HideableClientColumn[]>(readHiddenClientColumns);
const setHidden = useCallback((next: HideableClientColumn[]) => {
setHiddenState(next);
localStorage.setItem(HIDDEN_COLUMNS_KEY, JSON.stringify(next));
}, []);
return [hidden, setHidden] as const;
}
@@ -0,0 +1,109 @@
import { useMemo } from 'react';
import { Table } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import { fireEvent, render, screen, within } from '@testing-library/react';
import { afterEach, describe, expect, it } from 'vitest';
import ClientColumnPicker from '@/pages/clients/ClientColumnPicker';
import {
clientColumnOptions,
hideClientColumns,
useHiddenClientColumns,
} from '@/pages/clients/columnVisibility';
interface Row {
email: string;
}
function ClientsTable({ hasGroups = true }: { hasGroups?: boolean }) {
const [hidden, setHidden] = useHiddenClientColumns();
const base = useMemo<ColumnsType<Row>>(
() => [
{ title: 'Client', key: 'email', dataIndex: 'email' },
{ title: 'Group', key: 'group', hidden: !hasGroups, render: () => 'g' },
{ title: 'Speed', key: 'speed', render: () => '—' },
{ title: 'Remaining', key: 'remaining', render: () => '1 GB' },
],
[hasGroups],
);
return (
<>
<ClientColumnPicker
options={clientColumnOptions(base)}
hidden={hidden}
onChange={setHidden}
/>
<Table<Row>
rowKey="email"
columns={hideClientColumns(base, hidden)}
dataSource={[{ email: 'alice' }]}
pagination={false}
/>
</>
);
}
function headers(): string[] {
return Array.from(document.querySelectorAll('thead th')).map((th) => th.textContent ?? '');
}
function openPicker(): HTMLElement {
fireEvent.click(screen.getByRole('button', { name: /Columns/ }));
return document.querySelector('.ant-dropdown') as HTMLElement;
}
function tick(menu: HTMLElement, label: string) {
fireEvent.click(within(menu).getByRole('checkbox', { name: label }));
}
afterEach(() => {
localStorage.clear();
});
describe('clients column picker', () => {
it('keeps a column the admin hid hidden on the next visit', () => {
const first = render(<ClientsTable />);
tick(openPicker(), 'Speed');
expect(headers()).toEqual(['Client', 'Group', 'Remaining']);
first.unmount();
render(<ClientsTable />);
expect(headers()).toEqual(['Client', 'Group', 'Remaining']);
});
it('stays open while columns are ticked, so several can be changed in one go', () => {
render(<ClientsTable />);
const menu = openPicker();
tick(menu, 'Speed');
tick(menu, 'Remaining');
expect(menu.classList.contains('ant-dropdown-hidden')).toBe(false);
expect(headers()).toEqual(['Client', 'Group']);
});
it('never hides or offers the client column, even from a tampered stored value', () => {
localStorage.setItem('clientsHiddenColumns', JSON.stringify(['email', 'speed', 'gone']));
render(<ClientsTable />);
expect(headers()).toEqual(['Client', 'Group', 'Remaining']);
expect(within(openPicker()).queryByRole('checkbox', { name: 'Client' })).toBeNull();
});
it('falls back to all columns when the stored value is not valid JSON', () => {
localStorage.setItem('clientsHiddenColumns', '{not json');
render(<ClientsTable />);
expect(headers()).toEqual(['Client', 'Group', 'Speed', 'Remaining']);
});
it('keeps Group hidden through edits made while no groups exist', () => {
localStorage.setItem('clientsHiddenColumns', JSON.stringify(['group']));
const noGroups = render(<ClientsTable hasGroups={false} />);
const menu = openPicker();
expect(within(menu).queryByRole('checkbox', { name: 'Group' })).toBeNull();
tick(menu, 'Speed');
noGroups.unmount();
render(<ClientsTable hasGroups />);
expect(headers()).toEqual(['Client', 'Remaining']);
});
});
+1
View File
@@ -856,6 +856,7 @@
"has": "يملك",
"hasNot": "لا يملك",
"actions": "الإجراءات",
"columns": "الأعمدة",
"totalGB": "حد البيانات (جيجابايت)",
"totalGBDesc": "حصة البيانات لهذا العميل. 0 = غير محدود.",
"expiryTime": "انتهاء الصلاحية",
+1
View File
@@ -856,6 +856,7 @@
"has": "Has",
"hasNot": "Doesn't have",
"actions": "Actions",
"columns": "Columns",
"totalGB": "Traffic Limit (GB)",
"totalGBDesc": "Data quota for this client. 0 = unlimited.",
"expiryTime": "Expiry",
+1
View File
@@ -856,6 +856,7 @@
"has": "Tiene",
"hasNot": "No tiene",
"actions": "Acciones",
"columns": "Columnas",
"totalGB": "Límite de tráfico (GB)",
"totalGBDesc": "Cuota de datos para este cliente. 0 = ilimitado.",
"expiryTime": "Expiración",
+1
View File
@@ -856,6 +856,7 @@
"has": "دارد",
"hasNot": "ندارد",
"actions": "عملیات",
"columns": "ستون‌ها",
"totalGB": "سقف حجم (گیگابایت)",
"totalGBDesc": "سهمیه‌ی حجم مصرفی کلاینت. ۰ = نامحدود",
"expiryTime": "انقضا",
+1
View File
@@ -856,6 +856,7 @@
"has": "Memiliki",
"hasNot": "Tidak memiliki",
"actions": "Aksi",
"columns": "Kolom",
"totalGB": "Batas Trafik (GB)",
"totalGBDesc": "Kuota data untuk klien ini. 0 = tidak terbatas.",
"expiryTime": "Kedaluwarsa",
+1
View File
@@ -856,6 +856,7 @@
"has": "あり",
"hasNot": "なし",
"actions": "操作",
"columns": "列",
"totalGB": "トラフィック上限 (GB)",
"totalGBDesc": "このクライアントのデータ割当量。0 = 無制限。",
"expiryTime": "有効期限",
+1
View File
@@ -856,6 +856,7 @@
"has": "Tem",
"hasNot": "Não tem",
"actions": "Ações",
"columns": "Colunas",
"totalGB": "Limite de tráfego (GB)",
"totalGBDesc": "Cota de dados para este cliente. 0 = ilimitado.",
"expiryTime": "Expiração",
+1
View File
@@ -856,6 +856,7 @@
"has": "Есть",
"hasNot": "Нет",
"actions": "Действия",
"columns": "Столбцы",
"totalGB": "Лимит трафика (ГБ)",
"totalGBDesc": "Квота трафика для этого клиента. 0 = без ограничений.",
"expiryTime": "Срок действия",
+1
View File
@@ -856,6 +856,7 @@
"has": "Obsahuje",
"hasNot": "Neobsahuje",
"actions": "Akcie",
"columns": "Stĺpce",
"totalGB": "Dátový limit (GB)",
"totalGBDesc": "Dátový limit tohto klienta. Hodnota 0 znamená bez obmedzenia.",
"expiryTime": "Platnosť do",
+1
View File
@@ -856,6 +856,7 @@
"has": "Var",
"hasNot": "Yok",
"actions": "İşlemler",
"columns": "Sütunlar",
"totalGB": "Trafik Limiti (GB)",
"totalGBDesc": "Bu kullanıcı için veri kotası. 0 = sınırsız.",
"expiryTime": "Son Kullanma",
+1
View File
@@ -856,6 +856,7 @@
"has": "Має",
"hasNot": "Не має",
"actions": "Дії",
"columns": "Стовпці",
"totalGB": "Ліміт трафіку (ГБ)",
"totalGBDesc": "Квота трафіку для цього клієнта. 0 = без обмежень.",
"expiryTime": "Термін дії",
+1
View File
@@ -856,6 +856,7 @@
"has": "Có",
"hasNot": "Không có",
"actions": "Hành động",
"columns": "Cột",
"totalGB": "Giới hạn lưu lượng (GB)",
"totalGBDesc": "Hạn mức dữ liệu cho khách hàng này. 0 = không giới hạn.",
"expiryTime": "Hết hạn",
+1
View File
@@ -856,6 +856,7 @@
"has": "拥有",
"hasNot": "不拥有",
"actions": "操作",
"columns": "列",
"totalGB": "流量上限 (GB)",
"totalGBDesc": "该客户端的流量配额。0 = 不限制。",
"expiryTime": "过期时间",
+1
View File
@@ -856,6 +856,7 @@
"has": "擁有",
"hasNot": "不擁有",
"actions": "操作",
"columns": "欄位",
"totalGB": "流量上限 (GB)",
"totalGBDesc": "該客戶端的流量配額。0 = 不限制。",
"expiryTime": "到期時間",