All files / src/components RoutePointsEditor.tsx

2.76% Statements 7/253
100% Branches 0/0
0% Functions 0/4
2.76% Lines 7/253

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 3181x 1x 1x         1x 1x     1x   1x                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import {
  AdvancedMarker,
  Map as GoogleMap,
  useMap,
} from '@vis.gl/react-google-maps';
import { useTheme } from '@/contexts/ThemeContext';
import { GOOGLE_MAPS_MAP_ID, isGoogleMapsConfigured } from '@/components/GoogleMapsProvider';
import type { LocationSuggestion } from '@/models/event';
import type { RouteWaypoint } from '@/viewmodels/event/useCreateEventViewModel';
import { fetchRoutedGeometry, reverseGeocode } from '@/services/eventService';
 
const ROUTED_GEOMETRY_DEBOUNCE_MS = 400;
 
interface RoutePointsEditorProps {
  routePoints: RouteWaypoint[];
  locationQuery: string;
  isSearching: boolean;
  suggestions: LocationSuggestion[];
  errorText?: string | null;
  disabled?: boolean;
  onSearch: (query: string) => void;
  onAddFromSuggestion: (suggestion: LocationSuggestion) => void;
  onAddFromCoordinate: (lat: number, lon: number, label?: string | null) => void;
  onRemove: (index: number) => void;
  onMove: (index: number, direction: -1 | 1) => void;
  onUpdateLabel: (index: number, label: string) => void;
}
 
interface LatLng {
  lat: number;
  lng: number;
}
 
function RoutePolyline({ path }: { path: LatLng[] }) {
  const map = useMap();
  const { theme } = useTheme();
  useEffect(() => {
    if (!map || path.length < 2) return;
    const polyline = new google.maps.Polyline({
      map,
      path,
      strokeColor: theme === 'dark' ? '#A78BFA' : '#7C3AED',
      strokeOpacity: 1,
      strokeWeight: 4,
      clickable: false,
    });
    return () => {
      polyline.setMap(null);
    };
  }, [map, path, theme]);
  return null;
}
 
function FitBounds({ points }: { points: LatLng[] }) {
  const map = useMap();
  const prevLengthRef = useRef(0);
  useEffect(() => {
    if (!map || points.length < 2) return;
    if (points.length !== prevLengthRef.current) {
      const bounds = new google.maps.LatLngBounds();
      for (const p of points) bounds.extend(p);
      map.fitBounds(bounds, { top: 40, bottom: 40, left: 40, right: 40 });
    }
    prevLengthRef.current = points.length;
  }, [map, points]);
  return null;
}
 
function MapClickHandler({
  onMapClick,
}: {
  onMapClick: (lat: number, lng: number) => void;
}) {
  const map = useMap();
  useEffect(() => {
    if (!map) return;
    const listener = map.addListener('click', (e: google.maps.MapMouseEvent) => {
      if (e.latLng) {
        onMapClick(e.latLng.lat(), e.latLng.lng());
      }
    });
    return () => listener.remove();
  }, [map, onMapClick]);
  return null;
}
 
export default function RoutePointsEditor({
  routePoints,
  locationQuery,
  isSearching,
  suggestions,
  errorText,
  disabled,
  onSearch,
  onAddFromSuggestion,
  onAddFromCoordinate,
  onRemove,
  onMove,
  onUpdateLabel,
}: RoutePointsEditorProps) {
  const { t } = useTranslation();
  const { theme } = useTheme();
  const isDark = theme === 'dark';
  const configured = isGoogleMapsConfigured();
  const [routedGeometry, setRoutedGeometry] = useState<LatLng[] | null>(null);
 
  useEffect(() => {
    if (routePoints.length < 2) {
      setRoutedGeometry(null);
      return;
    }
    let cancelled = false;
    const handle = setTimeout(() => {
      fetchRoutedGeometry(routePoints.map((p) => ({ lat: p.lat, lon: p.lon })))
        .then((geom) => {
          if (!cancelled && geom && geom.length >= 2) {
            setRoutedGeometry(geom.map((p) => ({ lat: p.lat, lng: p.lon })));
          }
        })
        .catch(() => {
          if (!cancelled) setRoutedGeometry(null);
        });
    }, ROUTED_GEOMETRY_DEBOUNCE_MS);
    return () => {
      cancelled = true;
      clearTimeout(handle);
    };
  }, [routePoints]);
 
  const handleMapClick = useCallback(
    async (lat: number, lng: number) => {
      if (disabled) return;
      const insertIndex = routePoints.length;
      onAddFromCoordinate(lat, lng);
      try {
        const result = await reverseGeocode(lat, lng);
        if (result?.display_name) {
          onUpdateLabel(insertIndex, result.display_name);
        }
      } catch {
        // best-effort reverse geocode
      }
    },
    [disabled, routePoints.length, onAddFromCoordinate, onUpdateLabel],
  );
 
  const waypointLatLngs = useMemo<LatLng[]>(
    () => routePoints.map((p) => ({ lat: p.lat, lng: p.lon })),
    [routePoints],
  );
 
  const polylineCoords = useMemo<LatLng[]>(() => {
    if (routedGeometry && routedGeometry.length >= 2) return routedGeometry;
    return waypointLatLngs;
  }, [routedGeometry, waypointLatLngs]);
 
  const defaultCenter = useMemo<LatLng>(() => {
    if (routePoints.length > 0) {
      return { lat: routePoints[0].lat, lng: routePoints[0].lon };
    }
    return { lat: 41.0082, lng: 28.9784 };
  }, [routePoints]);
 
  return (
    <div className="ce-route-editor">
      {/* Search */}
      <div className="ce-route-search-row">
        <input
          type="text"
          className={`field-input ${errorText ? 'has-error' : ''}`}
          placeholder={t('create_event.route_search_placeholder')}
          value={locationQuery}
          onChange={(e) => onSearch(e.target.value)}
          disabled={disabled}
        />
        {isSearching && <span className="spinner ce-route-search-spinner" />}
      </div>
 
      {suggestions.length > 0 && (
        <ul className="ce-route-suggestions">
          {suggestions.map((s, i) => (
            <li key={`${s.lat}-${s.lon}-${i}`}>
              <button
                type="button"
                className="ce-route-suggestion-item"
                onClick={() => onAddFromSuggestion(s)}
              >
                <span className="ce-route-suggestion-plus">+</span>
                <span className="ce-route-suggestion-text">{s.display_name}</span>
              </button>
            </li>
          ))}
        </ul>
      )}
 
      <p className="ce-route-hint">
        {t('create_event.route_click_hint')}
      </p>
 
      {/* Map */}
      {configured ? (
        <div className="ce-route-map-container">
          <GoogleMap
            key={isDark ? 'dark' : 'light'}
            mapId={GOOGLE_MAPS_MAP_ID}
            defaultCenter={defaultCenter}
            defaultZoom={12}
            colorScheme={isDark ? 'DARK' : 'LIGHT'}
            gestureHandling="greedy"
            disableDefaultUI={false}
            mapTypeControl={false}
            streetViewControl={false}
            fullscreenControl={false}
            clickableIcons={false}
            className="ce-route-map-surface"
          >
            <MapClickHandler onMapClick={handleMapClick} />
            {waypointLatLngs.length >= 2 && <FitBounds points={waypointLatLngs} />}
            {waypointLatLngs.length >= 2 && <RoutePolyline path={polylineCoords} />}
            {routePoints.map((p, i) => (
              <AdvancedMarker
                key={`${p.lat}-${p.lon}-${i}`}
                position={{ lat: p.lat, lng: p.lon }}
              >
                <div className="ce-route-marker">
                  <div
                    className={`ce-route-marker-dot ${i === 0 ? 'ce-route-marker-dot--start' : ''} ${i === routePoints.length - 1 && routePoints.length > 1 ? 'ce-route-marker-dot--end' : ''}`}
                  >
                    <span className="ce-route-marker-number">{i + 1}</span>
                  </div>
                </div>
              </AdvancedMarker>
            ))}
          </GoogleMap>
        </div>
      ) : (
        <div className="ce-route-map-placeholder">
          {t('create_event.route_map_placeholder')}
        </div>
      )}
 
      {/* Waypoints list */}
      <div className="ce-route-list-header">
        {routePoints.length > 0
          ? t('create_event.waypoints_count', { count: routePoints.length })
          : t('create_event.waypoints')}
      </div>
 
      {routePoints.length === 0 ? (
        <div className="ce-route-empty">
          {t('create_event.route_empty')}
        </div>
      ) : (
        <div className="ce-route-waypoints">
          {routePoints.map((p, i) => (
            <div
              key={`waypoint-${i}-${p.lat}-${p.lon}`}
              className="ce-route-waypoint"
            >
              <div
                className={`ce-route-waypoint-index ${i === 0 ? 'ce-route-waypoint-index--start' : ''} ${i === routePoints.length - 1 && routePoints.length > 1 ? 'ce-route-waypoint-index--end' : ''}`}
              >
                {i + 1}
              </div>
              <div className="ce-route-waypoint-info">
                <span className="ce-route-waypoint-label">
                  {p.label ?? `${p.lat.toFixed(5)}, ${p.lon.toFixed(5)}`}
                </span>
                {p.label && (
                  <span className="ce-route-waypoint-coords">
                    {p.lat.toFixed(5)}, {p.lon.toFixed(5)}
                  </span>
                )}
              </div>
              <div className="ce-route-waypoint-actions">
                <button
                  type="button"
                  className="ce-route-action-btn"
                  onClick={() => onMove(i, -1)}
                  disabled={i === 0 || disabled}
                  aria-label={t('create_event.move_up')}
                  title={t('create_event.move_up')}
                >
                  &#8593;
                </button>
                <button
                  type="button"
                  className="ce-route-action-btn"
                  onClick={() => onMove(i, 1)}
                  disabled={i === routePoints.length - 1 || disabled}
                  aria-label={t('create_event.move_down')}
                  title={t('create_event.move_down')}
                >
                  &#8595;
                </button>
                <button
                  type="button"
                  className="ce-route-action-btn ce-route-action-btn--danger"
                  onClick={() => onRemove(i)}
                  disabled={disabled}
                  aria-label={t('create_event.remove')}
                  title={t('create_event.remove')}
                >
                  &times;
                </button>
              </div>
            </div>
          ))}
        </div>
      )}
 
      {errorText && <p className="field-error">{errorText}</p>}
    </div>
  );
}