From 678816c3ff4b82e40cce7f0be04a6793b84f8bab Mon Sep 17 00:00:00 2001 From: Hamed Sanaei Date: Tue, 1 Dec 2026 10:02:26 +0330 Subject: [PATCH 1/3] fix(hosts): reset form sessions and support address tag editing --- .../src/pages/hosts/HostAddressSelect.css | 42 ++++ .../src/pages/hosts/HostAddressSelect.tsx | 183 ++++++++++++++++++ frontend/src/pages/hosts/HostFormModal.tsx | 48 ++--- frontend/src/test/host-address-tags.test.tsx | 123 ++++++++++++ frontend/src/test/host-form-session.test.tsx | 143 ++++++++++++++ internal/web/translation/ar-EG.json | 6 + internal/web/translation/en-US.json | 6 + internal/web/translation/es-ES.json | 6 + internal/web/translation/fa-IR.json | 6 + internal/web/translation/id-ID.json | 6 + internal/web/translation/ja-JP.json | 6 + internal/web/translation/pt-BR.json | 6 + internal/web/translation/ru-RU.json | 6 + internal/web/translation/sk-SK.json | 6 + internal/web/translation/tr-TR.json | 6 + internal/web/translation/uk-UA.json | 6 + internal/web/translation/vi-VN.json | 6 + internal/web/translation/zh-CN.json | 6 + internal/web/translation/zh-TW.json | 6 + 19 files changed, 601 insertions(+), 22 deletions(-) create mode 100644 frontend/src/pages/hosts/HostAddressSelect.css create mode 100644 frontend/src/pages/hosts/HostAddressSelect.tsx create mode 100644 frontend/src/test/host-address-tags.test.tsx create mode 100644 frontend/src/test/host-form-session.test.tsx diff --git a/frontend/src/pages/hosts/HostAddressSelect.css b/frontend/src/pages/hosts/HostAddressSelect.css new file mode 100644 index 000000000..e6f29a6d3 --- /dev/null +++ b/frontend/src/pages/hosts/HostAddressSelect.css @@ -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%; +} diff --git a/frontend/src/pages/hosts/HostAddressSelect.tsx b/frontend/src/pages/hosts/HostAddressSelect.tsx new file mode 100644 index 000000000..15dc6cd97 --- /dev/null +++ b/frontend/src/pages/hosts/HostAddressSelect.tsx @@ -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>, + '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()); + const focusAfterEdit = useRef(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) { + 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) { + 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 ( +
+ {messageContext} + + {...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 ? ( + setEditing({ address, draft: event.target.value })} + onKeyDown={editKeyDown} + onMouseDown={(event) => event.stopPropagation()} + onBlur={() => setEditing(null)} + /> + ) : ( + + + + + ), + }); + }} + /> +
+ ); +} diff --git a/frontend/src/pages/hosts/HostFormModal.tsx b/frontend/src/pages/hosts/HostFormModal.tsx index d2237dbb1..4e863910f 100644 --- a/frontend/src/pages/hosts/HostFormModal.tsx +++ b/frontend/src/pages/hosts/HostFormModal.tsx @@ -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 & { @@ -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 ; +} + +function HostFormSession({ open, mode, host, @@ -111,9 +121,17 @@ export default function HostFormModal({ }: HostFormModalProps) { const { t } = useTranslation(); const { isMobile } = useMediaQuery(); - const methods = useForm({ defaultValues: defaultsFor(host) }); + const methods = useForm({ 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({ 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) }} > -