2 Commits
Author SHA1 Message Date
DenozordecandCursor ba66755a29 fix(ui): AutoComplete и флаги страны как в VPS Tracker
quality / commitlint (push) Skipped
CD / update-wiki (push) Successful in 6s
quality / changes (push) Successful in 5s
quality / api (push) Skipped
quality / docker-check (push) Skipped
quality / web (push) Successful in 1m6s
CD / quality (push) Successful in 1m14s
CD / publish (push) Successful in 1m37s
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-04 15:03:29 +07:00
DenozordecandCursor 25c95356a1 fix(ui): каскад страна и локация в форме ноды
quality / commitlint (push) Skipped
CD / update-wiki (push) Successful in 5s
quality / changes (push) Successful in 4s
quality / api (push) Skipped
quality / docker-check (push) Skipped
quality / web (push) Successful in 45s
CD / quality (push) Successful in 56s
CD / publish (push) Successful in 1m25s
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-04 14:43:50 +07:00
4 changed files with 290 additions and 13 deletions
@@ -0,0 +1,134 @@
'use client'
import * as React from 'react'
import { CheckIcon } from 'lucide-react'
import { cn } from '@cdnmanager/ui/lib/utils'
import {
Autocomplete,
AutocompleteContent,
AutocompleteEmpty,
AutocompleteInput,
AutocompleteItem,
AutocompleteList,
} from '@/components/reui/autocomplete'
import { TruncatedText } from '@/components/truncated-text'
export interface AutoCompleteOption {
value: string
label: string
/** Левый префикс (например флаг страны). */
leading?: React.ReactNode
}
interface AutoCompleteInputProps {
id?: string
value: string
onChange: (value: string) => void
options: AutoCompleteOption[]
placeholder?: string
searchPlaceholder?: string
emptyText?: string
className?: string
/** Показывать ли выбранный leading в поле (например флаг). */
showLeadingInInput?: boolean
/** Разрешать ли произвольный ввод (не только из списка). По умолчанию true. */
allowFreeText?: boolean
disabled?: boolean
}
export function AutoCompleteInput({
id,
value,
onChange,
options,
placeholder = 'Выбрать…',
searchPlaceholder,
emptyText = 'Ничего не найдено',
className,
showLeadingInInput = true,
allowFreeText = true,
disabled = false,
}: AutoCompleteInputProps) {
const trimmedValue = value.trim()
const selected = React.useMemo(
() => options.find((o) => o.value.toLowerCase() === trimmedValue.toLowerCase()),
[options, trimmedValue],
)
const leading = showLeadingInInput ? selected?.leading : undefined
const inputPlaceholder = searchPlaceholder ?? placeholder
const handleValueChange = React.useCallback(
(inputVal: string) => {
const q = inputVal.trim()
const match = options.find(
(o) =>
o.label.toLowerCase() === q.toLowerCase() ||
o.value.toLowerCase() === q.toLowerCase(),
)
if (match) {
onChange(match.value)
return
}
if (allowFreeText) {
onChange(inputVal)
}
},
[options, onChange, allowFreeText],
)
return (
<Autocomplete
items={options}
value={value}
onValueChange={handleValueChange}
itemToStringValue={(item) => item.label}
mode="list"
autoHighlight
openOnInputClick
disabled={disabled}
>
<div className="relative w-full">
{leading ? (
<span className="pointer-events-none absolute start-2.5 top-1/2 z-10 size-4 -translate-y-1/2 [&_svg]:size-full">
{leading}
</span>
) : null}
<AutocompleteInput
id={id}
placeholder={trimmedValue ? undefined : inputPlaceholder}
showTrigger
showClear={Boolean(trimmedValue)}
className={cn(leading && 'ps-8', className)}
/>
</div>
<AutocompleteContent>
<AutocompleteEmpty>{emptyText}</AutocompleteEmpty>
<AutocompleteList>
{(item) => {
const isSelected = item.value.toLowerCase() === trimmedValue.toLowerCase()
return (
<AutocompleteItem
key={item.value}
value={item}
className="gap-2.5 px-2 py-1.5"
>
{item.leading ? (
<span className="relative z-1 size-4 shrink-0">{item.leading}</span>
) : null}
<span className="relative z-1 min-w-0 flex-1">
<TruncatedText>{item.label}</TruncatedText>
</span>
{isSelected ? (
<CheckIcon className="relative z-1 size-4 shrink-0 opacity-60" />
) : null}
</AutocompleteItem>
)
}}
</AutocompleteList>
</AutocompleteContent>
</Autocomplete>
)
}
+22
View File
@@ -0,0 +1,22 @@
import { cn } from '@cdnmanager/ui/lib/utils'
import { countryCodeFromName, getCountryFlagUrl } from '@/lib/country-labels'
interface CountryFlagProps {
code?: string
country?: string
className?: string
}
export function CountryFlag({ code, country, className }: CountryFlagProps) {
const resolvedCode = code ?? (country ? countryCodeFromName(country) : undefined)
const url = getCountryFlagUrl(resolvedCode)
if (!url) return null
return (
<img
src={url}
alt=""
className={cn('size-4 shrink-0 rounded-full object-cover', className)}
/>
)
}
+29
View File
@@ -0,0 +1,29 @@
/** ISO → русское название (seed fleet locations). */
const COUNTRY_NAME_BY_CODE: Record<string, string> = {
RU: 'Россия',
DE: 'Германия',
NL: 'Нидерланды',
FI: 'Финляндия',
FR: 'Франция',
}
const COUNTRY_CODE_BY_NAME: Record<string, string> = Object.fromEntries(
Object.entries(COUNTRY_NAME_BY_CODE).map(([code, name]) => [name.toLowerCase(), code]),
)
export function countryNameFromCode(code: string | null | undefined): string {
if (!code) return ''
return COUNTRY_NAME_BY_CODE[code.toUpperCase()] ?? code
}
export function countryCodeFromName(name: string | null | undefined): string {
if (!name?.trim()) return ''
const trimmed = name.trim()
if (trimmed.length === 2) return trimmed.toUpperCase()
return COUNTRY_CODE_BY_NAME[trimmed.toLowerCase()] ?? ''
}
export function getCountryFlagUrl(code?: string): string | undefined {
if (!code || code.length !== 2) return undefined
return `https://flagcdn.com/${code.toLowerCase()}.svg`
}
+105 -13
View File
@@ -25,6 +25,13 @@ import { Button } from '@cdnmanager/ui/components/button'
import { Input } from '@cdnmanager/ui/components/input'
import { Label } from '@cdnmanager/ui/components/label'
import { SelectField } from '@/components/select-field'
import { AutoCompleteInput } from '@/components/auto-complete-input'
import { CountryFlag } from '@/components/country-flag'
import { FormFieldSimple } from '@/components/form-field'
import {
countryCodeFromName,
countryNameFromCode,
} from '@/lib/country-labels'
import { queryClient } from '@/lib/query-client'
import {
createNode,
@@ -80,6 +87,8 @@ function NodesPage() {
const [editing, setEditing] = useState<Node | null>(null)
const [deleteId, setDeleteId] = useState<string | null>(null)
const [preview, setPreview] = useState('')
const [countryName, setCountryName] = useState('')
const [locationQuery, setLocationQuery] = useState('')
const form = useForm<FormValues>({
resolver: zodResolver(formSchema),
@@ -102,6 +111,56 @@ function NodesPage() {
const watchIndex = form.watch('indexNum')
const watchProvider = form.watch('providerTag')
const countryCode = countryCodeFromName(countryName)
const countryOptions = useMemo(() => {
const codes = new Set<string>()
for (const loc of locations) {
if (loc.country) codes.add(loc.country)
}
return [...codes]
.map((code) => {
const name = countryNameFromCode(code)
return {
value: name,
label: name,
leading: <CountryFlag code={code} country={name} />,
}
})
.sort((a, b) => a.label.localeCompare(b.label, 'ru'))
}, [locations])
const locationOptions = useMemo(() => {
if (!countryCode) return []
return locations
.filter((l) => l.country === countryCode)
.map((l) => ({
value: `${l.code}${l.name}`,
label: `${l.code}${l.name}`,
}))
}, [locations, countryCode])
function locationLabel(locationId: string): string {
const loc = locations.find((l) => l.id === locationId)
return loc ? `${loc.code}${loc.name}` : ''
}
function countryNameForLocationId(locationId: string): string {
const code = locations.find((l) => l.id === locationId)?.country
return countryNameFromCode(code)
}
function locationIdFromDisplay(display: string): string {
const q = display.trim().toLowerCase()
if (!q) return ''
const match = locations.find((l) => {
if (countryCode && l.country !== countryCode) return false
const label = `${l.code}${l.name}`.toLowerCase()
return label === q || l.code.toLowerCase() === q || l.name.toLowerCase() === q
})
return match?.id ?? ''
}
async function refreshPreview() {
if (!watchZone || !watchLoc || !watchRole) return
try {
@@ -148,6 +207,8 @@ function NodesPage() {
toast.success(editing ? 'Нода обновлена' : 'Нода создана')
setSheetOpen(false)
setEditing(null)
setCountryName('')
setLocationQuery('')
form.reset()
void qc.invalidateQueries({ queryKey: ['fleet'] })
},
@@ -267,6 +328,8 @@ function NodesPage() {
onClick={() => {
const n = row.original
setEditing(n)
setCountryName(countryNameForLocationId(n.locationId))
setLocationQuery(locationLabel(n.locationId))
form.reset({
zoneId: n.zoneId,
locationId: n.locationId,
@@ -306,9 +369,12 @@ function NodesPage() {
size="sm"
onClick={() => {
setEditing(null)
const firstLoc = locations[0]
setCountryName(countryNameFromCode(firstLoc?.country))
setLocationQuery(firstLoc ? `${firstLoc.code}${firstLoc.name}` : '')
form.reset({
zoneId: zones[0]?.id ?? '',
locationId: locations[0]?.id ?? '',
locationId: firstLoc?.id ?? '',
role: 'gw',
indexNum: 1,
ipv4: '',
@@ -396,21 +462,47 @@ function NodesPage() {
</div>
) : null}
<div className="flex flex-col gap-2">
<Label>Локация</Label>
<SelectField
value={form.watch('locationId')}
onValueChange={(v) => {
form.setValue('locationId', v ?? '')
<FormFieldSimple label="Страна" htmlFor="node-country">
<AutoCompleteInput
id="node-country"
placeholder="Любая"
value={countryName}
onChange={(v) => {
setCountryName(v)
const nextCode = countryCodeFromName(v)
const currentLoc = locations.find((l) => l.id === form.getValues('locationId'))
if (!nextCode || !currentLoc || currentLoc.country !== nextCode) {
form.setValue('locationId', '')
setLocationQuery('')
setPreview('')
}
void refreshPreview()
}}
placeholder="Локация"
options={locations.map((l) => ({
value: l.id,
label: `${l.code}${l.name}`,
}))}
options={countryOptions}
searchPlaceholder="Поиск страны…"
emptyText="Нет вариантов"
/>
</div>
</FormFieldSimple>
<FormFieldSimple label="Локация" htmlFor="node-location">
<AutoCompleteInput
id="node-location"
placeholder="Любая"
value={locationQuery}
onChange={(v) => {
setLocationQuery(v)
const id = locationIdFromDisplay(v)
form.setValue('locationId', id)
const loc = locations.find((l) => l.id === id)
if (loc?.country) setCountryName(countryNameFromCode(loc.country))
void refreshPreview()
}}
options={locationOptions}
searchPlaceholder="Поиск локации…"
emptyText={countryCode ? 'Нет вариантов' : 'Сначала выберите страну'}
showLeadingInInput={false}
disabled={!countryCode}
/>
</FormFieldSimple>
<div className="grid grid-cols-2 gap-3">
<div className="flex flex-col gap-2">