added hints on map
This commit is contained in:
@@ -14,3 +14,8 @@ REACT_APP_YANDEX_MAPS_KEY=
|
||||
|
||||
# Почта поддержки в модалке «Поддержка». Необязательно — есть значение по умолчанию.
|
||||
REACT_APP_SUPPORT_EMAIL=
|
||||
|
||||
# Необязательно: ключ «API Геосаджеста» Яндекса — подсказки адреса как на Яндекс Картах.
|
||||
# Без него подсказки берутся из Геокодера (REACT_APP_YANDEX_GEOCODER_KEY).
|
||||
# Получить: https://developer.tech.yandex.ru/
|
||||
REACT_APP_YANDEX_SUGGEST_KEY=
|
||||
|
||||
@@ -12,10 +12,12 @@ jobs:
|
||||
env:
|
||||
GEOCODER_KEY: ${{ secrets.REACT_APP_YANDEX_GEOCODER_KEY }}
|
||||
MAPS_KEY: ${{ secrets.REACT_APP_YANDEX_MAPS_KEY }}
|
||||
SUGGEST_KEY: ${{ secrets.REACT_APP_YANDEX_SUGGEST_KEY }}
|
||||
run: |
|
||||
docker build \
|
||||
--build-arg REACT_APP_YANDEX_GEOCODER_KEY="$GEOCODER_KEY" \
|
||||
--build-arg REACT_APP_YANDEX_MAPS_KEY="$MAPS_KEY" \
|
||||
--build-arg REACT_APP_YANDEX_SUGGEST_KEY="$SUGGEST_KEY" \
|
||||
-t nakhodka-frontend:latest \
|
||||
-t nakhodka-frontend:${{ github.sha }} .
|
||||
- name: Restart frontend
|
||||
|
||||
@@ -6,9 +6,11 @@ COPY . .
|
||||
ARG REACT_APP_API_URL=https://app.nahodka-test.online
|
||||
ARG REACT_APP_YANDEX_GEOCODER_KEY=
|
||||
ARG REACT_APP_YANDEX_MAPS_KEY=
|
||||
ARG REACT_APP_YANDEX_SUGGEST_KEY=
|
||||
ENV REACT_APP_API_URL=$REACT_APP_API_URL
|
||||
ENV REACT_APP_YANDEX_GEOCODER_KEY=$REACT_APP_YANDEX_GEOCODER_KEY
|
||||
ENV REACT_APP_YANDEX_MAPS_KEY=$REACT_APP_YANDEX_MAPS_KEY
|
||||
ENV REACT_APP_YANDEX_SUGGEST_KEY=$REACT_APP_YANDEX_SUGGEST_KEY
|
||||
RUN npm run build
|
||||
|
||||
FROM nginx:alpine
|
||||
|
||||
@@ -1,11 +1,22 @@
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { whenYmapsReady } from "../utils/ymapsApi";
|
||||
|
||||
const YANDEX_GEOCODER_API_KEY = process.env.REACT_APP_YANDEX_GEOCODER_KEY;
|
||||
import { reverseGeocode } from "../utils/yandexGeo";
|
||||
|
||||
const DEFAULT_CENTER = [55.751574, 37.573856];
|
||||
const DEFAULT_ZOOM = 14;
|
||||
// Зум, к которому «подлетает» карта после выбора адреса — уровень дома
|
||||
export const ADDRESS_ZOOM = 16;
|
||||
|
||||
/**
|
||||
* Яндекс.Карта с одной перетаскиваемой меткой, связанная с полем адреса.
|
||||
*
|
||||
* - клик по карте / перетаскивание метки → метка встаёт туда, адрес
|
||||
* определяется обратным геокодированием;
|
||||
* - moveTo(lat, lng, { address }) → метка и карта переезжают в точку;
|
||||
* если адрес уже известен (выбрана подсказка), геокодер не дёргаем;
|
||||
* - setAddressText — ручной ввод в поле: адрес меняется, метка остаётся.
|
||||
*/
|
||||
export function useYandexMap(enabled, initialCoords = null, initialAddress = "") {
|
||||
const { t } = useTranslation();
|
||||
// tRef читается из эффекта инициализации карты. Добавлять t в его deps нельзя:
|
||||
@@ -25,79 +36,96 @@ export function useYandexMap(enabled, initialCoords = null, initialAddress = "")
|
||||
const [loading, setLoading] = useState(false);
|
||||
// Ошибка загрузки API карт: без неё пользователь смотрел бы в вечный спиннер.
|
||||
const [loadError, setLoadError] = useState("");
|
||||
// Адрес по точке не определился — координаты вместо адреса не показываем.
|
||||
const [addressError, setAddressError] = useState(false);
|
||||
// Всегда хранит последние координаты, чтобы при повторной инициализации
|
||||
// карты (например, при повторном открытии модалки) маркер появлялся там,
|
||||
// где пользователь его оставил, а не сбрасывался на initialCoords.
|
||||
// карты маркер появлялся там, где пользователь его оставил.
|
||||
const coordsRef = useRef(initialCoords);
|
||||
useEffect(() => { coordsRef.current = coords; }, [coords]);
|
||||
|
||||
const applyAddress = useCallback((value) => {
|
||||
setAddress(value);
|
||||
addressRef.current = value;
|
||||
}, []);
|
||||
|
||||
const resolveAddress = useCallback((lat, lng) => {
|
||||
const requestId = ++requestIdRef.current;
|
||||
setLoading(true);
|
||||
setAddressError(false);
|
||||
|
||||
fetch(
|
||||
`https://geocode-maps.yandex.ru/1.x/?apikey=${YANDEX_GEOCODER_API_KEY}&geocode=${lng},${lat}&format=json&lang=ru_RU`
|
||||
)
|
||||
.then(r => r.json())
|
||||
.then(data => {
|
||||
if (requestId !== requestIdRef.current) return;
|
||||
reverseGeocode(lat, lng)
|
||||
.catch(() => null)
|
||||
.then(found => {
|
||||
if (requestId !== requestIdRef.current) return;
|
||||
applyAddress(found || "");
|
||||
setAddressError(!found);
|
||||
setLoading(false);
|
||||
});
|
||||
}, [applyAddress]);
|
||||
|
||||
const found =
|
||||
data?.response?.GeoObjectCollection?.featureMember?.[0]
|
||||
?.GeoObject?.metaDataProperty?.GeocoderMetaData?.text;
|
||||
const resolved = found || `${lat.toFixed(5)}, ${lng.toFixed(5)}`;
|
||||
setAddress(resolved);
|
||||
addressRef.current = resolved;
|
||||
setLoading(false);
|
||||
})
|
||||
.catch(() => {
|
||||
if (requestId !== requestIdRef.current) return;
|
||||
|
||||
const fallback = `${lat.toFixed(5)}, ${lng.toFixed(5)}`;
|
||||
setAddress(fallback);
|
||||
addressRef.current = fallback;
|
||||
setLoading(false);
|
||||
});
|
||||
}, []);
|
||||
|
||||
const attachPlacemarkDrag = useCallback((map, pm) => {
|
||||
const placePin = useCallback((lat, lng) => {
|
||||
const map = ymapRef.current;
|
||||
if (placemarkRef.current) {
|
||||
placemarkRef.current.geometry.setCoordinates([lat, lng]);
|
||||
return;
|
||||
}
|
||||
const pm = new window.ymaps.Placemark([lat, lng], {}, { draggable: true, preset: "islands#redDotIcon" });
|
||||
pm.events.add("dragend", () => {
|
||||
const [lat, lng] = pm.geometry.getCoordinates();
|
||||
setCoords({ latitude: lat, longitude: lng });
|
||||
resolveAddress(lat, lng);
|
||||
const [pLat, pLng] = pm.geometry.getCoordinates();
|
||||
setCoords({ latitude: pLat, longitude: pLng });
|
||||
resolveAddress(pLat, pLng);
|
||||
});
|
||||
map.geoObjects.add(pm);
|
||||
placemarkRef.current = pm;
|
||||
}, [resolveAddress]);
|
||||
|
||||
/**
|
||||
* Устанавливает маркер и центр карты на указанные координаты.
|
||||
* Если карта ещё не инициализирована — откладывает фокус до её создания.
|
||||
* Ставит метку в точку и плавно центрирует на ней карту.
|
||||
* @param {{ address?: string, zoom?: number }} [opts] — address: адрес уже
|
||||
* известен, обратное геокодирование не нужно; zoom: целевой зум.
|
||||
*/
|
||||
const moveTo = useCallback((lat, lng) => {
|
||||
const moveTo = useCallback((lat, lng, opts = {}) => {
|
||||
const map = ymapRef.current;
|
||||
setCoords({ latitude: lat, longitude: lng });
|
||||
coordsRef.current = { latitude: lat, longitude: lng };
|
||||
|
||||
if (opts.address) {
|
||||
// Отменяем ответ возможного «старого» обратного геокодирования
|
||||
requestIdRef.current++;
|
||||
setLoading(false);
|
||||
setAddressError(false);
|
||||
applyAddress(opts.address);
|
||||
} else {
|
||||
resolveAddress(lat, lng);
|
||||
}
|
||||
|
||||
if (!map) {
|
||||
pendingFocusRef.current = { lat, lng };
|
||||
pendingFocusRef.current = { lat, lng, zoom: opts.zoom };
|
||||
return;
|
||||
}
|
||||
|
||||
pendingFocusRef.current = null;
|
||||
setCoords({ latitude: lat, longitude: lng });
|
||||
placePin(lat, lng);
|
||||
map.setCenter([lat, lng], opts.zoom ?? Math.max(map.getZoom(), DEFAULT_ZOOM), { duration: 300 });
|
||||
}, [applyAddress, placePin, resolveAddress]);
|
||||
|
||||
if (placemarkRef.current) {
|
||||
placemarkRef.current.geometry.setCoordinates([lat, lng]);
|
||||
} else {
|
||||
const pm = new window.ymaps.Placemark([lat, lng], {}, { draggable: true });
|
||||
map.geoObjects.add(pm);
|
||||
placemarkRef.current = pm;
|
||||
attachPlacemarkDrag(map, pm);
|
||||
}
|
||||
/** Ручной ввод адреса: текст меняется, метка остаётся на месте. */
|
||||
const setAddressText = useCallback((value) => {
|
||||
requestIdRef.current++;
|
||||
setLoading(false);
|
||||
setAddressError(false);
|
||||
applyAddress(value);
|
||||
}, [applyAddress]);
|
||||
|
||||
map.setCenter([lat, lng], 14);
|
||||
resolveAddress(lat, lng);
|
||||
}, [attachPlacemarkDrag, resolveAddress]);
|
||||
/** Текущий центр карты [lat, lng] — им подсказки «привязываются» к району. */
|
||||
const getCenter = useCallback(() => {
|
||||
const map = ymapRef.current;
|
||||
if (map) return map.getCenter();
|
||||
const c = coordsRef.current;
|
||||
return c ? [c.latitude, c.longitude] : null;
|
||||
}, []);
|
||||
|
||||
const init = useCallback(() => {
|
||||
if (ymapRef.current) return;
|
||||
if (ymapRef.current || !mapRef.current) return;
|
||||
|
||||
const startCoords = coordsRef.current;
|
||||
const center = startCoords
|
||||
@@ -106,32 +134,30 @@ export function useYandexMap(enabled, initialCoords = null, initialAddress = "")
|
||||
|
||||
const map = new window.ymaps.Map(mapRef.current, {
|
||||
center,
|
||||
zoom: 14,
|
||||
zoom: startCoords ? ADDRESS_ZOOM : DEFAULT_ZOOM,
|
||||
controls: ["zoomControl", "geolocationControl"],
|
||||
});
|
||||
ymapRef.current = map;
|
||||
|
||||
if (startCoords) {
|
||||
const pm = new window.ymaps.Placemark(center, {}, { draggable: true });
|
||||
map.geoObjects.add(pm);
|
||||
placemarkRef.current = pm;
|
||||
attachPlacemarkDrag(map, pm);
|
||||
resolveAddress(startCoords.latitude, startCoords.longitude);
|
||||
}
|
||||
if (startCoords) placePin(center[0], center[1]);
|
||||
|
||||
// Как на Яндекс Картах: клик ставит метку, карта при этом не прыгает
|
||||
map.events.add("click", e => {
|
||||
const [lat, lng] = e.get("coords");
|
||||
moveTo(lat, lng);
|
||||
setCoords({ latitude: lat, longitude: lng });
|
||||
coordsRef.current = { latitude: lat, longitude: lng };
|
||||
placePin(lat, lng);
|
||||
resolveAddress(lat, lng);
|
||||
});
|
||||
|
||||
// Если геолокация успела вернуть координаты раньше, чем создалась карта,
|
||||
// применяем отложенный фокус сразу после инициализации.
|
||||
// Точка могла прийти (геолокация, выбор подсказки) раньше, чем создалась карта
|
||||
if (pendingFocusRef.current) {
|
||||
const pending = pendingFocusRef.current;
|
||||
const { lat, lng, zoom } = pendingFocusRef.current;
|
||||
pendingFocusRef.current = null;
|
||||
moveTo(pending.lat, pending.lng);
|
||||
placePin(lat, lng);
|
||||
map.setCenter([lat, lng], zoom ?? ADDRESS_ZOOM);
|
||||
}
|
||||
}, [attachPlacemarkDrag, resolveAddress, moveTo]);
|
||||
}, [placePin, resolveAddress]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!enabled || !mapRef.current) return;
|
||||
@@ -152,7 +178,7 @@ export function useYandexMap(enabled, initialCoords = null, initialAddress = "")
|
||||
.catch((e) => {
|
||||
if (cancelled) return;
|
||||
// API карт так и не подгрузился: сбрасываем флаг, чтобы следующая
|
||||
// попытка открытия карты её повторила, и гасим бесконечный спиннер.
|
||||
// попытка её повторила, и гасим бесконечный спиннер.
|
||||
initializedRef.current = false;
|
||||
setLoadError(tRef.current("post.mapLoadFailed"));
|
||||
console.warn("Yandex Maps API failed to load:", e);
|
||||
@@ -166,11 +192,14 @@ export function useYandexMap(enabled, initialCoords = null, initialAddress = "")
|
||||
initializedRef.current = false;
|
||||
pendingFocusRef.current = null;
|
||||
};
|
||||
// enabled намеренно в deps — карта инициализируется/разрушается при открытии
|
||||
// и закрытии модалки. Начальные координаты читаются из coordsRef, чтобы
|
||||
// при повторном открытии маркер вставал на последний выбранный адрес.
|
||||
// enabled намеренно в deps — карта создаётся, когда её контейнер появляется
|
||||
// на экране, и разрушается, когда исчезает. Начальные координаты читаются
|
||||
// из coordsRef, чтобы маркер вставал на последний выбранный адрес.
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [enabled, init]);
|
||||
|
||||
return { mapRef, coords, address, addressRef, loading, loadError, moveTo };
|
||||
return {
|
||||
mapRef, coords, address, addressRef, loading, loadError, addressError,
|
||||
moveTo, setAddressText, getCenter,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -101,17 +101,22 @@
|
||||
"photoHint": "JPEG / PNG / WebP · up to {{maxSize}} MB · multiple allowed",
|
||||
"categoryLabel": "Category",
|
||||
"mapLabel": "Location on map",
|
||||
"mapHint": "Click on the map to mark the location",
|
||||
"mapHint": "Start typing an address or pick a place on the map",
|
||||
"mapPickLabel": "Choose on map",
|
||||
"mapEmpty": "Location not selected yet",
|
||||
"selectedAddress": "Selected address",
|
||||
"saveLocation": "Save location",
|
||||
"openMap": "Open map",
|
||||
"pickLocation": "Select",
|
||||
"addressNotDetected": "Could not detect the address. Pick another point.",
|
||||
"geoLoading": "Determining location…",
|
||||
"geoSuccess": "Your location has been determined",
|
||||
"geoDenied": "Location access denied",
|
||||
"geoUnsupported": "Geolocation is not available in this browser",
|
||||
"geoTimeout": "Unable to determine your location",
|
||||
"mapLoadFailed": "Could not load the map. Check your connection or ad blocker and try again.",
|
||||
"addressNotFound": "Address not found — refine the query or mark the place on the map",
|
||||
"addressSearchFailed": "Couldn't load address suggestions",
|
||||
"addressLabel": "Address",
|
||||
"addressPlaceholder": "E.g. 123 Main St, New York",
|
||||
"phoneLabel": "Phone number",
|
||||
|
||||
@@ -101,17 +101,22 @@
|
||||
"photoHint": "JPEG / PNG / WebP · до {{maxSize}} МБ · можно несколько",
|
||||
"categoryLabel": "Категория",
|
||||
"mapLabel": "Место на карте",
|
||||
"mapHint": "Нажмите на карту, чтобы отметить место",
|
||||
"mapHint": "Начните вводить адрес или выберите место на карте",
|
||||
"mapPickLabel": "Указать местоположение на карте",
|
||||
"mapEmpty": "Место ещё не выбрано",
|
||||
"selectedAddress": "Выбранный адрес",
|
||||
"saveLocation": "Сохранить местоположение",
|
||||
"openMap": "Указать метополложение на карте",
|
||||
"pickLocation": "Выбрать",
|
||||
"addressNotDetected": "Не удалось определить адрес. Выберите другую точку.",
|
||||
"geoLoading": "Определение местоположения…",
|
||||
"geoSuccess": "Ваше местоположение определено",
|
||||
"geoDenied": "Доступ к геолокации запрещён",
|
||||
"geoUnsupported": "Геолокация недоступна в этом браузере",
|
||||
"geoTimeout": "Не удалось определить местоположение",
|
||||
"mapLoadFailed": "Не удалось загрузить карту. Проверьте интернет или блокировщик рекламы и попробуйте снова.",
|
||||
"addressNotFound": "Адрес не найден — уточните запрос или отметьте место на карте",
|
||||
"addressSearchFailed": "Не удалось получить подсказки адреса",
|
||||
"addressLabel": "Адрес",
|
||||
"addressPlaceholder": "Например: Москва, ул. Ленина, 5",
|
||||
"phoneLabel": "Номер телефона",
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import { useCallback, useState } from "react";
|
||||
import CloseIcon from "../components/icons/CloseIcon";
|
||||
import RulesModal from "./RulesModal";
|
||||
import { EMPTY_FORM, CATEGORIES } from "../config/feedConstants";
|
||||
@@ -7,10 +7,9 @@ import { usePostMutation } from "../hooks/usePostMutation";
|
||||
import { useImageUpload, ACCEPT, MAX_SIZE_MB } from "../hooks/useImageUpload";
|
||||
import { validatePostForm } from "../utils/validatePostForm";
|
||||
import { formatPhone } from "../utils/formatPhone";
|
||||
import { useYandexMap } from "../hooks/useYandexMap";
|
||||
import { useGeolocation, GEO_STATUS } from "../hooks/useGeolocation";
|
||||
import MapModal from "./MapModal";
|
||||
import ClearableField from "../components/ClearableField";
|
||||
import AddressAutocomplete from "../components/AddressAutocomplete";
|
||||
|
||||
/**
|
||||
* CreateUpdatePost — модальная форма создания и редактирования объявления.
|
||||
@@ -34,7 +33,7 @@ export default function CreateUpdatePost({ onClose, onSuccess, initialData, admi
|
||||
category: initialData.category || "",
|
||||
date: initialData.date || "",
|
||||
phone: initialData.phone || "",
|
||||
address: initialData.city || "",
|
||||
address: initialData.address || initialData.city || "",
|
||||
rulesAccepted: true,
|
||||
reward: initialData.reward ?? false,
|
||||
rewardText: initialData.rewardText
|
||||
@@ -67,37 +66,9 @@ export default function CreateUpdatePost({ onClose, onSuccess, initialData, admi
|
||||
? { latitude: initialData.latitude, longitude: initialData.longitude }
|
||||
: null;
|
||||
|
||||
const { mapRef, coords, address, addressRef, loading: mapLoading, loadError: mapLoadError, moveTo } = useYandexMap(
|
||||
mapModalOpen,
|
||||
initialCoords,
|
||||
isEdit ? (initialData.location || "") : ""
|
||||
);
|
||||
|
||||
const { coords: geoCoords, status: geoStatus, requestLocation: requestGeoLocation } =
|
||||
useGeolocation();
|
||||
// При открытии окна карты запрашиваем геолокацию; если пользователь дал
|
||||
// разрешение — автоматически центрируем карту и ставим маркер на его место.
|
||||
// При отказе/недоступности API ничего не делаем — остаётся дефолтный центр.
|
||||
useEffect(() => {
|
||||
if (mapModalOpen) {
|
||||
requestGeoLocation();
|
||||
}
|
||||
}, [mapModalOpen, requestGeoLocation]);
|
||||
|
||||
useEffect(() => {
|
||||
if (mapModalOpen && geoStatus === GEO_STATUS.SUCCESS && geoCoords) {
|
||||
moveTo(geoCoords.latitude, geoCoords.longitude);
|
||||
}
|
||||
}, [mapModalOpen, geoStatus, geoCoords, moveTo]);
|
||||
|
||||
useEffect(() => {
|
||||
if (address) {
|
||||
setForm(prev => ({ ...prev, address }));
|
||||
// Адрес пришёл — очищаем и ошибку поля, и "карта грузится",
|
||||
// иначе последняя может остаться висеть на экране навсегда.
|
||||
setErrors(prev => ({ ...prev, address: "", map: "" }));
|
||||
}
|
||||
}, [address]);
|
||||
// Точка на карте. Адрес лежит в form.address; точку задаёт выбор подсказки
|
||||
// в поле «Адрес» или выбор места в окне карты.
|
||||
const [coords, setCoords] = useState(initialCoords);
|
||||
|
||||
const loading = saving || compressing;
|
||||
|
||||
@@ -115,11 +86,6 @@ export default function CreateUpdatePost({ onClose, onSuccess, initialData, admi
|
||||
return;
|
||||
}
|
||||
|
||||
if (coords && !addressRef.current) {
|
||||
setErrors(prev => ({ ...prev, map: t('post.mapLoading') }));
|
||||
return;
|
||||
}
|
||||
|
||||
const data = new FormData();
|
||||
data.append("type", form.type.toUpperCase());
|
||||
data.append("title", form.title.trim());
|
||||
@@ -308,35 +274,37 @@ export default function CreateUpdatePost({ onClose, onSuccess, initialData, admi
|
||||
{errors.category && <p className="f-err-msg">{errors.category}</p>}
|
||||
</div>
|
||||
|
||||
{/* Место на карте */}
|
||||
{/* Адрес + карта: связаны в обе стороны, как на Яндекс Картах */}
|
||||
<div className="f-m-group">
|
||||
<label className="f-m-label">{t('post.mapLabel')}</label>
|
||||
<label className="f-m-label">{t('post.addressLabel')}</label>
|
||||
<AddressAutocomplete
|
||||
value={form.address}
|
||||
onChange={text => {
|
||||
// Адрес правят вручную — старая точка ему уже не соответствует
|
||||
set("address", text);
|
||||
setCoords(null);
|
||||
}}
|
||||
onSelect={({ address: picked, coords: [lat, lng] }) => {
|
||||
set("address", picked);
|
||||
setCoords({ latitude: lat, longitude: lng });
|
||||
}}
|
||||
getCenter={() => (coords ? [coords.latitude, coords.longitude] : null)}
|
||||
placeholder={t('post.addressPlaceholder')}
|
||||
invalid={!!errors.address}
|
||||
/>
|
||||
{errors.address && <p className="f-err-msg">{errors.address}</p>}
|
||||
|
||||
<button
|
||||
className="f-map-pick"
|
||||
className="f-map-pick f-map-open"
|
||||
type="button"
|
||||
onClick={() => setMapModalOpen(true)}
|
||||
>
|
||||
{form.address ? `📍 ${form.address}` : t('post.mapPickLabel')}
|
||||
📍 {t('post.openMap')}
|
||||
</button>
|
||||
{!coords && <p className="f-hint">{t('post.mapHint')}</p>}
|
||||
{mapLoadError && <p className="f-err-msg">{mapLoadError}</p>}
|
||||
{errors.map && <p className="f-err-msg">{errors.map}</p>}
|
||||
</div>
|
||||
|
||||
<div className="f-m-group">
|
||||
<label className="f-m-label">{t('post.addressLabel')}</label>
|
||||
<ClearableField onClear={() => set("address", "")} visible={!!form.address}>
|
||||
<input
|
||||
className={`f-m-field${errors.address ? " err" : ""}`}
|
||||
type="text"
|
||||
placeholder={t('post.addressPlaceholder')}
|
||||
value={form.address}
|
||||
onChange={e => set("address", e.target.value)}
|
||||
/>
|
||||
</ClearableField>
|
||||
{errors.address && <p className="f-err-msg">{errors.address}</p>}
|
||||
</div>
|
||||
|
||||
{/* Телефон */}
|
||||
<div className="f-m-group">
|
||||
<label className="f-m-label">{t('post.phoneLabel')}</label>
|
||||
@@ -440,12 +408,15 @@ export default function CreateUpdatePost({ onClose, onSuccess, initialData, admi
|
||||
|
||||
{mapModalOpen && (
|
||||
<MapModal
|
||||
mapRef={mapRef}
|
||||
address={address}
|
||||
mapLoading={mapLoading}
|
||||
geoStatus={geoStatus}
|
||||
initialCoords={coords}
|
||||
initialAddress={form.address}
|
||||
onClose={() => setMapModalOpen(false)}
|
||||
onSave={() => setMapModalOpen(false)}
|
||||
onPick={({ address: picked, coords: point }) => {
|
||||
set("address", picked);
|
||||
setCoords(point);
|
||||
setErrors(prev => ({ ...prev, map: "" }));
|
||||
setMapModalOpen(false);
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
|
||||
|
||||
@@ -1,20 +1,40 @@
|
||||
import { useEffect } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import CloseIcon from "../components/icons/CloseIcon";
|
||||
import { GEO_STATUS } from "../hooks/useGeolocation";
|
||||
import { useYandexMap, ADDRESS_ZOOM } from "../hooks/useYandexMap";
|
||||
import { useGeolocation, GEO_STATUS } from "../hooks/useGeolocation";
|
||||
|
||||
/**
|
||||
* MapModal — модальное окно с картой для выбора местоположения.
|
||||
* MapModal — модальное окно с картой для выбора места.
|
||||
*
|
||||
* @param {object} mapRef — ref, в который монтируется Яндекс.Карта
|
||||
* @param {string} address — текущий (выбранный) адрес
|
||||
* @param {boolean} mapLoading — идёт ли подгрузка адреса по координатам
|
||||
* @param {string} geoStatus — статус геолокации (GEO_STATUS.*)
|
||||
* @param {function} onClose — закрыть окно без сохранения
|
||||
* @param {function} onSave — сохранить выбранное местоположение
|
||||
* Клик по карте / перетаскивание метки определяет адрес; в форму он попадает
|
||||
* только по кнопке «Выбрать». Закрытие окна ничего не меняет.
|
||||
*
|
||||
* @param {{ latitude: number, longitude: number } | null} initialCoords — текущая точка формы
|
||||
* @param {string} initialAddress — текущий адрес формы
|
||||
* @param {function} onClose — закрыть окно без выбора
|
||||
* @param {function} onPick — выбрано место: ({ address, coords: { latitude, longitude } }) => void
|
||||
*/
|
||||
export default function MapModal({ mapRef, address, mapLoading, geoStatus, onClose, onSave }) {
|
||||
export default function MapModal({ initialCoords, initialAddress, onClose, onPick }) {
|
||||
const { t } = useTranslation();
|
||||
const { mapRef, coords, address, loading, loadError, addressError, moveTo } =
|
||||
useYandexMap(true, initialCoords, initialCoords ? initialAddress : "");
|
||||
|
||||
const { coords: geoCoords, status: geoStatus, requestLocation } = useGeolocation();
|
||||
|
||||
// Точки ещё нет — пробуем поставить метку на место пользователя.
|
||||
// При отказе/недоступности остаётся центр по умолчанию.
|
||||
useEffect(() => {
|
||||
if (!initialCoords) requestLocation();
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [requestLocation]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!initialCoords && geoStatus === GEO_STATUS.SUCCESS && geoCoords) {
|
||||
moveTo(geoCoords.latitude, geoCoords.longitude, { zoom: ADDRESS_ZOOM });
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [geoStatus, geoCoords, moveTo]);
|
||||
|
||||
useEffect(() => {
|
||||
const prev = document.body.style.overflow;
|
||||
@@ -23,17 +43,17 @@ export default function MapModal({ mapRef, address, mapLoading, geoStatus, onClo
|
||||
}, []);
|
||||
|
||||
const geoHint =
|
||||
geoStatus === GEO_STATUS.SUCCESS ? t('post.geoSuccess')
|
||||
: geoStatus === GEO_STATUS.LOADING ? t('post.geoLoading')
|
||||
: geoStatus === GEO_STATUS.DENIED ? t('post.geoDenied')
|
||||
: geoStatus === GEO_STATUS.UNSUPPORTED ? t('post.geoUnsupported')
|
||||
: geoStatus === GEO_STATUS.TIMEOUT ? t('post.geoTimeout')
|
||||
: null;
|
||||
geoStatus === GEO_STATUS.LOADING ? t('post.geoLoading')
|
||||
: geoStatus === GEO_STATUS.DENIED ? t('post.geoDenied')
|
||||
: geoStatus === GEO_STATUS.UNSUPPORTED ? t('post.geoUnsupported')
|
||||
: geoStatus === GEO_STATUS.TIMEOUT ? t('post.geoTimeout')
|
||||
: null;
|
||||
|
||||
const canPick = !!coords && !!address && !loading;
|
||||
|
||||
return (
|
||||
<div className="f-modal-bg" onClick={e => e.target === e.currentTarget && onClose()}>
|
||||
<div className="f-modal f-map-modal">
|
||||
{/* Header */}
|
||||
<div className="f-modal-head">
|
||||
<span className="f-modal-title">{t('post.mapLabel')}</span>
|
||||
<button className="f-close-btn" type="button" onClick={onClose}>
|
||||
@@ -41,28 +61,31 @@ export default function MapModal({ mapRef, address, mapLoading, geoStatus, onClo
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Map */}
|
||||
<div className="f-map-frame f-map-modal-frame">
|
||||
<div className={`f-map-frame f-map-modal-frame${loading ? " loading" : ""}`}>
|
||||
<div ref={mapRef} className="f-map-inner" />
|
||||
</div>
|
||||
|
||||
{geoHint && (
|
||||
<div className="f-map-geo">{geoHint}</div>
|
||||
)}
|
||||
{!coords && geoHint && <div className="f-map-geo">{geoHint}</div>}
|
||||
{loadError && <p className="f-err-msg">{loadError}</p>}
|
||||
|
||||
{/* Selected address */}
|
||||
<div className="f-map-selected">
|
||||
<span className="f-map-selected-label">{t('post.selectedAddress')}</span>
|
||||
<span className="f-map-selected-value">
|
||||
{mapLoading ? t('post.mapLoading') : (address || t('post.mapEmpty'))}
|
||||
{loading ? t('post.mapLoading')
|
||||
: addressError ? t('post.addressNotDetected')
|
||||
: (coords && address) || t('post.mapEmpty')}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<button className="f-m-submit" type="button" onClick={onSave} disabled={mapLoading}>
|
||||
<div className="f-m-submit-row">{t('post.saveLocation')}</div>
|
||||
<button
|
||||
className="f-m-submit"
|
||||
type="button"
|
||||
disabled={!canPick}
|
||||
onClick={() => onPick({ address, coords })}
|
||||
>
|
||||
<div className="f-m-submit-row">{t('post.pickLocation')}</div>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -650,3 +650,32 @@ select.f-m-field::selection { background: transparent; }
|
||||
margin: auto;
|
||||
}
|
||||
}
|
||||
/* ── Address autocomplete + inline map (CreateUpdatePost) ── */
|
||||
.f-addr { position: relative; z-index: 30; }
|
||||
.f-addr-list {
|
||||
position: absolute; z-index: 20;
|
||||
top: calc(100% + 4px); left: 0; right: 0;
|
||||
margin: 0; padding: 4px; list-style: none;
|
||||
max-height: 264px; overflow-y: auto;
|
||||
background: var(--bg-surface-solid);
|
||||
border: 1px solid var(--border); border-radius: 12px;
|
||||
box-shadow: 0 8px 24px rgba(0, 0, 0, .14);
|
||||
}
|
||||
.f-addr-item {
|
||||
display: flex; flex-direction: column; gap: 2px;
|
||||
padding: 9px 12px; border-radius: 8px; cursor: pointer;
|
||||
font-family: var(--font);
|
||||
}
|
||||
.f-addr-item.active { background: var(--hover-bg); }
|
||||
.f-addr-title { font-size: .9rem; color: var(--text-primary); }
|
||||
.f-addr-sub { font-size: .75rem; color: var(--muted); }
|
||||
/* Индикатор поиска — слева от крестика очистки */
|
||||
.f-addr-spinner {
|
||||
position: absolute; right: 42px; top: 21px; margin-top: -8px;
|
||||
width: 16px; height: 16px; border-radius: 50%;
|
||||
border: 2px solid rgba(var(--teal-rgb), .25); border-top-color: var(--teal);
|
||||
animation: f-addr-spin .7s linear infinite; pointer-events: none;
|
||||
}
|
||||
@keyframes f-addr-spin { to { transform: rotate(360deg); } }
|
||||
.f-map-open { margin-top: 10px; }
|
||||
.f-map-modal-frame.loading { opacity: .85; }
|
||||
|
||||
Reference in New Issue
Block a user