Files
admin-front/src/pages/attractions/AttractionForm.tsx
T
2026-10-06 10:23:46 +03:00

188 lines
6.2 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import type { FormInstance } from 'antd'
import { Button, Form, Input, InputNumber, Select, Space } from 'antd'
import { MinusCircleOutlined, PlusOutlined } from '@ant-design/icons'
import type { CreateAttractionRequest, CvProfile, UpdateAttractionRequest } from '@/api/types'
import { useIsMobile } from '@/hooks/useIsMobile'
import { cvProfileOptions } from '@/utils/format'
export interface AttractionFormValues {
name: string
cvProfile: CvProfile
about?: string
address?: string
latitude?: number | null
longitude?: number | null
facts?: (string | undefined)[]
}
export interface AttractionFormInitialValues {
name: string
cvProfile: CvProfile
about?: string | null
address?: string | null
latitude?: number | null
longitude?: number | null
facts?: string[] | null
}
function normalizeFacts(facts: (string | undefined)[] | undefined): string[] {
return (facts ?? [])
.map((f) => f?.trim())
.filter((f): f is string => !!f)
}
export function toCreateRequest(
areaId: string,
v: AttractionFormValues,
): CreateAttractionRequest {
const facts = normalizeFacts(v.facts)
return {
areaId,
name: v.name.trim(),
cvProfile: v.cvProfile,
about: v.about?.trim() || undefined,
address: v.address?.trim() || undefined,
latitude: v.latitude ?? undefined,
longitude: v.longitude ?? undefined,
facts: facts.length ? facts : undefined,
}
}
/**
* PATCH-семантика бэкенда: отсутствующее поле = «не менять»,
* поэтому пустые значения просто не отправляем (API не поддерживает очистку полей).
*/
export function toUpdateRequest(v: AttractionFormValues): UpdateAttractionRequest {
const request: UpdateAttractionRequest = {}
const name = v.name?.trim()
if (name) request.name = name
if (v.cvProfile) request.cvProfile = v.cvProfile
const about = v.about?.trim()
if (about) request.about = about
const address = v.address?.trim()
if (address) request.address = address
if (v.latitude != null) request.latitude = v.latitude
if (v.longitude != null) request.longitude = v.longitude
const facts = normalizeFacts(v.facts)
if (facts.length) request.facts = facts
return request
}
export function AttractionForm({
form,
initialValues,
}: {
form: FormInstance<AttractionFormValues>
initialValues?: AttractionFormInitialValues
}) {
const isMobile = useIsMobile()
return (
<Form
form={form}
layout="vertical"
initialValues={
initialValues && {
name: initialValues.name,
cvProfile: initialValues.cvProfile,
about: initialValues.about ?? undefined,
address: initialValues.address ?? undefined,
latitude: initialValues.latitude ?? undefined,
longitude: initialValues.longitude ?? undefined,
facts: initialValues.facts ?? [],
}
}
>
<Form.Item
name="name"
label="Название"
rules={[{ required: true, message: 'Укажите название' }]}
>
<Input maxLength={255} placeholder="Например, Дом со шпилем" />
</Form.Item>
<Form.Item
name="cvProfile"
label="CV-профиль распознавания"
rules={[{ required: true, message: 'Выберите профиль' }]}
extra="Влияет на алгоритм сопоставления фотографий."
>
<Select options={cvProfileOptions} />
</Form.Item>
<Form.Item name="about" label="Описание">
<Input.TextArea rows={3} maxLength={4000} />
</Form.Item>
<Form.Item name="address" label="Адрес">
<Input maxLength={255} />
</Form.Item>
<Space
size="large"
style={{ display: 'flex' }}
align="start"
direction={isMobile ? 'vertical' : 'horizontal'}
>
<Form.Item
name="latitude"
label="Широта"
style={{ width: isMobile ? '100%' : 220 }}
rules={[
{
validator: (_, value: number | null | undefined) =>
value == null || (value >= -90 && value <= 90)
? Promise.resolve()
: Promise.reject(new Error('Диапазон −90…90')),
},
]}
>
<InputNumber style={{ width: '100%' }} min={-90} max={90} step={0.000001} placeholder="55.751244" />
</Form.Item>
<Form.Item
name="longitude"
label="Долгота"
style={{ width: isMobile ? '100%' : 220 }}
rules={[
{
validator: (_, value: number | null | undefined) =>
value == null || (value >= -180 && value <= 180)
? Promise.resolve()
: Promise.reject(new Error('Диапазон −180…180')),
},
]}
>
<InputNumber style={{ width: '100%' }} min={-180} max={180} step={0.000001} placeholder="37.618423" />
</Form.Item>
</Space>
<Form.Item label="Интересные факты" style={{ marginBottom: 0 }}>
<Form.List name="facts">
{(fields, { add, remove }) => (
<>
{fields.map((field) => (
<div
key={field.key}
style={{ display: 'flex', alignItems: 'baseline', gap: 8, marginBottom: 4 }}
>
<Form.Item
name={field.name}
rules={[{ required: true, message: 'Пустой факт — удалите строку' }]}
noStyle
>
<Input placeholder="Текст факта" maxLength={500} style={{ flex: 1, minWidth: 0 }} />
</Form.Item>
<MinusCircleOutlined onClick={() => remove(field.name)} />
</div>
))}
<Button
type="dashed"
icon={<PlusOutlined />}
onClick={() => add()}
style={{ width: '100%', maxWidth: 472 }}
>
Добавить факт
</Button>
</>
)}
</Form.List>
</Form.Item>
</Form>
)
}