fix(hosts): reset form sessions and support address tag editing

This commit is contained in:
Hamed Sanaei
2026-12-01 10:02:26 +03:30
parent 267379456a
commit 678816c3ff
19 changed files with 601 additions and 22 deletions
@@ -0,0 +1,42 @@
.host-address-tag-actions {
display: inline-flex;
align-items: center;
gap: 4px;
max-width: 100%;
}
.host-address-tag-button,
.host-address-tag-editor {
padding: 0 2px;
border: 0;
border-radius: 2px;
background: transparent;
color: inherit;
font: inherit;
}
.host-address-tag-button {
cursor: pointer;
}
.host-address-tag-button:first-child {
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.host-address-tag-button:last-child {
flex-shrink: 0;
}
.host-address-tag-button:focus-visible,
.host-address-tag-editor:focus {
outline: 2px solid var(--ant-color-primary);
outline-offset: -1px;
}
.host-address-tag-editor {
width: 24ch;
max-width: 100%;
}
@@ -0,0 +1,183 @@
import { useCallback, useLayoutEffect, useRef, useState } from 'react';
import type { ClipboardEvent, ComponentPropsWithRef, KeyboardEvent, MouseEvent } from 'react';
import { CopyOutlined } from '@ant-design/icons';
import { Select, message } from 'antd';
import { useTranslation } from 'react-i18next';
import { selectTagRender } from '@/components/form';
import { ClipboardManager } from '@/utils';
import './HostAddressSelect.css';
type Props = Pick<
ComponentPropsWithRef<typeof Select<string[]>>,
'aria-describedby' | 'aria-invalid' | 'id' | 'onBlur' | 'options' | 'ref' | 'value'
> & {
onChange?: (value: string[]) => void;
validateEdit: () => void;
};
const separators = /[\s,;]+/u;
function keepFromSelect(event: MouseEvent) {
event.preventDefault();
event.stopPropagation();
}
function keepActivationFromSelect(event: KeyboardEvent) {
if (event.key === 'Enter' || event.key === ' ') event.stopPropagation();
}
export default function HostAddressSelect({ value, onChange, validateEdit, ...props }: Props) {
const { t } = useTranslation();
const addresses = value ?? [];
const [messageApi, messageContext] = message.useMessage();
const [editing, setEditing] = useState<{ address: string; draft: string } | null>(null);
const [search, setSearch] = useState('');
const [open, setOpen] = useState(false);
const editButtons = useRef(new Map<string, HTMLButtonElement>());
const focusAfterEdit = useRef<string | null>(null);
const focusEditor = useCallback((input: HTMLInputElement | null) => {
input?.focus();
input?.select();
}, []);
useLayoutEffect(() => {
if (editing !== null || focusAfterEdit.current === null) return;
editButtons.current.get(focusAfterEdit.current)?.focus();
focusAfterEdit.current = null;
}, [editing]);
function startEdit(address: string) {
setOpen(false);
setSearch('');
setEditing({ address, draft: address });
}
function finishEdit(address: string) {
focusAfterEdit.current = address;
setEditing(null);
}
function editKeyDown(event: KeyboardEvent<HTMLInputElement>) {
if (event.key !== 'Tab') event.stopPropagation();
if (!editing || event.nativeEvent.isComposing) return;
if (event.key === 'Escape') {
event.preventDefault();
finishEdit(editing.address);
}
if (event.key !== 'Enter') return;
event.preventDefault();
const next = editing.draft.trim();
if (!next || separators.test(next)) {
messageApi.warning(t('pages.hosts.addressActions.single'));
return;
}
if (next !== editing.address) {
if (addresses.includes(next)) {
messageApi.warning(t('pages.hosts.addressActions.duplicate'));
return;
}
const index = addresses.indexOf(editing.address);
onChange?.(addresses.map((address, i) => (i === index ? next : address)));
validateEdit();
}
finishEdit(next);
}
function pasteAddresses(event: ClipboardEvent<HTMLDivElement>) {
const input = event.target;
if (!(input instanceof HTMLInputElement) || input.getAttribute('role') !== 'combobox') return;
const pasted = event.clipboardData.getData('text/plain');
if (!pasted.trim()) return;
event.preventDefault();
event.stopPropagation();
const start = input.selectionStart ?? input.value.length;
const end = input.selectionEnd ?? start;
const text = input.value.slice(0, start) + pasted + input.value.slice(end);
const existing = new Set(addresses);
const additions = [...new Set(text.split(separators))].filter(
(address) => address && !existing.has(address),
);
if (additions.length > 0) onChange?.([...addresses, ...additions]);
setSearch('');
setOpen(false);
}
async function copyAddress(address: string) {
if (await ClipboardManager.copyText(address)) messageApi.success(t('copied'));
else messageApi.error(t('somethingWentWrong'));
}
return (
<div onPasteCapture={pasteAddresses}>
{messageContext}
<Select<string[]>
{...props}
mode="tags"
value={addresses}
onChange={onChange}
showSearch={{ searchValue: search, onSearch: setSearch }}
open={editing ? false : open}
onOpenChange={setOpen}
tokenSeparators={[',', ';', ' ', '\t', '\r', '\n']}
placeholder="cdn.example.com, cdn2.example.com:443"
tagRender={(tag) => {
if (tag.isMaxTag || tag.disabled) return selectTagRender(tag);
const address = String(tag.value);
const editLabel = t('pages.hosts.addressActions.edit', { address });
return selectTagRender({
...tag,
label:
editing?.address === address ? (
<input
className="host-address-tag-editor"
type="text"
dir="ltr"
aria-label={editLabel}
ref={focusEditor}
value={editing.draft}
onChange={(event) => setEditing({ address, draft: event.target.value })}
onKeyDown={editKeyDown}
onMouseDown={(event) => event.stopPropagation()}
onBlur={() => setEditing(null)}
/>
) : (
<span className="host-address-tag-actions">
<button
type="button"
className="host-address-tag-button"
aria-label={editLabel}
title={editLabel}
ref={(button) => {
if (button) editButtons.current.set(address, button);
else editButtons.current.delete(address);
}}
onMouseDown={keepFromSelect}
onKeyDown={keepActivationFromSelect}
onClick={(event) => {
if (event.detail === 0) startEdit(address);
}}
onDoubleClick={() => startEdit(address)}
>
<bdi>{address}</bdi>
</button>
<button
type="button"
className="host-address-tag-button"
aria-label={t('pages.hosts.addressActions.copy', { address })}
title={t('copy')}
onMouseDown={keepFromSelect}
onKeyDown={keepActivationFromSelect}
onClick={() => void copyAddress(address)}
>
<CopyOutlined aria-hidden />
</button>
</span>
),
});
}}
/>
</div>
);
}
+26 -22
View File
@@ -1,4 +1,4 @@
import { useMemo, useState } from 'react';
import { useLayoutEffect, useMemo, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import {
Alert,
@@ -35,6 +35,7 @@ import { useNodesQuery } from '@/api/queries/useNodesQuery';
import { useMediaQuery } from '@/hooks/useMediaQuery';
import { catTabLabel } from '@/pages/settings/catTabLabel';
import { withHostPort } from '@/lib/hosts/host-port';
import HostAddressSelect from './HostAddressSelect';
import { HostFinalMaskForm, HostMuxForm, HostSockoptForm } from './json-forms';
type FormShape = Omit<BulkAddHostValues, 'isDisabled'> & {
@@ -100,7 +101,16 @@ function defaultsFor(host: HostRecord | null): FormShape {
};
}
export default function HostFormModal({
export default function HostFormModal(props: HostFormModalProps) {
const key = props.open ? (props.mode === 'add' ? 'add' : `edit:${props.host?.groupId}`) : null;
const [session, setSession] = useState({ key, generation: 0 });
if (key !== session.key) {
setSession({ key, generation: session.generation + (key === null ? 0 : 1) });
}
return <HostFormSession key={session.generation} {...props} />;
}
function HostFormSession({
open,
mode,
host,
@@ -111,9 +121,17 @@ export default function HostFormModal({
}: HostFormModalProps) {
const { t } = useTranslation();
const { isMobile } = useMediaQuery();
const methods = useForm<FormShape>({ defaultValues: defaultsFor(host) });
const methods = useForm<FormShape>({ defaultValues: defaultsFor(mode === 'edit' ? host : null) });
const [messageApi, messageContextHolder] = message.useMessage();
const [loading, setLoading] = useState(false);
const active = useRef(false);
useLayoutEffect(() => {
active.current = open;
return () => {
active.current = false;
};
}, [open]);
const security = (useWatch({ control: methods.control, name: 'security' }) ?? 'same') as string;
const fingerprint = (useWatch({ control: methods.control, name: 'fingerprint' }) ?? '') as string;
@@ -130,18 +148,6 @@ export default function HostFormModal({
const watchedHosts = useWatch({ control: methods.control, name: 'hosts' });
const hasCidr = Boolean(watchedHosts?.some((h) => typeof h === 'string' && h.includes('/')));
// React resets this during render rather than in an effect so the modal's
// first open frame already shows cleared fields.
const openHost = open ? host : null;
const [syncedHost, setSyncedHost] = useState(openHost);
if (openHost !== syncedHost) {
setSyncedHost(openHost);
if (open) {
methods.reset(defaultsFor(host));
setLoading(false);
}
}
const { nodes } = useNodesQuery();
const inboundSelectOptions = useMemo(
@@ -219,6 +225,7 @@ export default function HostFormModal({
setLoading(true);
try {
const res = await save(payload);
if (!active.current) return;
if (res?.success) {
messageApi.success(
t(mode === 'add' ? 'pages.hosts.toasts.add' : 'pages.hosts.toasts.update'),
@@ -230,7 +237,7 @@ export default function HostFormModal({
} catch (err) {
console.error(err);
} finally {
setLoading(false);
if (active.current) setLoading(false);
}
};
@@ -238,7 +245,7 @@ export default function HostFormModal({
<Modal
open={open}
title={t(mode === 'add' ? 'pages.hosts.addHost' : 'pages.hosts.editHost')}
onOk={methods.handleSubmit(onFinish)}
onOk={(event) => void methods.handleSubmit(onFinish)(event)}
onCancel={() => onOpenChange(false)}
confirmLoading={loading}
okText={t('save')}
@@ -302,12 +309,9 @@ export default function HostFormModal({
tooltip={t('pages.hosts.hints.address')}
rules={{ validate: rhfZodValidate(BulkAddHostSchema.shape.hosts) }}
>
<Select
mode="tags"
tagRender={selectTagRender}
<HostAddressSelect
options={hostOptions}
tokenSeparators={[',', ';', ' ']}
placeholder="cdn.example.com, cdn2.example.com:443"
validateEdit={() => void methods.trigger('hosts')}
/>
</FormField>
{hasCidr && (
@@ -0,0 +1,123 @@
import { fireEvent, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import type { HostRecord } from '@/api/queries/useHostsQuery';
import HostFormModal from '@/pages/hosts/HostFormModal';
import { HttpUtil, Msg } from '@/utils';
import { renderWithProviders } from './test-utils';
const ipv6 = '[2001:db8::a]:8443';
const cidr = '192.0.2.0/24';
const host = {
groupId: 'g1',
remark: 'Fixture host',
inboundIds: [1],
hosts: [ipv6, cidr],
} as HostRecord;
function renderHost() {
const save = vi.fn().mockResolvedValue({ success: true });
renderWithProviders(
<HostFormModal
open
mode="edit"
host={host}
inboundOptions={[{ id: 1, remark: 'In', tag: 'in', protocol: 'vless' }]}
existingHosts={[host]}
save={save}
onOpenChange={() => {}}
/>,
);
return save;
}
describe('Host address tags', () => {
beforeEach(() => {
vi.spyOn(HttpUtil, 'get').mockResolvedValue(new Msg(true, '', []));
});
afterEach(() => {
vi.unstubAllGlobals();
});
it('pastes single and mixed-delimiter addresses and copies the exact tag text', async () => {
vi.stubGlobal('isSecureContext', true);
const user = userEvent.setup();
const save = renderHost();
const address = await screen.findByRole('combobox', { name: 'Address' });
await user.click(address);
await user.paste('Example.TEST:444');
expect(screen.getByRole('button', { name: 'Remove Example.TEST:444' })).not.toBeNull();
await user.paste(
'proxy.test;192.0.2.7:443,\r\n2001:db8::7\tother.test duplicate.test duplicate.test',
);
expect(screen.getByRole('button', { name: 'Remove 2001:db8::7' })).not.toBeNull();
const copy = screen.getByRole('button', { name: `Copy ${ipv6}` });
copy.focus();
await user.keyboard('{Enter}');
await waitFor(async () => expect(await navigator.clipboard.readText()).toBe(ipv6));
const remark = screen.getByRole<HTMLInputElement>('textbox', { name: 'Remark' });
await user.click(remark);
await user.keyboard('{Control>}a{/Control}');
await user.paste();
expect(remark.value).toBe(ipv6);
fireEvent.click(screen.getByRole('button', { name: 'Save' }));
await waitFor(() => expect(save).toHaveBeenCalledTimes(1));
expect(save).toHaveBeenCalledWith(
expect.objectContaining({
hosts: [
ipv6,
cidr,
'Example.TEST:444',
'proxy.test',
'192.0.2.7:443',
'2001:db8::7',
'other.test',
'duplicate.test',
],
}),
);
});
it('edits one tag with Enter, cancels with Escape and keeps removal working', async () => {
const user = userEvent.setup();
const save = renderHost();
const address = await screen.findByRole('combobox', { name: 'Address' });
await user.dblClick(screen.getByText(ipv6, { exact: true }));
let edit = screen.getByRole('textbox', { name: `Edit ${ipv6}` });
expect(document.activeElement).toBe(edit);
expect(address.getAttribute('aria-expanded')).toBe('false');
await user.clear(edit);
await user.paste('[2001:db8::f]:8443');
await user.keyboard('{Enter}');
const replaced = screen.getByRole('button', { name: 'Edit [2001:db8::f]:8443' });
expect(document.activeElement).toBe(replaced);
expect(address.getAttribute('aria-expanded')).toBe('false');
expect(save).not.toHaveBeenCalled();
await user.keyboard('{Enter}');
edit = screen.getByRole('textbox', { name: 'Edit [2001:db8::f]:8443' });
await user.clear(edit);
await user.type(edit, cidr);
await user.keyboard('{Enter}');
expect(await screen.findByText('This address is already in the list.')).not.toBeNull();
expect(document.activeElement).toBe(edit);
await user.clear(edit);
await user.type(edit, 'cancelled.test');
await user.keyboard('{Escape}');
expect(screen.getByRole('dialog')).not.toBeNull();
expect(document.activeElement).toBe(
screen.getByRole('button', { name: 'Edit [2001:db8::f]:8443' }),
);
expect(screen.queryByText('cancelled.test')).toBeNull();
fireEvent.paste(address, { clipboardData: { getData: () => 'append.test' } });
await user.click(screen.getByRole('button', { name: 'Remove append.test' }));
fireEvent.click(screen.getByRole('button', { name: 'Save' }));
await waitFor(() => expect(save).toHaveBeenCalledTimes(1));
expect(save).toHaveBeenCalledWith(
expect.objectContaining({ hosts: ['[2001:db8::f]:8443', cidr] }),
);
});
});
@@ -0,0 +1,143 @@
import { useState, type ComponentProps } from 'react';
import { act, fireEvent, screen, waitFor } from '@testing-library/react';
import { ConfigProvider } from 'antd';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import type { HostRecord } from '@/api/queries/useHostsQuery';
import HostFormModal from '@/pages/hosts/HostFormModal';
import { HttpUtil, Msg } from '@/utils';
import { chooseSelectOption, renderWithProviders } from './test-utils';
const inboundOptions = [{ id: 1, remark: 'Fixture inbound', tag: 'in', protocol: 'vless' }];
const first = {
groupId: 'first',
remark: 'First host',
inboundIds: [1],
hosts: ['first.example.test'],
port: 8443,
} as HostRecord;
const second = {
...first,
groupId: 'second',
remark: 'Second host',
hosts: ['second.example.test'],
port: 443,
} as HostRecord;
function Sessions({ save }: { save: ComponentProps<typeof HostFormModal>['save'] }) {
const [host, setHost] = useState<HostRecord | null>(null);
const [open, setOpen] = useState(false);
function show(next: HostRecord | null) {
setHost(next);
setOpen(true);
}
return (
<ConfigProvider theme={{ token: { motion: false } }}>
<button onClick={() => show(null)}>New session</button>
<button onClick={() => show(first)}>First session</button>
<button onClick={() => show(second)}>Second session</button>
<button onClick={() => setOpen(false)}>Close externally</button>
<HostFormModal
open={open}
mode={host ? 'edit' : 'add'}
host={host}
inboundOptions={inboundOptions}
existingHosts={[first, second]}
save={save}
onOpenChange={setOpen}
/>
</ConfigProvider>
);
}
async function openSession(name = 'New session') {
fireEvent.click(screen.getByRole('button', { name }));
return screen.findByRole<HTMLInputElement>('textbox', { name: 'Remark' });
}
function fillDraft(remark: HTMLElement) {
fireEvent.change(remark, { target: { value: 'Draft host' } });
const inbound = screen.getByRole('combobox', { name: 'Inbounds' });
chooseSelectOption(inbound.id, 'Fixture inbound');
fireEvent.change(screen.getByRole('spinbutton', { name: 'Port' }), { target: { value: '9443' } });
const address = screen.getByRole('combobox', { name: 'Address' });
fireEvent.change(address, { target: { value: 'draft.example.test,' } });
}
async function closeSession() {
fireEvent.click(screen.getByRole('button', { name: 'Cancel' }));
await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull());
}
describe('Host form sessions', () => {
beforeEach(() => {
vi.spyOn(HttpUtil, 'get').mockResolvedValue(new Msg(true, '', []));
});
it.each(['success', 'rejection', 'error', 'cancel'])(
'starts from Add defaults after a previous %s',
async (result) => {
const save = vi.fn().mockResolvedValue({ success: result === 'success', msg: 'Cannot save' });
if (result === 'error') {
save.mockRejectedValue(new Error('Request failed'));
vi.spyOn(console, 'error').mockImplementation(() => {});
}
renderWithProviders(<Sessions save={save} />);
const remark = await openSession();
fillDraft(remark);
if (result !== 'cancel') {
fireEvent.click(screen.getByRole('button', { name: 'Save' }));
await waitFor(() => expect(save).toHaveBeenCalledTimes(1));
expect(save).toHaveBeenCalledWith(
expect.objectContaining({
remark: 'Draft host',
port: 9443,
hosts: ['draft.example.test'],
}),
);
}
if (result === 'success') {
await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull());
} else {
expect(screen.getByRole<HTMLInputElement>('textbox', { name: 'Remark' }).value).toBe(
'Draft host',
);
await closeSession();
}
expect((await openSession()).value).toBe('');
expect(screen.getByRole<HTMLInputElement>('spinbutton', { name: 'Port' }).value).toBe('0');
expect(screen.queryByRole('button', { name: 'Remove draft.example.test' })).toBeNull();
expect(screen.queryByRole('button', { name: 'Remove Fixture inbound' })).toBeNull();
},
);
it('loads a different Edit host and then opens a clean Add form', async () => {
renderWithProviders(<Sessions save={vi.fn()} />);
expect((await openSession('First session')).value).toBe('First host');
expect((await openSession('Second session')).value).toBe('Second host');
expect(screen.getByRole('button', { name: 'Remove second.example.test' })).not.toBeNull();
await closeSession();
expect((await openSession()).value).toBe('');
expect(screen.queryByRole('button', { name: 'Remove second.example.test' })).toBeNull();
});
it('keeps a later session open when a cancelled request finishes', async () => {
let resolve!: (value: { success: boolean }) => void;
const pending = new Promise<{ success: boolean }>((done) => {
resolve = done;
});
const save = vi.fn().mockReturnValue(pending);
renderWithProviders(<Sessions save={save} />);
await openSession('First session');
fireEvent.click(screen.getByRole('button', { name: 'Save' }));
await waitFor(() => expect(save).toHaveBeenCalledTimes(1));
fireEvent.click(screen.getByRole('button', { name: 'Close externally' }));
await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull());
expect((await openSession('Second session')).value).toBe('Second host');
await act(async () => resolve({ success: true }));
expect(screen.getByRole<HTMLInputElement>('textbox', { name: 'Remark' }).value).toBe(
'Second host',
);
});
});