mirror of
https://github.com/MHSanaei/3x-ui.git
synced 2026-12-04 16:34:52 +03:00
fix(hosts): isolate form sessions and improve address editing
Fix Host form state leaking across Add/Edit modal sessions by creating a fresh form session for each opening and ignoring stale asynchronous completions after a session closes. Improve the Address field with per-tag copy, multi-address paste, and accessible inline editing with validation, ordered replacement, Escape cancellation, and focus restoration. Preserve existing address formats, tag removal, schema validation, and host-port rewriting. Guard keyboard event propagation from Edit/Copy controls to prevent Backspace from unintentionally removing a tag. Add regression coverage for form lifecycle, async races, clipboard interactions, inline editing, validation, focus, and keyboard behavior. Verified by GitHub Actions CI on the reviewed head: 12/12 jobs successful.
This commit is contained in:
@@ -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,208 @@
|
||||
import { useCallback, useImperativeHandle, useLayoutEffect, useRef, useState } from 'react';
|
||||
import type { ClipboardEvent, ComponentPropsWithRef, KeyboardEvent, MouseEvent, Ref } 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;
|
||||
commitEditRef: Ref<() => boolean>;
|
||||
validateEdit: () => void;
|
||||
};
|
||||
|
||||
const separators = /[\s,;]+/u;
|
||||
|
||||
function keepFromSelect(event: MouseEvent) {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
}
|
||||
|
||||
function keepKeyFromSelect(event: KeyboardEvent) {
|
||||
if (event.key !== 'Tab') event.stopPropagation();
|
||||
}
|
||||
|
||||
export default function HostAddressSelect({
|
||||
value,
|
||||
onChange,
|
||||
commitEditRef,
|
||||
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, restoreFocus: boolean) {
|
||||
if (restoreFocus) focusAfterEdit.current = address;
|
||||
setEditing(null);
|
||||
}
|
||||
|
||||
function commitEdit(restoreFocus: boolean): boolean {
|
||||
if (!editing) return true;
|
||||
const index = addresses.indexOf(editing.address);
|
||||
if (index < 0) {
|
||||
setEditing(null);
|
||||
return true;
|
||||
}
|
||||
const next = editing.draft.trim();
|
||||
if (!next || separators.test(next)) {
|
||||
messageApi.warning({
|
||||
key: 'host-address-edit',
|
||||
content: t('pages.hosts.addressActions.single'),
|
||||
});
|
||||
return false;
|
||||
}
|
||||
if (next !== editing.address) {
|
||||
if (addresses.includes(next)) {
|
||||
messageApi.warning({
|
||||
key: 'host-address-edit',
|
||||
content: t('pages.hosts.addressActions.duplicate'),
|
||||
});
|
||||
return false;
|
||||
}
|
||||
onChange?.(addresses.map((address, i) => (i === index ? next : address)));
|
||||
validateEdit();
|
||||
}
|
||||
finishEdit(next, restoreFocus);
|
||||
return true;
|
||||
}
|
||||
|
||||
useImperativeHandle(commitEditRef, () => () => commitEdit(false));
|
||||
|
||||
function editKeyDown(event: KeyboardEvent<HTMLInputElement>) {
|
||||
keepKeyFromSelect(event);
|
||||
if (!editing || event.nativeEvent.isComposing) return;
|
||||
if (event.key === 'Escape') {
|
||||
event.preventDefault();
|
||||
finishEdit(editing.address, true);
|
||||
} else if (event.key === 'Enter') {
|
||||
event.preventDefault();
|
||||
commitEdit(true);
|
||||
}
|
||||
}
|
||||
|
||||
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={() => commitEdit(false)}
|
||||
/>
|
||||
) : (
|
||||
<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={keepKeyFromSelect}
|
||||
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={keepKeyFromSelect}
|
||||
onClick={() => void copyAddress(address)}
|
||||
>
|
||||
<CopyOutlined aria-hidden />
|
||||
</button>
|
||||
</span>
|
||||
),
|
||||
});
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -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,18 @@ 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);
|
||||
const commitAddressEdit = useRef<(() => boolean) | null>(null);
|
||||
|
||||
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 +149,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 +226,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 +238,7 @@ export default function HostFormModal({
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
if (active.current) setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -238,7 +246,10 @@ export default function HostFormModal({
|
||||
<Modal
|
||||
open={open}
|
||||
title={t(mode === 'add' ? 'pages.hosts.addHost' : 'pages.hosts.editHost')}
|
||||
onOk={methods.handleSubmit(onFinish)}
|
||||
onOk={(event) => {
|
||||
if (commitAddressEdit.current?.() === false) return;
|
||||
void methods.handleSubmit(onFinish)(event);
|
||||
}}
|
||||
onCancel={() => onOpenChange(false)}
|
||||
confirmLoading={loading}
|
||||
okText={t('save')}
|
||||
@@ -302,12 +313,10 @@ 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"
|
||||
commitEditRef={commitAddressEdit}
|
||||
validateEdit={() => void methods.trigger('hosts')}
|
||||
/>
|
||||
</FormField>
|
||||
{hasCidr && (
|
||||
|
||||
@@ -0,0 +1,180 @@
|
||||
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.each(['Edit', 'Copy'])(
|
||||
'keeps all addresses when Backspace is pressed on %s',
|
||||
async (action) => {
|
||||
const user = userEvent.setup();
|
||||
const save = renderHost();
|
||||
const button = screen.getByRole('button', { name: `${action} ${ipv6}` });
|
||||
button.focus();
|
||||
expect(document.activeElement).toBe(button);
|
||||
await user.keyboard('{Backspace}');
|
||||
|
||||
expect(screen.getByRole('button', { name: `Remove ${ipv6}` })).not.toBeNull();
|
||||
expect(screen.getByRole('button', { name: `Remove ${cidr}` })).not.toBeNull();
|
||||
await user.click(screen.getByRole('button', { name: 'Save' }));
|
||||
await waitFor(() => expect(save).toHaveBeenCalledTimes(1));
|
||||
expect(save).toHaveBeenCalledWith(expect.objectContaining({ hosts: [ipv6, cidr] }));
|
||||
},
|
||||
);
|
||||
|
||||
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] }),
|
||||
);
|
||||
});
|
||||
|
||||
it('saves the address being edited when the operator clicks Save', async () => {
|
||||
const user = userEvent.setup();
|
||||
const save = renderHost();
|
||||
await user.dblClick(screen.getByText(ipv6, { exact: true }));
|
||||
const editor = screen.getByRole('textbox', { name: `Edit ${ipv6}` });
|
||||
await user.clear(editor);
|
||||
await user.type(editor, 'replacement.test');
|
||||
await user.click(screen.getByRole('button', { name: 'Save' }));
|
||||
|
||||
await waitFor(() => expect(save).toHaveBeenCalledTimes(1));
|
||||
expect(save).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ hosts: ['replacement.test', cidr] }),
|
||||
);
|
||||
});
|
||||
|
||||
it('keeps an invalid draft and blocks saving until it is corrected', async () => {
|
||||
const user = userEvent.setup();
|
||||
const save = renderHost();
|
||||
await user.dblClick(screen.getByText(ipv6, { exact: true }));
|
||||
const editor = screen.getByRole<HTMLInputElement>('textbox', { name: `Edit ${ipv6}` });
|
||||
const saveButton = screen.getByRole('button', { name: 'Save' });
|
||||
await user.clear(editor);
|
||||
await user.type(editor, cidr);
|
||||
await user.click(saveButton);
|
||||
expect(await screen.findByText('This address is already in the list.')).not.toBeNull();
|
||||
expect(save).not.toHaveBeenCalled();
|
||||
expect(editor.value).toBe(cidr);
|
||||
expect(screen.getByRole('textbox', { name: `Edit ${ipv6}` })).toBe(editor);
|
||||
|
||||
await user.clear(editor);
|
||||
await user.type(editor, 'corrected.test');
|
||||
await user.tab();
|
||||
const replacement = screen.getByRole('button', { name: 'Edit corrected.test' });
|
||||
expect(document.activeElement).not.toBe(replacement);
|
||||
await user.click(saveButton);
|
||||
await waitFor(() => expect(save).toHaveBeenCalledTimes(1));
|
||||
expect(save).toHaveBeenCalledWith(expect.objectContaining({ hosts: ['corrected.test', 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',
|
||||
);
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user