All files / applications/go-by-transit/src/view/nearby/util useVehiclePositions.ts

100% Statements 17/17
75% Branches 6/8
100% Functions 9/9
100% Lines 13/13

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                    17x 34x 17x 17x 17x 17x             53x 17x   10x 10x     12x 12x     53x    
import { useMemo } from "react";
import type { Map as MapboxMap } from "mapbox-gl";
import { useVehiclePositions as usePositions } from "@overworld/trimet-client/react";
import type { VehicleViewport } from "@overworld/trimet-client/react";
import type { VehicleBounds } from "@overworld/trimet-client";
import { getVehicles } from "../../../api/trimet/vehicles";
 
export type { VehicleFeed } from "@overworld/trimet-client/react";
 
function viewportBounds(map: MapboxMap): VehicleBounds {
  const bounds = map.getBounds();
  const wrap = (longitude: number) => ((longitude + 180) % 360 + 360) % 360 - 180;
  const west = wrap(bounds.getWest());
  const east = wrap(bounds.getEast());
  const wholeWorld = bounds.getEast() - bounds.getWest() >= 360 || west > east;
  return [
    wholeWorld ? -180 : west, Math.max(-90, bounds.getSouth()),
    wholeWorld ? 180 : east, Math.min(90, bounds.getNorth()),
  ];
}
 
export function useVehiclePositions(map: MapboxMap | undefined, enabled: boolean, vehicleId?: string) {
  const viewport = useMemo<VehicleViewport | undefined>(() => map && ({
    getBounds: () => viewportBounds(map),
    subscribeMove(listener) {
      map.on("moveend", listener);
      return () => { map.off("moveend", listener); };
    },
    subscribeRemove(listener) {
      map.on("remove", listener);
      return () => { map.off("remove", listener); };
    }
  }), [map]);
  return usePositions(viewport, enabled, getVehicles, vehicleId);
}