import { useEffect, useRef, useState } from "react"; import Alert from "@mui/material/Alert"; import AppBar from "@mui/material/AppBar"; import Autocomplete from "@mui/material/Autocomplete"; import Box from "@mui/material/Box"; import Chip from "@mui/material/Chip"; import CircularProgress from "@mui/material/CircularProgress"; import Container from "@mui/material/Container"; import InputAdornment from "@mui/material/InputAdornment"; import Paper from "@mui/material/Paper"; import Stack from "@mui/material/Stack"; import TextField from "@mui/material/TextField"; import Toolbar from "@mui/material/Toolbar"; import Typography from "@mui/material/Typography"; import AccountBalanceOutlined from "@mui/icons-material/AccountBalanceOutlined"; import CodeOutlined from "@mui/icons-material/CodeOutlined"; import HomeOutlined from "@mui/icons-material/HomeOutlined"; import LocationCityOutlined from "@mui/icons-material/LocationCityOutlined"; import MapOutlined from "@mui/icons-material/MapOutlined"; import SignpostOutlined from "@mui/icons-material/SignpostOutlined"; const API_BASE_URL = ( import.meta.env.VITE_API_BASE_URL || (import.meta.env.DEV ? "/address-service/api" : "") ).replace(/\/$/, ""); function requestUrl(path, extra = {}) { const parameters = new URLSearchParams({ limit: "20", ...extra }); const suffix = `${path}?${parameters}`; if (API_BASE_URL) { return `${API_BASE_URL}/${suffix}`; } const origin = window.location.pathname.endsWith("/") ? window.location.href : `${window.location.href}/`; return new URL(`api/${suffix}`, origin).toString(); } const levelNames = { 1: "Субъект РФ", 2: "Район", 3: "Муниципальный район", 4: "Поселение", 5: "Город", 6: "Населённый пункт", 7: "Планировочная структура", 8: "Улица", }; async function requestItems(path, extra = {}) { const response = await fetch(requestUrl(path, extra)); if (!response.ok) throw new Error(`Ошибка API: ${response.status}`); return response.json(); } function addressTitle(address) { return address.label || `${address.type_name} ${address.name}`.trim(); } const NESTED_PARENT_LEVELS = new Set([2, 7]); function addressChain(address) { const items = []; const seen = new Set(); for (let node = address; node && !seen.has(node.id); node = node.parent) { seen.add(node.id); items.push({ level: node.level, type_name: node.type_name, name: node.name, label: addressTitle(node), fias_id: node.fias_id, }); } return items.reverse(); } function toAddressOption(address) { const parent = address.parent; const showParent = parent && NESTED_PARENT_LEVELS.has(parent.level); return { value: address.fias_id, label: showParent ? `${addressTitle(address)} · ${addressTitle(parent)}` : addressTitle(address), meta: `${levelNames[address.level] || "Адрес"} · ${address.region_code}`, address, }; } function streetAncestorContext(address) { const parts = []; const seen = new Set([address.id]); for (let node = address.parent; node && !seen.has(node.id); node = node.parent) { seen.add(node.id); if (node.level === 1) continue; parts.push(addressTitle(node)); } return parts.reverse().join(", "); } function toStreetOption(address) { return { value: address.fias_id, label: addressTitle(address), meta: streetAncestorContext(address), address, }; } function toHouseOption(house) { return { value: house.fias_id, label: house.display_number, house, }; } async function loadAddresses(path, query, extra, minLength = 2, toOption = toAddressOption) { const normalizedQuery = query.trim(); if (normalizedQuery.length < minLength) return []; const data = await requestItems(path, { query: normalizedQuery, ...extra }); return data.items.map(toOption); } async function loadHouses(query, streetId) { const extra = { parent_id: String(streetId) }; if (query.trim()) extra.query = query.trim(); const data = await requestItems("houses", extra); return data.items.map(toHouseOption); } const loadRegions = (query) => loadAddresses("regions", query); const loadLocalities = (query, regionId) => loadAddresses("localities", query, { region_id: String(regionId) }); const loadStreets = (query, { parentId, regionCode } = {}) => loadAddresses( "streets", query, { ...(parentId ? { parent_id: String(parentId) } : {}), ...(regionCode ? { region_code: String(regionCode) } : {}), }, 2, toStreetOption, ); function twoCharHint(kind) { return ({ inputValue }) => inputValue.trim().length < 2 ? "Введите хотя бы 2 символа" : `${kind} не найден`; } function AddressSelect({ inputId, label, value, onChange, loadOptions, placeholder, disabled, noOptionsMessage, loadingMessage, selectKey, defaultOptions = false, icon, }) { const [inputValue, setInputValue] = useState(""); const [options, setOptions] = useState([]); const [loading, setLoading] = useState(false); const loadOptionsRef = useRef(loadOptions); const valueRef = useRef(value); const requestIdRef = useRef(0); loadOptionsRef.current = loadOptions; valueRef.current = value; useEffect(() => { setInputValue(value?.label ?? ""); setOptions(value ? [value] : []); }, [value, selectKey]); useEffect(() => { if (disabled) { setLoading(false); return undefined; } const query = inputValue; if (!defaultOptions && query.trim().length < 2) { setOptions(valueRef.current ? [valueRef.current] : []); setLoading(false); return undefined; } const requestId = ++requestIdRef.current; const delay = defaultOptions && !query.trim() ? 0 : 300; const timer = window.setTimeout(async () => { setLoading(true); try { const items = await loadOptionsRef.current(query); if (requestId !== requestIdRef.current) return; const selected = valueRef.current; setOptions( selected && !items.some((item) => item.value === selected.value) ? [selected, ...items] : items, ); } catch { if (requestId !== requestIdRef.current) return; setOptions(valueRef.current ? [valueRef.current] : []); } finally { if (requestId === requestIdRef.current) setLoading(false); } }, delay); return () => window.clearTimeout(timer); }, [inputValue, disabled, selectKey, defaultOptions]); return ( items} getOptionLabel={(option) => option?.label ?? ""} getOptionKey={(option) => option.value} isOptionEqualToValue={(left, right) => left.value === right.value} loading={loading} loadingText={loadingMessage()} noOptionsText={noOptionsMessage({ inputValue })} autoHighlight clearOnBlur={false} onChange={(_, next) => onChange(next)} onInputChange={(_, next) => setInputValue(next)} slotProps={{ paper: { elevation: 3 } }} renderOption={(props, option) => { const { key, ...optionProps } = props; return ( {option.label} {option.meta ? ( {option.meta} ) : null} ); }} renderInput={(params) => ( {icon} {params.slotProps.input.startAdornment} ), endAdornment: ( <> {loading ? : null} {params.slotProps.input.endAdornment} ), }, }} /> )} /> ); } export default function App() { const [region, setRegion] = useState(null); const [locality, setLocality] = useState(null); const [street, setStreet] = useState(null); const [house, setHouse] = useState(null); const [error, setError] = useState(""); const findOptions = (loader) => async (query) => { try { setError(""); return await loader(query); } catch (requestError) { setError(requestError.message || "Не удалось выполнить поиск"); return []; } }; const selectRegion = (option) => { setRegion(option); setLocality(null); setStreet(null); setHouse(null); }; const selectLocality = (option) => { setLocality(option); setStreet(null); setHouse(null); }; const selectStreet = (option) => { setStreet(option); setHouse(null); if (locality || !option?.address?.parent) return; const parent = option.address.parent; if (parent.level !== 1) { setLocality(toAddressOption(parent)); } }; const result = region ? { region: region.address, locality: locality?.address ?? null, street: street?.address ?? null, house: house?.house ?? null, chain: addressChain(street?.address || locality?.address || region.address), } : null; return ( Поиск адреса Субъект РФ → населённый пункт → улица → дом } value={region} onChange={selectRegion} loadOptions={findOptions(loadRegions)} placeholder="Начните вводить название субъекта РФ" noOptionsMessage={twoCharHint("Субъект РФ")} loadingMessage={() => "Ищем субъект РФ…"} /> } selectKey={region?.value || "no-region"} value={locality} onChange={selectLocality} disabled={!region} loadOptions={findOptions((query) => region ? loadLocalities(query, region.address.region_code) : [], )} placeholder={region ? "Например, Владивосток" : "Сначала выберите субъект РФ"} noOptionsMessage={twoCharHint("Населённый пункт")} loadingMessage={() => "Ищем населённый пункт…"} /> } selectKey={`${region?.value || "no-region"}-${locality?.value || "no-locality"}`} value={street} onChange={selectStreet} disabled={!region} loadOptions={findOptions((query) => region ? loadStreets(query, { parentId: locality?.address.id, regionCode: region.address.region_code, }) : [], )} placeholder={ region ? "Например, Светланская или СНТ" : "Сначала выберите субъект РФ" } noOptionsMessage={twoCharHint("Улица или СНТ")} loadingMessage={() => "Ищем улицу…"} /> } selectKey={street?.value || "no-street"} value={house} onChange={setHouse} disabled={!street} defaultOptions loadOptions={findOptions((query) => street ? loadHouses(query, street.address.id) : [], )} placeholder={street ? "Например, 10" : "Сначала выберите улицу или СНТ"} noOptionsMessage={() => "Дом не найден"} loadingMessage={() => "Ищем дом…"} /> {error ? ( {error} ) : null} Результат {result ? ( {result.chain.map((item) => ( ))} {result.house ? ( ) : null} {JSON.stringify(result, null, 2)} ) : ( Выберите поле, и его JSON появится здесь. )} ); }