Files
mirror-3x-ui/frontend/src/pages/hosts/HostAddressSelect.tsx
T

184 lines
6.5 KiB
TypeScript

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>
);
}