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

89.58% Statements 43/48
69.23% Branches 18/26
83.33% Functions 25/30
90.69% Lines 39/43

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                                                                      3x 2x   2x 2x   2x   4x 4x 4x                 2x       2x                         5x   2x 1x   5x   2x 1x     5x   4x   4x     2x   4x   4x                                   3x 3x 3x 3x       3x       3x 4x         3x       3x   6x     3x     3x                   3x                                                       6x 6x                                                           2x                       4x                                          
import {
  Button,
  Card,
  CardHeader,
  ListGroup,
  ListItem,
} from "@wintermuted/ui-react";
import { MultiSelect } from "@wintermuted/ui-react/select";
import { Dictionary } from "lodash";
import React, { useMemo, useState } from "react";
import { Link } from "react-router-dom";
import { Direction, TrimetRoute } from "../../../api/trimet/interfaces/types";
import RouteIndicator from "../../../component/route/RouteIndicator";
import NearbyRouteControlPopover from "./NearbyRouteControlPopover";
import NearbySubNav from "./common/NearbySubNav";
import "./NearbyRoutes.scss";
 
interface RouteDirection {
  key: string;
  routeId: number;
  direction: Direction;
}
 
interface RouteGroup {
  routeId: number;
  description: string;
  directions: RouteDirection[];
}
 
interface FilterOption {
  label: string;
  value: string;
}
 
function getRouteGroups(routes: Dictionary<TrimetRoute[]>): RouteGroup[] {
  return Object.values(routes || {})
    .filter((group) => group?.length > 0)
    .map((group) => {
      const routeId = group[0].route;
      const directions = new Map<string, RouteDirection>();
 
      group.forEach((route) =>
        (route.dir || []).forEach((direction) => {
          const key = `${route.route}-${direction.dir}`;
          Eif (!directions.has(key)) {
            directions.set(key, {
              direction,
              key,
              routeId: route.route,
            });
          }
        })
      );
 
      return {
        description: group[0].desc,
        directions: Array.from(directions.values()).sort(
          (a, b) =>
            a.direction.desc.localeCompare(b.direction.desc) ||
            a.direction.dir - b.direction.dir
        ),
        routeId,
      };
    })
    .sort((a, b) => a.routeId - b.routeId);
}
 
export function filterRouteGroups(
  groups: RouteGroup[],
  selectedValues: string[]
): Array<RouteGroup & { visibleDirections: RouteDirection[] }> {
  const selectedRoutes = new Set(
    selectedValues
      .filter((value) => value.startsWith("route:"))
      .map((value) => value.slice("route:".length))
  );
  const selectedDirections = new Set(
    selectedValues
      .filter((value) => value.startsWith("direction:"))
      .map((value) => value.slice("direction:".length))
  );
 
  return groups
    .map((group) => {
      const routeSelected = selectedRoutes.has(String(group.routeId));
      const visibleDirections =
        selectedValues.length === 0 || routeSelected
          ? group.directions
          : group.directions.filter((direction) =>
              selectedDirections.has(direction.key)
            );
      return { ...group, visibleDirections };
    })
    .filter((group) => group.visibleDirections.length > 0);
}
 
export interface NearbyRoutesProps {
  nearbyRoutes: Dictionary<TrimetRoute[]>;
  radiusSize: number;
  handleRadiusSelectionChange: (e: any) => void;
  routeCount: number;
  stopCount: number;
}
 
export default function NearbyRoutes({
  nearbyRoutes,
  radiusSize,
  handleRadiusSelectionChange,
  routeCount,
  stopCount,
}: NearbyRoutesProps) {
  const [selectedValues, setSelectedValues] = useState<string[]>([]);
  const isLoading = nearbyRoutes == null;
  const routeGroups = useMemo(
    () => getRouteGroups(nearbyRoutes),
    [nearbyRoutes]
  );
 
  const routeOptions: FilterOption[] = routeGroups.map((group) => ({
    label: `Route ${group.routeId} — ${group.description}`,
    value: `route:${group.routeId}`,
  }));
  const directionOptions: FilterOption[] = routeGroups.flatMap((group) =>
    group.directions.map((direction) => ({
      label: `Route ${group.routeId} — ${direction.direction.desc}`,
      value: `direction:${direction.key}`,
    }))
  );
  const filterOptions = [
    { label: "Routes", options: routeOptions },
    { label: "Directions", options: directionOptions },
  ];
  const availableValues = new Set(
    filterOptions.flatMap((group) =>
      group.options.map((option) => option.value)
    )
  );
  const activeValues = selectedValues.filter((value) =>
    availableValues.has(value)
  );
  const filteredGroups = filterRouteGroups(routeGroups, activeValues);
 
  function handleFilterChange(selected: readonly FilterOption[]) {
    setSelectedValues(selected.map((option) => option.value));
  }
 
  function handleClearFilters() {
    setSelectedValues([]);
  }
 
  return (
    <div id="nearby-view-routes" className="scrollarea">
      <NearbySubNav routeCount={routeCount} stopCount={stopCount} />
      <br />
      <div className="transit-route-controls">
        <NearbyRouteControlPopover
          icon="filter"
          activeCount={activeValues.length}
          buttonLabel={
            activeValues.length > 0
              ? `Filter (${activeValues.length})`
              : "Filter"
          }
          disabled={isLoading || routeGroups.length === 0}
          label="Route filters"
        >
          <label
            className="transit-route-filter-label"
            htmlFor="nearby-routes-filter"
          >
            Filter by route or direction
          </label>
          <MultiSelect<FilterOption>
            id="nearby-routes-filter"
            aria-label="Filter by route or direction"
            className="transit-route-filter"
            options={filterOptions}
            value={filterOptions
              .flatMap((group) => group.options)
              .filter((option) => activeValues.includes(option.value))}
            onChange={handleFilterChange}
            placeholder="All nearby routes"
            isDisabled={isLoading || routeGroups.length === 0}
          />
          {activeValues.length > 0 && (
            <Button
              type="button"
              variant="link"
              className="transit-route-filter-clear"
              onClick={handleClearFilters}
            >
              Clear filters
            </Button>
          )}
        </NearbyRouteControlPopover>
      </div>
      {isLoading ? (
        <p role="status">Loading nearby routes…</p>
      ) : routeGroups.length === 0 ? (
        <p role="status" className="transit-route-list-message">
          No routes were found within this search area.
        </p>
      ) : filteredGroups.length === 0 ? (
        <p role="status" className="transit-route-list-message">
          No nearby routes match these filters.
        </p>
      ) : (
        <div className="transit-route-groups">
          {filteredGroups.map((group) => (
            <Card key={group.routeId}>
              <CardHeader as="h5" className="transit-route-card-header">
                <Link
                  to={`/lines/${group.routeId}`}
                  aria-label={`View Route ${group.routeId} details`}
                >
                  <RouteIndicator routeId={group.routeId} linked={false} />
                  <span>{group.description}</span>
                </Link>
              </CardHeader>
              <ListGroup>
                {group.visibleDirections.map(({ key, routeId, direction }) => (
                  <ListItem key={key}>
                    <Link
                      className="transit-route-direction-link"
                      to={`/nearby/simple-routes/${routeId}?direction=${direction.dir}`}
                    >
                      <RouteIndicator routeId={routeId} linked={false} />
                      <span>{direction.desc}</span>
                      <span className="transit-route-direction-action">
                        View arrivals
                      </span>
                    </Link>
                  </ListItem>
                ))}
              </ListGroup>
            </Card>
          ))}
        </div>
      )}
    </div>
  );
}