All files / applications/go-by-transit/src/view/nearby/components NearbySimpleRoutes.tsx

88.88% Statements 72/81
80.76% Branches 63/78
80% Functions 20/25
89.47% Lines 68/76

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 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366                                                                                                            106x 106x 106x 106x 106x   106x 106x 106x 106x 106x 106x 106x     106x     106x 106x   106x 57x       100x 6x       106x 28x     28x 28x 28x   28x       28x   28x 8x           8x 8x     20x 35x       20x 20x 19x 19x 19x     1x 1x 1x         28x 28x 28x       106x   105x             106x   92x                 106x       106x       106x   212x     106x     106x         106x             2x 2x 2x         1x               11x 11x 11x 11x       52x 52x 52x     106x                                                                                                                                   212x   144x                                                                                                                                                                              
import { Button, Select } from "@wintermuted/ui-react";
import { MultiSelect } from "@wintermuted/ui-react/select";
import { join, map } from "lodash";
import React, { useEffect, useMemo, useRef, useState } from "react";
import { useSearchParams } from "react-router-dom";
import { getArrivals } from "../../../api/trimet/arrivals";
import { ArrivalData } from "../../../api/trimet/interfaces/arrivals";
import { StopData } from "../../../api/trimet/interfaces/types";
import Loading from "../../loading/Loading";
import useStopHighlight from "../util/useStopHighlight";
import useWalkingEstimates from "../util/useWalkingEstimates";
import NearbyRouteControlPopover from "./NearbyRouteControlPopover";
import NearbySubNav from "./common/NearbySubNav";
import "./NearbyRoutes.scss";
import SimpleRouteGroups from "./SimpleRouteGroups";
import { filterRouteStructures, getRouteArrivals, getDisplayRoutes } from "./nearbyRouteArrivals";
import NearbyRouteInfo from "./NearbyRouteInfo";
import { TrimetRoute as DetailedRoute } from "../../../api/trimet/interfaces/routes";
 
export { filterRouteStructures, getRouteArrivals } from "./nearbyRouteArrivals";
export type { RouteStructure } from "./nearbyRouteArrivals";
 
interface Props {
  nearbyStops: StopData;
  currentLocation: number[];
  radiusSize: number;
  handleSimpleRoutesOpened: () => void;
  handleRadiusSelectionChange: (e: any) => void;
  routeCount: number;
  stopCount: number;
  onStopHighlightChanged?: (stopId?: number) => void;
  walkingEnabled?: boolean;
  onRouteInfoChanged?: (route: DetailedRoute, onError: () => void) => () => void;
  onRouteInfoStopHighlighted?: (stopId?: number) => void;
}
 
interface FilterOption {
  label: string;
  value: string;
}
 
export default function NearbySimpleRoutes({
  nearbyStops,
  currentLocation,
  radiusSize,
  handleRadiusSelectionChange,
  handleSimpleRoutesOpened,
  routeCount,
  stopCount,
  onStopHighlightChanged,
  walkingEnabled = false,
  onRouteInfoChanged,
  onRouteInfoStopHighlighted,
}: Props) {
  const [searchParams, setSearchParams] = useSearchParams();
  const routeValues = searchParams.getAll("route");
  const routeValue = routeValues[0];
  const parsedRoute = /^\d+$/.test(routeValue || "") ? Number(routeValue) : NaN;
  const infoRouteId = routeValues.length === 1 && Number.isSafeInteger(parsedRoute) && parsedRoute > 0
    ? parsedRoute : undefined;
  const invalidRoute = routeValues.length > 0 && infoRouteId === undefined;
  const infoButton = useRef<HTMLAnchorElement>(null);
  const [arrivalData, setArrivalData] = useState<ArrivalData>();
  const [isLoading, setIsLoading] = useState(true);
  const [loadError, setLoadError] = useState(false);
  const [retryCount, setRetryCount] = useState(0);
  const [selectedFilterValues, setSelectedFilterValues] = useState<string[]>(
    []
  );
  const [sortBy, setSortBy] = useState<"arrival" | "distance" | "route">(
    "arrival"
  );
  const { clearHighlight, focusStop, hoverStop } = useStopHighlight(onStopHighlightChanged);
  const walking = useWalkingEstimates(currentLocation, nearbyStops?.location ?? [], walkingEnabled);
 
  useEffect(() => {
    clearHighlight();
  }, [nearbyStops, isLoading, selectedFilterValues, sortBy, clearHighlight]);
 
  function handleDisclosureToggle(event: React.SyntheticEvent<HTMLDetailsElement>) {
    if (!event.currentTarget.open) {
      clearHighlight();
    }
  }
 
  useEffect(() => {
    let active = true;
 
    async function fetchData() {
      setIsLoading(true);
      setLoadError(false);
      setArrivalData(undefined);
 
      Iif (!nearbyStops) {
        return;
      }
 
      handleSimpleRoutesOpened();
 
      if (!nearbyStops.location?.length) {
        setArrivalData({
          arrival: [],
          detour: [],
          location: [],
          queryTime: "",
        });
        setIsLoading(false);
        return;
      }
 
      const locationIds = join(
        map(nearbyStops.location, (location) => location.locid),
        ","
      );
 
      try {
        const arrivals = await getArrivals(locationIds, 90);
        Eif (active) {
          setArrivalData(arrivals);
          setIsLoading(false);
        }
      } catch {
        Eif (active) {
          setLoadError(true);
          setIsLoading(false);
        }
      }
    }
 
    void fetchData();
    return () => {
      active = false;
    };
  }, [nearbyStops, retryCount]);
 
  const routeStructures = useMemo(
    () =>
      arrivalData
        ? getRouteArrivals(arrivalData, nearbyStops, currentLocation,
            walkingEnabled ? walking.estimates : undefined)
        : [],
    [arrivalData, nearbyStops, currentLocation, walkingEnabled, walking.estimates]
  );
 
  const routeOptions: FilterOption[] = Array.from(
    new Map(
      routeStructures.map((route) => [
        String(route.route.route),
        {
          label: `Route ${route.route.route} — ${route.route.desc}`,
          value: `route:${route.route.route}`,
        },
      ])
    ).values()
  );
  const directionOptions: FilterOption[] = routeStructures.map((route) => ({
    label: `Route ${route.route.route} — ${route.direction.desc}`,
    value: `direction:${route.key}`,
  }));
  const filterOptions = [
    { label: "Routes", options: routeOptions },
    { label: "Directions", options: directionOptions },
  ];
  const availableFilterValues = new Set(
    filterOptions.flatMap((group) =>
      group.options.map((option) => option.value)
    )
  );
  const activeFilterValues = selectedFilterValues.filter((value) =>
    availableFilterValues.has(value)
  );
  const filteredRoutes = filterRouteStructures(
    routeStructures,
    activeFilterValues
  );
 
  const displayRoutes = getDisplayRoutes(filteredRoutes, sortBy, walkingEnabled);
 
  function handleFilterChange(selected: readonly FilterOption[]) {
    setSelectedFilterValues(selected.map((option) => option.value));
  }
 
  function handleSortChange(event: React.ChangeEvent<HTMLSelectElement>) {
    const value = event.currentTarget.value;
    Eif (value === "arrival" || value === "distance" || value === "route") {
      setSortBy(value);
    }
  }
 
  function handleRetry() {
    setRetryCount((count) => count + 1);
  }
 
  function handleClearFilters() {
    setSelectedFilterValues([]);
  }
 
  function closeRouteInfo() {
    const next = new URLSearchParams(searchParams);
    next.delete("route");
    setSearchParams(next, { replace: true });
    requestAnimationFrame(() => infoButton.current?.focus());
  }
 
  function routeInfoSearch(routeId: number) {
    const next = new URLSearchParams(searchParams);
    next.set("route", String(routeId));
    return `?${next.toString()}`;
  }
 
  return (
    <>
    {infoRouteId !== undefined && (
      <NearbyRouteInfo
        key={infoRouteId}
        routeId={infoRouteId}
        onMapChanged={onRouteInfoChanged}
        onStopHighlightChanged={onRouteInfoStopHighlighted}
        onClose={closeRouteInfo}
      />
    )}
    {invalidRoute && (
      <section className="transit-destination-panel" aria-label="Route details" onKeyDown={(event) => {
        if (event.key === "Escape") {
          event.preventDefault();
          event.stopPropagation();
          closeRouteInfo();
        }
      }}>
        <p role="alert">Invalid route number in the link.</p>
        <Button autoFocus variant="secondary" onClick={closeRouteInfo}>Close</Button>
      </section>
    )}
    <div hidden={infoRouteId !== undefined || invalidRoute}>
    <div id="nearby-view-routes" className="scrollarea transit-explore-routes">
      <NearbySubNav routeCount={routeCount} stopCount={stopCount} />
      {walkingEnabled && walking.status === "loading" && (
        <p role="status">Calculating walking distances...</p>
      )}
      {walkingEnabled && walking.status === "error" && (
        <div role="alert">
          <p>Walking estimates unavailable. {walking.error} Straight-line distances are labeled below.</p>
          <Button variant="secondary" onClick={walking.refresh}>Retry walking estimates</Button>
        </div>
      )}
      {walkingEnabled && walking.status === "ready" && (
        <Button variant="link" onClick={walking.refresh}>Refresh walking estimates</Button>
      )}
      {!nearbyStops ? (
        <Loading />
      ) : (
        <>
          <div className="transit-route-controls">
            <NearbyRouteControlPopover
              icon="filter"
              activeCount={activeFilterValues.length}
              buttonLabel={
                activeFilterValues.length > 0
                  ? `Filter (${activeFilterValues.length})`
                  : "Filter"
              }
              disabled={isLoading || routeStructures.length === 0}
              label="Route filters"
            >
              <label
                className="transit-route-filter-label"
                htmlFor="nearby-route-filter"
              >
                Filter by route or direction
              </label>
              <MultiSelect<FilterOption>
                id="nearby-route-filter"
                aria-label="Filter by route or direction"
                className="transit-route-filter"
                options={filterOptions}
                value={filterOptions
                  .flatMap((group) => group.options)
                  .filter((option) =>
                    activeFilterValues.includes(option.value)
                  )}
                onChange={handleFilterChange}
                placeholder="All nearby routes"
                isDisabled={isLoading || routeStructures.length === 0}
              />
              {activeFilterValues.length > 0 && (
                <Button
                  type="button"
                  variant="link"
                  className="transit-route-filter-clear"
                  onClick={handleClearFilters}
                >
                  Clear filters
                </Button>
              )}
            </NearbyRouteControlPopover>
            <NearbyRouteControlPopover
              icon="sort-amount-asc"
              buttonLabel={`Sort: ${
                sortBy === "arrival"
                  ? "Soonest arrival"
                  : sortBy === "distance"
                    ? `Nearest stop (${walkingEnabled ? "walking" : "straight-line"})`
                    : "Route number"
              }`}
              label="Route sorting"
            >
              <div className="transit-route-sort">
                <label htmlFor="nearby-route-sort">Sort by</label>
                <Select
                  id="nearby-route-sort"
                  value={sortBy}
                  onChange={handleSortChange}
                >
                  <option value="arrival">Soonest arrival</option>
                  <option value="distance">Nearest stop ({walkingEnabled ? "walking" : "straight-line"})</option>
                  <option value="route">Route number</option>
                </Select>
              </div>
            </NearbyRouteControlPopover>
          </div>
          {isLoading ? (
            <p role="status">Loading nearby route arrivals…</p>
          ) : loadError ? (
            <div role="alert" className="transit-route-list-message">
              <p>Nearby arrivals could not be loaded.</p>
              <Button type="button" variant="link" onClick={handleRetry}>
                Retry
              </Button>
            </div>
          ) : !nearbyStops.location?.length ? (
            <p role="status" className="transit-route-list-message">
              No stops were found within this search area.
            </p>
          ) : routeStructures.length === 0 ? (
            <p role="status" className="transit-route-list-message">
              No routes were found within this search area.
            </p>
          ) : filteredRoutes.length === 0 ? (
            <div className="transit-route-list-message">
              <p role="status">No nearby routes match these filters.</p>
              <Button type="button" variant="link" onClick={handleClearFilters}>
                Clear filters
              </Button>
            </div>
          ) : (
            <SimpleRouteGroups
              displayRoutes={displayRoutes}
              currentLocation={currentLocation}
              walkingEnabled={walkingEnabled}
              walkingLoading={walking.status === "loading"}
              focusStop={focusStop}
              hoverStop={hoverStop}
              clearHighlight={clearHighlight}
              handleDisclosureToggle={handleDisclosureToggle}
              infoButton={infoButton}
              routeInfoSearch={routeInfoSearch}
            />
          )}
        </>
      )}
    </div>
    </div>
    </>
  );
}