address-service/client/src/App.jsx

500 lines
16 KiB
JavaScript
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 { 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 (
<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 [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 (
<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 } }}>
<Typography variant="body2" color="text.secondary" sx={{ mb: 3 }}>
Субъект РФ → населённый пункт → улица → дом
</Typography>
<Stack spacing={2.5}>
<AddressSelect
inputId="region-search"
label="Субъект РФ"
icon={<AccountBalanceOutlined fontSize="small" />}
value={region}
onChange={selectRegion}
loadOptions={findOptions(loadRegions)}
placeholder="Начните вводить название субъекта РФ"
noOptionsMessage={twoCharHint("Субъект РФ")}
loadingMessage={() => "Ищем субъект РФ…"}
/>
<AddressSelect
inputId="locality-search"
label="Населённый пункт"
icon={<LocationCityOutlined fontSize="small" />}
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={() => "Ищем населённый пункт…"}
/>
<AddressSelect
inputId="street-search"
label="Улица / СНТ"
icon={<SignpostOutlined fontSize="small" />}
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={() => "Ищем улицу…"}
/>
<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.id) : [],
)}
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>
);
}