Files
nahodka-front/src/components/MapView.jsx
2026-10-23 00:02:44 +03:00

500 lines
19 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 { useTranslation } from "react-i18next";
import { API_URL, getImageUrl } from "../config/authConstants";
import { useGeolocation, GEO_STATUS } from "../hooks/useGeolocation";
import { whenYmapsReady } from "../utils/ymapsApi";
import { escapeCssUrl, escapeHtml } from "../utils/escapeHtml";
const MARKER_COLORS = {
LOST: "#ff3b30",
LOSS: "#ff3b30",
FOUND: "#34c759",
};
function createMarkerLayout(color, imageUrl, pinId) {
const bgStyle = imageUrl
? `background-image:url('${escapeCssUrl(imageUrl)}');background-size:cover;background-position:center;`
: "";
return window.ymaps.templateLayoutFactory.createClass(
`<div class="f-map-pin" data-pin-id="${escapeHtml(pinId ?? "")}" style="
width:40px;height:40px;
border-radius:50%;
border:3px solid ${color};
box-shadow:0 2px 8px rgba(0,0,0,.35);
overflow:hidden;
background:${imageUrl ? "transparent" : color};
display:flex;align-items:center;justify-content:center;
cursor:pointer;
">
<div style="
width:100%;height:100%;border-radius:50%;
${bgStyle}
"></div>
</div>`,
{
build() {
this.constructor.superclass.build.call(this);
},
}
);
}
const FOCUS_ZOOM = 16;
const COORD_MATCH_TOLERANCE = 0.005;
const MAP_CENTER = [55.751574, 37.573856];
const MAP_ZOOM = 11;
const BOUNDS_DEBOUNCE_MS = 400;
const BOUNDS_RETRY_MS = 120;
const MAX_BOUNDS_ATTEMPTS = 25;
/**
* GET /api/v1/posts/map
*
* Контракт требует границы видимой области карты — без любого из четырёх
* параметров бэкенд отвечает 400. type/category остаются опциональными и
* уезжают тем же запросом.
*/
async function loadMarkers(bounds, type, category) {
const [[minLat, minLng], [maxLat, maxLng]] = bounds;
const params = new URLSearchParams({
minLat: minLat.toString(),
maxLat: maxLat.toString(),
minLng: minLng.toString(),
maxLng: maxLng.toString(),
});
if (type) params.append("type", type);
if (category) params.append("category", category);
const response = await fetch(`${API_URL}/api/v1/posts/map?${params.toString()}`);
if (!response.ok) {
throw new Error(`Failed to load markers: ${response.status}`);
}
return response.json();
}
// Ключ для отсечения повторных запросов с одними и теми же границами.
// Нужен, потому что границы меняются и от действий пользователя (pan/zoom),
// и от программной установки центра — иначе на каждое такое изменение
// улетал бы лишний одинаковый запрос.
function boundsKey(bounds) {
return bounds.map(([lat, lng]) => `${lat.toFixed(5)}:${lng.toFixed(5)}`).join("|");
}
function createPostPlacemark(m) {
const color = MARKER_COLORS[m.type] || MARKER_COLORS.LOST;
const typeLabel = m.type === "FOUND" ? "Находка" : "Потеря";
const imgSrc = m.imageUrl ? getImageUrl(m.imageUrl) : null;
const iconLayout = createMarkerLayout(color, imgSrc, m.id != null ? String(m.id) : "");
return new window.ymaps.Placemark(
[m.latitude, m.longitude],
// hintContent — свойство метки (не опция) и рендерится как HTML:
// заголовок объявления — пользовательский текст, экранируем.
{ hintContent: escapeHtml(m.title || typeLabel) },
{
iconLayout,
iconImageSize: [40, 40],
iconImageOffset: [-20, -20],
// Без явного iconShape карта не может корректно вычислить
// кликабельную область для кастомного HTML-лейаута —
// маркер рисуется, но клики по нему не срабатывают.
iconShape: {
type: "Circle",
coordinates: [20, 20],
radius: 20,
},
hasBalloon: false,
hasHint: true,
}
);
}
/**
* @param {{
* focusPostId?: any, focusLat?: number, focusLng?: number,
* type?: string | null, category?: string | null,
* onPostClick?: (id: any) => void, onBack?: () => void,
* onMarkersChange?: (markers: any[]) => void, onMarkerHover?: (id: string | null) => void,
* highlightId?: string | null, focusTarget?: { lat: number, lng: number, zoom?: number } | null,
* }} props
*/
export default function MapView({
focusPostId,
focusLat,
focusLng,
type = null,
category = null,
onPostClick,
onBack,
// Необязательные пропсы десктопной карты (на мобильном не передаются):
// onMarkersChange — список меток в видимой области после каждой загрузки,
// onMarkerHover — наведение на метку (id | null), highlightId — подсветка
// метки, focusTarget — {lat, lng, zoom?} плавный перелёт к точке.
onMarkersChange,
onMarkerHover,
highlightId = null,
focusTarget = null,
}) {
const { t } = useTranslation();
// tRef нужен, чтобы читать перевод из эффектов, не добавляя t в их deps:
// иначе смена языка пересоздавала бы карту и все маркеры с нуля.
const tRef = useRef(t);
tRef.current = t;
const mapRef = useRef(null);
const ymapRef = useRef(null);
const userMarkerRef = useRef(null);
const markersRef = useRef(null);
const renderMarkersRef = useRef(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
const { coords: geoCoords, status: geoStatus } = useGeolocation({ onMount: true });
const onPostClickRef = useRef(onPostClick);
onPostClickRef.current = onPostClick;
const onMarkersChangeRef = useRef(onMarkersChange);
onMarkersChangeRef.current = onMarkersChange;
const onMarkerHoverRef = useRef(onMarkerHover);
onMarkerHoverRef.current = onMarkerHover;
const placemarksRef = useRef(new Map());
// Фильтры читаются через ref: их смена не должна пересоздавать карту,
// они просто уезжают вместе с границами в том же самом запросе.
const filtersRef = useRef({ type, category });
filtersRef.current = { type, category };
useEffect(() => {
let map;
let destroyed = false;
let debounceTimer = null;
let boundsRetryTimer = null;
let firstLoadDone = false;
let lastBoundsKey = null;
let requestId = 0;
const subscriptions = [];
// Перерисовывает маркеры в текущей видимой области и возвращает
// словарь postId -> [lat, lng] для логики фокуса.
const renderMarkers = (markers) => {
const collection = markersRef.current;
const placemarksById = new Map();
if (!collection) return placemarksById;
collection.removeAll();
placemarksRef.current = new Map();
markers.forEach((m) => {
if (m.latitude == null || m.longitude == null) return;
const placemark = createPostPlacemark(m);
collection.add(placemark);
if (m.id != null) {
const postId = String(m.id);
placemarksById.set(postId, [m.latitude, m.longitude]);
placemarksRef.current.set(postId, placemark);
placemark.events.add("click", () => {
if (onPostClickRef.current) {
onPostClickRef.current(postId);
}
});
placemark.events.add("mouseenter", () => onMarkerHoverRef.current?.(postId));
placemark.events.add("mouseleave", () => onMarkerHoverRef.current?.(null));
}
});
onMarkersChangeRef.current?.(markers.filter((m) => m.latitude != null && m.longitude != null));
return placemarksById;
};
renderMarkersRef.current = renderMarkers;
const focusOnPost = (placemarksById) => {
let target = focusPostId != null
? placemarksById.get(String(focusPostId))
: null;
if (!target && Number.isFinite(focusLat) && Number.isFinite(focusLng)) {
let best = null;
let bestDist = Infinity;
placemarksById.forEach((coords) => {
const d =
Math.pow(coords[0] - focusLat, 2) +
Math.pow(coords[1] - focusLng, 2);
if (d < bestDist) {
bestDist = d;
best = coords;
}
});
if (best && bestDist < COORD_MATCH_TOLERANCE * COORD_MATCH_TOLERANCE) {
target = best;
}
}
if (target) {
map.setCenter(target, FOCUS_ZOOM);
}
};
const load = async (bounds, isInitial) => {
if (isInitial) setLoading(true);
const request = ++requestId;
try {
const markers = await loadMarkers(
bounds,
filtersRef.current.type,
filtersRef.current.category
);
if (destroyed || request !== requestId) return;
const placemarksById = renderMarkers(Array.isArray(markers) ? markers : []);
if (isInitial) focusOnPost(placemarksById);
} catch (e) {
// Фоновая догрузка не должна перекрывать рабочую карту ошибкой —
// показываем её только на первом запросе.
if (!destroyed && request === requestId && isInitial) setError(e.message);
} finally {
if (!destroyed && request === requestId) setLoading(false);
// Спиннер снимаем в любом случае: иначе при пустых границах карта
// навсегда останется закрыта оверлеем загрузки.
if (!destroyed && isInitial) {
firstLoadDone = true;
setLoading(false);
}
}
};
const requestMarkers = (bounds, isInitial) => {
if (destroyed) return;
if (!bounds || bounds.length < 2) return;
const key = boundsKey(bounds);
if (key === lastBoundsKey) return;
lastBoundsKey = key;
load(bounds, isInitial);
};
// Перемещение/зум: перезапрашиваем маркеры, но не на каждый пиксель.
const scheduleMarkers = () => {
if (destroyed) return;
clearTimeout(debounceTimer);
debounceTimer = setTimeout(() => {
requestMarkers(readBounds(), false);
}, BOUNDS_DEBOUNCE_MS);
};
// Безопасное чтение границ: до полного рендера карты getBounds()
// возвращает null/undefined или координаты-заглушки.
const readBounds = () => {
if (destroyed || !map) return null;
const bounds = map.getBounds();
if (!bounds || bounds.length < 2) return null;
const [[minLat, minLng], [maxLat, maxLng]] = bounds;
if (![minLat, minLng, maxLat, maxLng].every(Number.isFinite)) return null;
return bounds;
};
// Первая загрузка. У ymaps.Map в 2.1 нет события 'load', поэтому
// готовность границ отслеживаем через boundschange (он прилетает уже
// при первом расчёте вьюпорта) + короткий ретрай, если событие не пришло.
const loadInitial = (attempt = 0) => {
if (destroyed || firstLoadDone) return;
const bounds = readBounds();
if (bounds) {
requestMarkers(bounds, true);
return;
}
if (attempt >= MAX_BOUNDS_ATTEMPTS) {
firstLoadDone = true;
setLoading(false);
return;
}
boundsRetryTimer = setTimeout(() => loadInitial(attempt + 1), BOUNDS_RETRY_MS);
};
const init = () => {
if (!mapRef.current || destroyed) return;
try {
const hasFocusCoords = Number.isFinite(focusLat) && Number.isFinite(focusLng);
map = new window.ymaps.Map(mapRef.current, {
center: hasFocusCoords ? [focusLat, focusLng] : MAP_CENTER,
zoom: hasFocusCoords ? FOCUS_ZOOM : MAP_ZOOM,
controls: ["zoomControl", "geolocationControl"],
});
ymapRef.current = map;
const collection = new window.ymaps.GeoObjectCollection();
map.geoObjects.add(collection);
markersRef.current = collection;
subscriptions.push(map.events.add("boundschange", () => {
if (!firstLoadDone) {
clearTimeout(boundsRetryTimer);
loadInitial();
}
scheduleMarkers();
}));
// Подстраховка на случай, если boundschange не придёт.
loadInitial();
} catch (e) {
if (!destroyed) {
setError(e.message);
setLoading(false);
}
}
};
whenYmapsReady()
.then((ymaps) => {
if (destroyed) return;
ymaps.ready(init);
})
.catch((e) => {
// API карт не подгрузился (заблокирован/офлайн/медленный CDN).
// Без этой ветки пользователь смотрел бы в вечный спиннер без ошибки.
if (!destroyed) {
setError(tRef.current("post.mapLoadFailed"));
setLoading(false);
}
console.warn("Yandex Maps API failed to load:", e);
});
return () => {
destroyed = true;
clearTimeout(debounceTimer);
clearTimeout(boundsRetryTimer);
subscriptions.forEach((sub) => {
try {
map?.events.remove(sub);
} catch (e) {
// карта уже уничтожена — ничего не делаем
}
});
ymapRef.current?.destroy();
ymapRef.current = null;
markersRef.current = null;
renderMarkersRef.current = null;
userMarkerRef.current = null;
};
}, [focusPostId, focusLat, focusLng]);
// Смена фильтров type/category: догружаем маркеры для текущих границ,
// карту при этом не пересоздаём.
const prevFiltersRef = useRef({ type, category });
useEffect(() => {
const prev = prevFiltersRef.current;
prevFiltersRef.current = { type, category };
if (prev.type === type && prev.category === category) return;
const map = ymapRef.current;
if (!map) return;
const bounds = map.getBounds();
if (!bounds || bounds.length < 2) return;
const timer = setTimeout(async () => {
try {
const markers = await loadMarkers(bounds, type, category);
renderMarkersRef.current?.(Array.isArray(markers) ? markers : []);
} catch (e) {
// Фоновый запрос: молча оставляем прежние маркеры на месте.
}
}, BOUNDS_DEBOUNCE_MS);
return () => clearTimeout(timer);
}, [type, category]);
// Подсветка метки (наведение на карточку в списке десктопной карты):
// класс на DOM-узле лейаута + zIndex, чтобы метка была поверх соседних.
useEffect(() => {
if (highlightId == null) return undefined;
const id = String(highlightId);
const placemark = placemarksRef.current.get(id);
placemark?.options.set("zIndex", 1000);
const node = mapRef.current?.querySelector(`[data-pin-id="${CSS.escape(id)}"]`);
node?.classList.add("is-hl");
return () => {
placemark?.options.unset("zIndex");
node?.classList.remove("is-hl");
};
}, [highlightId]);
// Программный перелёт к точке (клик по карточке в списке десктопной карты).
useEffect(() => {
if (!focusTarget) return;
const map = ymapRef.current;
if (!map) return;
const { lat, lng, zoom } = focusTarget;
if (!Number.isFinite(lat) || !Number.isFinite(lng)) return;
map.setCenter([lat, lng], Math.max(map.getZoom(), zoom ?? FOCUS_ZOOM - 1), { duration: 300 });
}, [focusTarget]);
// Геолокация: если юзер разрешил и карта уже создана — центр на его месте.
// Не трогаем, если карта была открыта с фокусом на конкретном объявлении.
const hasFocus = focusPostId != null || (Number.isFinite(focusLat) && Number.isFinite(focusLng));
useEffect(() => {
if (hasFocus) return;
if (geoStatus !== GEO_STATUS.SUCCESS || !geoCoords) return;
const map = ymapRef.current;
if (!map) return;
const [lat, lng] = [geoCoords.latitude, geoCoords.longitude];
map.setCenter([lat, lng], 14);
if (userMarkerRef.current) {
userMarkerRef.current.geometry.setCoordinates([lat, lng]);
} else {
const pm = new window.ymaps.Placemark(
[lat, lng],
{},
{ preset: "islands#blueCircleIcon" }
);
map.geoObjects.add(pm);
userMarkerRef.current = pm;
}
}, [hasFocus, geoStatus, geoCoords, loading]);
return (
<div className="f-mapview">
{loading && (
<div className="f-mapview-status" data-testid="mapview-loading">
<div className="f-spinner" />
</div>
)}
{error && (
<div className="f-mapview-status f-mapview-error">
Ошибка загрузки карты
</div>
)}
<div ref={mapRef} className="f-mapview-canvas" />
{geoStatus === GEO_STATUS.LOADING && !hasFocus && (
<div className="f-mapview-geo f-mapview-geo-info">Определение местоположения…</div>
)}
{geoStatus === GEO_STATUS.DENIED && (
<div className="f-mapview-geo f-mapview-geo-warn">Доступ к геолокации запрещён</div>
)}
{geoStatus === GEO_STATUS.TIMEOUT && (
<div className="f-mapview-geo f-mapview-geo-warn">Геолокация не определилась</div>
)}
{geoStatus === GEO_STATUS.UNSUPPORTED && (
<div className="f-mapview-geo f-mapview-geo-warn">Геолокация недоступна</div>
)}
{onBack && (
<button type="button" className="f-mapview-back" onClick={onBack}>
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={2.2} strokeLinecap="round" strokeLinejoin="round" className="f-mapview-back-icon">
<path d="M19 12H5" />
<path d="m12 19-7-7 7-7" />
</svg>
{t('map.backToListings')}
</button>
)}
</div>
);
}