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.4 KB
Raw Blame
import L from 'leaflet';
import { useEffect, useLayoutEffect, useRef } from 'react';
import { useMap } from 'react-leaflet';
import { frameLng } from '../../utils/lngFrame';
import { GHOST_SIZE, mountGhosts, setGhostHot, type GhostHandlers } from './assistantGhostMarker';
import { useLngFrame } from './lngFrameContext';
import type { AssistantGhost } from './mapViewContract';

interface AssistantGhostLayerProps {
  ghosts: readonly AssistantGhost[] | undefined;
  hoveredId: string | null | undefined;
  onHover?: (id: string | null) => void;
  onClick?: (id: string) => void;
}

/** Above the place pins, so a suggestion on a busy day is never buried under the stops it joins. */
const GHOST_Z_OFFSET = 900;

/**
 * The assistant's suggestions on the Leaflet map, outside the cluster group:
 * a suggestion stands on its own until it is decided. The name shows in the
 * map's own tooltip, built from text. A hover only toggles a class on the
 * element; the pins are rebuilt when the suggestions change, never on hover.
 */
export function AssistantGhostLayer({ ghosts, hoveredId, onHover, onClick }: AssistantGhostLayerProps) {
  const map = useMap();
  // Pinned where the map draws the trip, in its longitude frame (#2975).
  const frame = useLngFrame();
  const handlers = useRef<GhostHandlers>({ onHover, onClick });
  useLayoutEffect(() => {
    handlers.current = { onHover, onClick };
  }, [onHover, onClick]);
  const elements = useRef<ReadonlyMap<string, HTMLElement>>(new Map());

  useEffect(() => {
    if (!ghosts?.length) return;
    const mounted = mountGhosts(
      ghosts,
      (el, ghost) => {
        const icon = L.divIcon({ html: el, className: 'trek-ghost-pin', iconSize: [GHOST_SIZE, GHOST_SIZE] });
        const label = document.createElement('span');
        label.textContent = ghost.name;
        const marker = L.marker([ghost.lat, frameLng(frame, ghost.lng)], {
          icon,
          keyboard: false,
          zIndexOffset: GHOST_Z_OFFSET,
        })
          .bindTooltip(label, { direction: 'top', offset: [0, -GHOST_SIZE / 2], className: 'map-tooltip' })
          .addTo(map);
        return { remove: () => marker.remove() };
      },
      handlers
    );
    elements.current = mounted.elements;
    return () => {
      mounted.dispose();
      elements.current = new Map();
    };
  }, [ghosts, map, frame]);

  useEffect(() => {
    setGhostHot(elements.current, hoveredId);
  }, [ghosts, hoveredId]);

  return null;
}