Files
3x-ui/frontend/src/pages/inbounds/clients/DetachClientsModal.tsx
T
Sanaei b9eda09da9 chore(frontend): update dependencies and adapt to oxlint 1.79
npm install was failing with ERESOLVE: the lockfile pinned storybook 10.5.7
and vitest 4.1.10 as peers while package.json asked for ^10.5.9 and ^4.1.11,
and npm would not move either. Neither npm update, a targeted install, nor
--package-lock-only broke the cycle, so node_modules and package-lock.json
were regenerated from scratch (601 packages, 0 vulnerabilities).

oxlint 1.79.0 then promoted five React Compiler rules into the correctness
category, flagging 101 pre-existing sites. 1.78.0 exits 0 on the same tree,
so nothing in our code changed - the rule set grew. They are fixed rather
than suppressed:

- refs (31): latest-value ref writes moved out of render into an effect.
  onlineClientsRef turned out to be write-only and is gone; expireDiffRef
  and trafficDiffRef were replaced by reading the values directly.
- set-state-in-effect (55): reset-on-open modals now adjust state during
  render; where an effect mixed a synchronous reset with an async fetch, the
  reset moved to render and the effect kept only the request. useMediaQuery
  became useSyncExternalStore.
- preserve-manual-memoization (11): optional-chained deps the compiler cannot
  match, hoisted to locals or dropped where the memo wrapped a string concat.
- purity (3): Date.now() in render replaced by a state-backed clock, which
  also refreshes the expiry tag every 60s instead of freezing it until the
  next unrelated re-render.
- immutability (1): applyClientStatsEvent merged websocket traffic into
  DBInbound rows in place; it now rebuilds only the rows it touches.

Two things fell out of that. clientCount is derived with useMemo instead of
an imperative rebuildClientCount() called from five sites, which also fixes a
staleness bug where changing the expiry or traffic threshold left the counts
alone until some later rebuild. statsVersion existed only to force a
re-render after an in-place mutation, is meaningless now that rows are
replaced, and nothing read it, so it is removed.

Also adds a lint:fix script - oxlint --fix was previously only reachable
through the lint-staged hook.
2026-08-19 17:48:28 +02:00

191 lines
5.6 KiB
TypeScript

import { useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Input, Modal, Space, Table, Tag, Typography, message } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import { HttpUtil } from '@/utils';
import { coerceInboundJsonField, type DBInbound } from '@/models/dbinbound';
interface DetachClientsModalProps {
open: boolean;
source: DBInbound | null;
onClose: () => void;
onDetached?: () => void;
}
interface BulkDetachResult {
detached?: string[];
skipped?: string[];
errors?: string[];
}
interface ClientRow {
email: string;
comment: string;
enable: boolean;
}
function readClientRows(settings: unknown): ClientRow[] {
const parsed = coerceInboundJsonField(settings) as {
clients?: Array<{ email?: string; comment?: string; enable?: boolean }>;
};
const clients = Array.isArray(parsed?.clients) ? parsed.clients : [];
return clients
.map((c) => ({
email: (c?.email || '').trim(),
comment: (c?.comment || '').trim(),
enable: c?.enable !== false,
}))
.filter((r) => r.email);
}
export default function DetachClientsModal({
open,
source,
onClose,
onDetached,
}: DetachClientsModalProps) {
const { t } = useTranslation();
const [messageApi, messageContextHolder] = message.useMessage();
const [saving, setSaving] = useState(false);
const [clientRows, setClientRows] = useState<ClientRow[]>([]);
const [selectedEmails, setSelectedEmails] = useState<string[]>([]);
const [search, setSearch] = useState('');
// Reset during render, not in an effect, so the first frame is already clean.
const openSource = open ? source : null;
const [syncedSource, setSyncedSource] = useState(openSource);
if (openSource !== syncedSource) {
setSyncedSource(openSource);
if (openSource) {
setClientRows(readClientRows(openSource.settings));
setSelectedEmails([]);
setSearch('');
}
}
const filteredRows = useMemo(() => {
const q = search.trim().toLowerCase();
if (!q) return clientRows;
return clientRows.filter(
(r) => r.email.toLowerCase().includes(q) || r.comment.toLowerCase().includes(q),
);
}, [clientRows, search]);
const columns: ColumnsType<ClientRow> = useMemo(
() => [
{
title: t('pages.inbounds.email'),
dataIndex: 'email',
key: 'email',
ellipsis: true,
},
{
title: t('comment'),
dataIndex: 'comment',
key: 'comment',
ellipsis: true,
},
{
title: t('enable'),
dataIndex: 'enable',
key: 'enable',
width: 90,
render: (enabled: boolean) =>
enabled ? (
<Tag color="success">{t('enable')}</Tag>
) : (
<Tag>{t('pages.inbounds.attachClientsStatusDisabled')}</Tag>
),
},
],
[t],
);
async function submit() {
if (!source || selectedEmails.length === 0) return;
setSaving(true);
try {
const msg = await HttpUtil.post(
'/panel/api/clients/bulkDetach',
{ emails: selectedEmails, inboundIds: [source.id] },
{ headers: { 'Content-Type': 'application/json' } },
);
if (!msg?.success) {
messageApi.error(msg?.msg || t('somethingWentWrong'));
return;
}
const result = (msg.obj || {}) as BulkDetachResult;
const detached = result.detached?.length ?? 0;
const skipped = result.skipped?.length ?? 0;
const errors = result.errors?.length ?? 0;
if (errors > 0) {
messageApi.warning(
t('pages.inbounds.detachClientsResultMixed', { detached, skipped, errors }),
);
} else {
messageApi.success(t('pages.inbounds.detachClientsResult', { detached, skipped }));
}
onDetached?.();
onClose();
} finally {
setSaving(false);
}
}
return (
<Modal
open={open}
onCancel={onClose}
onOk={submit}
okButtonProps={{
danger: true,
disabled: selectedEmails.length === 0,
loading: saving,
}}
okText={t('pages.inbounds.detachClients')}
cancelText={t('cancel')}
title={t('pages.inbounds.detachClientsTitle', { remark: source?.tag ?? '' })}
width={680}
>
{messageContextHolder}
<Typography.Paragraph type="secondary">
{t('pages.inbounds.detachClientsDesc', { count: clientRows.length })}
</Typography.Paragraph>
<Space orientation="vertical" size="small" style={{ width: '100%' }}>
<Typography.Text strong>{t('pages.inbounds.detachClientsSelectLabel')}</Typography.Text>
<Space style={{ width: '100%', justifyContent: 'space-between' }} wrap>
<Input.Search
allowClear
aria-label={t('search')}
value={search}
onChange={(e) => setSearch(e.target.value)}
placeholder={t('pages.inbounds.attachClientsSearchPlaceholder')}
style={{ maxWidth: 320 }}
/>
<Typography.Text type="secondary">
{t('pages.inbounds.attachClientsSelectedCount', {
selected: selectedEmails.length,
total: clientRows.length,
})}
</Typography.Text>
</Space>
<Table<ClientRow>
size="small"
rowKey="email"
columns={columns}
dataSource={filteredRows}
pagination={false}
scroll={{ y: 280 }}
rowSelection={{
selectedRowKeys: selectedEmails,
onChange: (keys) => setSelectedEmails(keys as string[]),
preserveSelectedRowKeys: true,
}}
/>
</Space>
</Modal>
);
}