Skip to content

armgit / TREK

Public Imported from GitHub
0

The most complete open-source travel planner: real-time collaboration, bookings, budgets, packing lists, journals, offline PWA, SSO and an AI-ready MCP server, with planet-wide place search and routing built in.

2.1 KB
Raw Blame
import L from 'leaflet';
import { useCallback, useEffect } from 'react';
import { useMap } from 'react-leaflet';
import { frameLng } from '../../utils/lngFrame';
import { MAX_ZOOM_RASTER, type ViewportPadding } from '../../utils/mapViewport';
import { ASSISTANT_CAMERA_MS, centreOf, coverPadding, useCameraRequest, useUserMoveClock } from './assistantCamera';
import { useLngFrame } from './lngFrameContext';
import type { AssistantCamera } from './mapViewContract';

interface AssistantCameraControllerProps {
  camera: AssistantCamera | null | undefined;
  /** The planner's padding for its panels, in pixels per edge. */
  padding: ViewportPadding;
}

/**
 * Moves the Leaflet map where the assistant asks: `fit` frames the points,
 * `pan` brings their centre into view only when it is outside. Zoomed in no
 * further than a day fit, the same scale the GL map stops at.
 */
export function AssistantCameraController({ camera, padding }: AssistantCameraControllerProps) {
  const map = useMap();
  // The points are framed the way the map draws them (#2975).
  const frame = useLngFrame();
  const getContainer = useCallback(() => map.getContainer(), [map]);
  const userMovedAt = useUserMoveClock(getContainer, true);
  const request = useCameraRequest(camera, userMovedAt);

  useEffect(() => {
    request((camera) => {
      const next = frame
        ? { ...camera, points: camera.points.map(([lat, lng]) => [lat, frameLng(frame, lng)] as [number, number]) }
        : camera;
      const duration = ASSISTANT_CAMERA_MS / 1000;
      if (next.mode === 'pan') {
        const centre = centreOf(next.points);
        if (!map.getBounds().contains(centre)) map.panTo(centre, { animate: next.animate, duration });
        return;
      }
      const box = coverPadding(padding, next.cover);
      map.fitBounds(L.latLngBounds(next.points), {
        paddingTopLeft: [box.left, box.top],
        paddingBottomRight: [box.right, box.bottom],
        maxZoom: MAX_ZOOM_RASTER,
        animate: next.animate,
        duration,
      });
    });
  }, [map, padding, request, frame]);

  return null;
}