681 lines
22 KiB
JavaScript
681 lines
22 KiB
JavaScript
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 FormControlLabel from "@mui/material/FormControlLabel";
|
||
import InputAdornment from "@mui/material/InputAdornment";
|
||
import Paper from "@mui/material/Paper";
|
||
import Stack from "@mui/material/Stack";
|
||
import Switch from "@mui/material/Switch";
|
||
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 SearchOutlined from "@mui/icons-material/SearchOutlined";
|
||
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();
|
||
}
|
||
|
||
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();
|
||
}
|
||
|
||
const LOCALITY_LEVELS = new Set([2, 5, 6]);
|
||
const STREET_LEVELS = new Set([7, 8]);
|
||
|
||
function chainLabels(address, levels) {
|
||
return addressChain(address)
|
||
.filter((item) => levels.has(item.level))
|
||
.map((item) => item.label)
|
||
.join(", ");
|
||
}
|
||
|
||
function localityPathLabel(address) {
|
||
return chainLabels(address, LOCALITY_LEVELS) || addressTitle(address);
|
||
}
|
||
|
||
function streetPathLabel(address) {
|
||
return chainLabels(address, STREET_LEVELS) || addressTitle(address);
|
||
}
|
||
|
||
function nearestLocality(address) {
|
||
for (let node = address; node; node = node.parent) {
|
||
if (node.level === 1) return null;
|
||
if (LOCALITY_LEVELS.has(node.level)) return node;
|
||
}
|
||
return null;
|
||
}
|
||
|
||
function toAddressOption(address) {
|
||
return {
|
||
value: address.fias_id,
|
||
label: address.short_label || localityPathLabel(address),
|
||
meta: `${levelNames[address.level] || "Адрес"} · ${address.region_code}`,
|
||
address,
|
||
};
|
||
}
|
||
|
||
function toRegionOption(address) {
|
||
return {
|
||
value: address.fias_id,
|
||
label: address.label || addressTitle(address),
|
||
meta: `Субъект РФ · ${address.region_code}`,
|
||
address,
|
||
};
|
||
}
|
||
|
||
function toStreetOption(address) {
|
||
return {
|
||
value: address.fias_id,
|
||
label: address.short_label || streetPathLabel(address),
|
||
address,
|
||
};
|
||
}
|
||
|
||
function suggestPathLabel(address) {
|
||
return addressChain(address)
|
||
.filter((item) => item.level !== 1)
|
||
.map((item) => item.label)
|
||
.join(", ");
|
||
}
|
||
|
||
function toSuggestOption(address) {
|
||
return {
|
||
value: address.fias_id,
|
||
label: address.parent ? suggestPathLabel(address) : address.full_label || addressTitle(address),
|
||
address,
|
||
};
|
||
}
|
||
|
||
function toHouseOption(house) {
|
||
return {
|
||
value: house.fias_id,
|
||
label: house.display_number,
|
||
house,
|
||
};
|
||
}
|
||
|
||
function compactAddress(address) {
|
||
if (!address) return null;
|
||
return {
|
||
fias_id: address.fias_id,
|
||
label: address.label || addressTitle(address),
|
||
short_label: address.short_label || address.label || addressTitle(address),
|
||
level: address.level,
|
||
region_code: address.region_code,
|
||
full_label: address.full_label,
|
||
};
|
||
}
|
||
|
||
function compactRegion(address) {
|
||
if (!address) return null;
|
||
return {
|
||
fias_id: address.fias_id,
|
||
label: address.label || addressTitle(address),
|
||
region_code: address.region_code,
|
||
};
|
||
}
|
||
|
||
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, street) {
|
||
const extra = street.id
|
||
? { parent_id: String(street.id) }
|
||
: { parent_fias_id: String(street.fias_id) };
|
||
if (query.trim()) extra.query = query.trim();
|
||
const data = await requestItems("houses", extra);
|
||
return data.items.map(toHouseOption);
|
||
}
|
||
|
||
const addressPath = (path, compact) => (compact ? `${path}/compact` : path);
|
||
|
||
const loadRegions = (query, { includeParent, compact } = {}) =>
|
||
loadAddresses(
|
||
addressPath("regions", compact),
|
||
query,
|
||
{
|
||
include_parent: String(Boolean(includeParent)),
|
||
},
|
||
2,
|
||
toRegionOption,
|
||
);
|
||
const loadLocalities = (query, regionId, { includeParent, compact } = {}) =>
|
||
loadAddresses(addressPath("localities", compact), query, {
|
||
region_id: String(regionId),
|
||
include_parent: String(Boolean(includeParent)),
|
||
});
|
||
const loadStreets = (query, { parentId, parentFiasId, regionCode, includeParent, compact } = {}) =>
|
||
loadAddresses(
|
||
addressPath("streets", compact),
|
||
query,
|
||
{
|
||
include_parent: String(Boolean(includeParent)),
|
||
...(parentId
|
||
? { parent_id: String(parentId) }
|
||
: parentFiasId
|
||
? { parent_fias_id: String(parentFiasId) }
|
||
: {}),
|
||
...(regionCode ? { region_code: String(regionCode) } : {}),
|
||
},
|
||
2,
|
||
toStreetOption,
|
||
);
|
||
const loadSuggest = (query, regionCode, { includeParent, compact } = {}) =>
|
||
loadAddresses(
|
||
addressPath("suggest", compact),
|
||
query,
|
||
{
|
||
region_code: String(regionCode),
|
||
include_parent: String(Boolean(includeParent)),
|
||
},
|
||
2,
|
||
toSuggestOption,
|
||
);
|
||
|
||
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 (
|
||
<Autocomplete
|
||
id={inputId}
|
||
disabled={disabled}
|
||
options={options}
|
||
value={value}
|
||
inputValue={inputValue}
|
||
filterOptions={(items) => 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 (
|
||
<Box key={option.value || key} component="li" {...optionProps}>
|
||
<Box sx={{ py: 0.25 }}>
|
||
<Typography variant="body2">{option.label}</Typography>
|
||
{option.meta ? (
|
||
<Typography variant="caption" color="text.secondary">
|
||
{option.meta}
|
||
</Typography>
|
||
) : null}
|
||
</Box>
|
||
</Box>
|
||
);
|
||
}}
|
||
renderInput={(params) => (
|
||
<TextField
|
||
{...params}
|
||
label={label}
|
||
placeholder={placeholder}
|
||
slotProps={{
|
||
...params.slotProps,
|
||
input: {
|
||
...params.slotProps.input,
|
||
startAdornment: (
|
||
<>
|
||
<InputAdornment position="start">{icon}</InputAdornment>
|
||
{params.slotProps.input.startAdornment}
|
||
</>
|
||
),
|
||
endAdornment: (
|
||
<>
|
||
{loading ? <CircularProgress color="inherit" size={20} /> : null}
|
||
{params.slotProps.input.endAdornment}
|
||
</>
|
||
),
|
||
},
|
||
}}
|
||
/>
|
||
)}
|
||
/>
|
||
);
|
||
}
|
||
|
||
export default function App() {
|
||
const [region, setRegion] = useState(null);
|
||
const [suggest, setSuggest] = useState(null);
|
||
const [locality, setLocality] = useState(null);
|
||
const [street, setStreet] = useState(null);
|
||
const [house, setHouse] = useState(null);
|
||
const [includeParent, setIncludeParent] = useState(false);
|
||
const [quickSearch, setQuickSearch] = useState(false);
|
||
const [compact, setCompact] = useState(false);
|
||
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);
|
||
setSuggest(null);
|
||
setLocality(null);
|
||
setStreet(null);
|
||
setHouse(null);
|
||
};
|
||
|
||
const selectLocality = (option) => {
|
||
setLocality(option);
|
||
setSuggest(null);
|
||
setStreet(null);
|
||
setHouse(null);
|
||
};
|
||
|
||
const selectStreet = (option) => {
|
||
setStreet(option);
|
||
setHouse(null);
|
||
setSuggest(option?.address ? toSuggestOption(option.address) : null);
|
||
if (locality || !option?.address) return;
|
||
const localityNode = nearestLocality(option.address);
|
||
if (localityNode) setLocality(toAddressOption(localityNode));
|
||
};
|
||
|
||
const selectSuggest = (option) => {
|
||
setSuggest(option);
|
||
setStreet(option?.address ? toStreetOption(option.address) : null);
|
||
setHouse(null);
|
||
const localityNode = option?.address ? nearestLocality(option.address) : null;
|
||
setLocality(localityNode ? toAddressOption(localityNode) : null);
|
||
};
|
||
|
||
const result = region
|
||
? compact
|
||
? {
|
||
region: compactRegion(region.address),
|
||
locality: compactAddress(locality?.address),
|
||
street: compactAddress(street?.address),
|
||
house: house?.house ?? null,
|
||
chain: addressChain(street?.address || locality?.address || region.address).map(
|
||
compactAddress,
|
||
),
|
||
}
|
||
: {
|
||
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 (
|
||
<Box sx={{ minHeight: "100vh", bgcolor: "background.default" }}>
|
||
<AppBar position="sticky">
|
||
<Container maxWidth="md">
|
||
<Toolbar disableGutters>
|
||
<MapOutlined sx={{ mr: 1.5 }} />
|
||
<Typography variant="h6" component="h1" sx={{ flexGrow: 1 }}>
|
||
Поиск адреса
|
||
</Typography>
|
||
<Chip
|
||
label="ФИАС"
|
||
size="small"
|
||
variant="outlined"
|
||
sx={{ color: "inherit", borderColor: "rgba(255,255,255,0.48)" }}
|
||
/>
|
||
</Toolbar>
|
||
</Container>
|
||
</AppBar>
|
||
|
||
<Container maxWidth="md" sx={{ py: { xs: 2, sm: 4 } }}>
|
||
<Stack spacing={3}>
|
||
<Paper elevation={1} sx={{ p: { xs: 2, sm: 3 } }}>
|
||
<Stack direction="row" useFlexGap flexWrap="wrap" spacing={1} sx={{ mb: 3 }}>
|
||
<FormControlLabel
|
||
sx={{ mr: 1 }}
|
||
control={
|
||
<Switch
|
||
checked={includeParent}
|
||
onChange={(event) => setIncludeParent(event.target.checked)}
|
||
size="small"
|
||
/>
|
||
}
|
||
label="Выводить родителей"
|
||
/>
|
||
<FormControlLabel
|
||
sx={{ mr: 1 }}
|
||
control={
|
||
<Switch
|
||
checked={quickSearch}
|
||
onChange={(event) => setQuickSearch(event.target.checked)}
|
||
size="small"
|
||
/>
|
||
}
|
||
label="Быстрый поиск"
|
||
/>
|
||
<FormControlLabel
|
||
sx={{ mr: 0 }}
|
||
control={
|
||
<Switch
|
||
checked={compact}
|
||
onChange={(event) => setCompact(event.target.checked)}
|
||
size="small"
|
||
/>
|
||
}
|
||
label="Короткий вывод"
|
||
/>
|
||
</Stack>
|
||
|
||
<Stack spacing={2.5}>
|
||
<AddressSelect
|
||
inputId="region-search"
|
||
label="Субъект РФ"
|
||
icon={<AccountBalanceOutlined fontSize="small" />}
|
||
selectKey={`${String(includeParent)}-${compact}`}
|
||
value={region}
|
||
onChange={selectRegion}
|
||
loadOptions={findOptions((query) =>
|
||
loadRegions(query, { includeParent, compact }),
|
||
)}
|
||
placeholder="Начните вводить название субъекта РФ"
|
||
noOptionsMessage={twoCharHint("Субъект РФ")}
|
||
loadingMessage={() => "Ищем субъект РФ…"}
|
||
/>
|
||
|
||
{quickSearch ? (
|
||
<AddressSelect
|
||
inputId="suggest-search"
|
||
label="Быстрый поиск"
|
||
icon={<SearchOutlined fontSize="small" />}
|
||
selectKey={`${region?.value || "no-region"}-${includeParent}-${compact}`}
|
||
value={suggest}
|
||
onChange={selectSuggest}
|
||
disabled={!region}
|
||
loadOptions={findOptions((query) =>
|
||
region
|
||
? loadSuggest(query, region.address.region_code, { includeParent, compact })
|
||
: [],
|
||
)}
|
||
placeholder={
|
||
region ? "Поиск по адресному объекту" : "Сначала выберите субъект РФ"
|
||
}
|
||
noOptionsMessage={twoCharHint("Адрес")}
|
||
loadingMessage={() => "Ищем адрес…"}
|
||
/>
|
||
) : (
|
||
<>
|
||
<AddressSelect
|
||
inputId="locality-search"
|
||
label="Населённый пункт"
|
||
icon={<LocationCityOutlined fontSize="small" />}
|
||
selectKey={`${region?.value || "no-region"}-${includeParent}-${compact}`}
|
||
value={locality}
|
||
onChange={selectLocality}
|
||
disabled={!region}
|
||
loadOptions={findOptions((query) =>
|
||
region
|
||
? loadLocalities(query, region.address.region_code, {
|
||
includeParent,
|
||
compact,
|
||
})
|
||
: [],
|
||
)}
|
||
placeholder={region ? "Например, Владивосток" : "Сначала выберите субъект РФ"}
|
||
noOptionsMessage={twoCharHint("Населённый пункт")}
|
||
loadingMessage={() => "Ищем населённый пункт…"}
|
||
/>
|
||
|
||
<AddressSelect
|
||
inputId="street-search"
|
||
label="Улица / СНТ"
|
||
icon={<SignpostOutlined fontSize="small" />}
|
||
selectKey={`${region?.value || "no-region"}-${locality?.value || "no-locality"}-${includeParent}-${compact}`}
|
||
value={street}
|
||
onChange={selectStreet}
|
||
disabled={!region}
|
||
loadOptions={findOptions((query) =>
|
||
region
|
||
? loadStreets(query, {
|
||
parentId: locality?.address.id,
|
||
parentFiasId: locality?.address.fias_id,
|
||
regionCode: region.address.region_code,
|
||
includeParent,
|
||
compact,
|
||
})
|
||
: [],
|
||
)}
|
||
placeholder={
|
||
region ? "Например, Светланская или СНТ" : "Сначала выберите субъект РФ"
|
||
}
|
||
noOptionsMessage={twoCharHint("Улица или СНТ")}
|
||
loadingMessage={() => "Ищем улицу…"}
|
||
/>
|
||
</>
|
||
)}
|
||
|
||
<AddressSelect
|
||
inputId="house-search"
|
||
label="Дом"
|
||
icon={<HomeOutlined fontSize="small" />}
|
||
selectKey={street?.value || "no-street"}
|
||
value={house}
|
||
onChange={setHouse}
|
||
disabled={!street}
|
||
defaultOptions
|
||
loadOptions={findOptions((query) =>
|
||
street ? loadHouses(query, street.address) : [],
|
||
)}
|
||
placeholder={street ? "Например, 10" : "Сначала выберите улицу или СНТ"}
|
||
noOptionsMessage={() => "Дом не найден"}
|
||
loadingMessage={() => "Ищем дом…"}
|
||
/>
|
||
</Stack>
|
||
|
||
{error ? (
|
||
<Alert severity="error" sx={{ mt: 2 }}>
|
||
{error}
|
||
</Alert>
|
||
) : null}
|
||
</Paper>
|
||
|
||
<Paper elevation={1} sx={{ overflow: "hidden" }}>
|
||
<Box
|
||
sx={{
|
||
display: "flex",
|
||
alignItems: "center",
|
||
justifyContent: "space-between",
|
||
px: 2,
|
||
py: 1.5,
|
||
borderBottom: 1,
|
||
borderColor: "divider",
|
||
bgcolor: "action.hover",
|
||
}}
|
||
>
|
||
<Typography variant="overline" color="text.secondary">
|
||
Результат
|
||
</Typography>
|
||
<Chip label="JSON" size="small" color="primary" variant="outlined" />
|
||
</Box>
|
||
|
||
{result ? (
|
||
<Box sx={{ px: 2, pt: 2 }}>
|
||
<Stack direction="row" useFlexGap spacing={1} sx={{ mb: 2, flexWrap: "wrap" }}>
|
||
{result.chain.map((item) => (
|
||
<Chip
|
||
key={item.fias_id}
|
||
size="small"
|
||
label={item.label}
|
||
/>
|
||
))}
|
||
{result.house ? (
|
||
<Chip size="small" color="primary" label={result.house.display_number} />
|
||
) : null}
|
||
</Stack>
|
||
<Box
|
||
component="pre"
|
||
sx={{
|
||
m: 0,
|
||
mx: -2,
|
||
mb: -0,
|
||
p: 2,
|
||
overflow: "auto",
|
||
bgcolor: "#1e1e1e",
|
||
color: "#c8e6c9",
|
||
fontFamily: '"Roboto Mono", "SFMono-Regular", Consolas, monospace',
|
||
fontSize: 13,
|
||
lineHeight: 1.65,
|
||
whiteSpace: "pre-wrap",
|
||
}}
|
||
>
|
||
{JSON.stringify(result, null, 2)}
|
||
</Box>
|
||
</Box>
|
||
) : (
|
||
<Stack spacing={1} sx={{ py: 7, px: 2, color: "text.secondary", alignItems: "center" }}>
|
||
<CodeOutlined sx={{ fontSize: 40, opacity: 0.35 }} />
|
||
<Typography variant="body2" align="center">
|
||
Выберите поле, и его JSON появится здесь.
|
||
</Typography>
|
||
</Stack>
|
||
)}
|
||
</Paper>
|
||
</Stack>
|
||
</Container>
|
||
</Box>
|
||
);
|
||
}
|