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 | 1376x 1376x 281x 281x 281x 281x 1376x 60x 60x 60x 60x 1376x 1376x 60x 60x 60x 26x 16x 16x 16x 16x 19x 19x 19x 19x 23x 9x 23x 19x 23x 23x 20x 20x 3x 23x 18x 18x 18x 26x 18x 26x 19x 16x 16x 16x 16x 16x 60x 60x 60x 1372x 60x 2x 36x 1376x 1376x 1074x 1376x 1376x 1376x | import { Badge } from "@wintermuted/ui-react";
import { map } from "lodash";
import React, { useEffect, useState } from "react";
import FontAwesome from "react-fontawesome";
import { getArrivals } from "../../../../api/trimet/arrivals";
import { Arrival } from "../../../../api/trimet/interfaces/arrivals";
import { RouteDirectionStop } from "../../../../api/trimet/interfaces/routes";
import { StopData, TrimetRoute } from "../../../../api/trimet/interfaces/types";
import { getNearbyStops } from "../../../../api/trimet/stops";
import { getMatchingStopTime, reportedTime } from "../../util/tripTimes";
import { StopPredictionList, useTimeDisplay } from "@overworld/ui";
interface StopsOnRouteParams {
remainingStopsOnRoute: RouteDirectionStop[];
selectedArrival?: Arrival;
repeatedStopIds?: number[];
}
interface PredictionBatch {
ids: number[];
arrivals: Arrival[] | null;
error: boolean;
loading: boolean;
}
interface PredictionsState {
key: string;
batches: PredictionBatch[];
loading: boolean;
}
function RouteAtStop({ stopData }: { stopData: StopData }) {
const routes: TrimetRoute[] = stopData.location[0].route;
return (
<div className="route-at-stop">
<FontAwesome name="bus" />
{map(routes, (route: TrimetRoute) => {
return (
<Badge key={route.route} tone="neutral">
{route.route}
</Badge>
);
})}
</div>
);
}
function StopRoutes({
routeDirectionStop,
}: {
routeDirectionStop: RouteDirectionStop;
}) {
const [stopData, setStopData] = useState<StopData>(null);
useEffect(() => {
async function fetchData() {
Eif (routeDirectionStop) {
const location = {
coords: {
latitude: routeDirectionStop.lat,
longitude: routeDirectionStop.lng,
},
};
const nearbyStopData = await getNearbyStops(location, 10);
setStopData(nearbyStopData);
}
}
fetchData();
}, [routeDirectionStop]);
return stopData && <RouteAtStop stopData={stopData} />;
}
export function StopsOnRoute({
remainingStopsOnRoute,
selectedArrival,
repeatedStopIds = [],
}: StopsOnRouteParams) {
const { timezone } = useTimeDisplay();
const [retry, setRetry] = useState(0);
const [state, setState] = useState<PredictionsState>();
const ids = Array.from(
new Set(
remainingStopsOnRoute
.map((stop) => stop.locid)
.filter((id) => !repeatedStopIds.includes(id)),
),
);
const key = JSON.stringify([
selectedArrival?.id,
selectedArrival?.tripID,
selectedArrival?.route,
selectedArrival?.dir,
selectedArrival?.locid,
ids,
]);
const canFetch =
!!selectedArrival?.tripID &&
!!reportedTime(selectedArrival) &&
ids.length > 0;
useEffect(() => {
if (!canFetch) return;
let active = true;
let pending = false;
const groups: number[][] = [];
for (let index = 0; index < ids.length; index += 128) {
groups.push(ids.slice(index, index + 128));
}
async function load() {
Iif (pending) return;
pending = true;
setState((previous) => ({
key,
batches: groups.map((group) => {
const last =
previous?.key === key
? previous.batches.find(
(batch) => batch.ids.join(",") === group.join(","),
)
: undefined;
return {
ids: group,
arrivals: last?.arrivals ?? null,
error: false,
loading: true,
};
}),
loading: true,
}));
await Promise.all(
groups.map(async (group) => {
let result: { arrivals: Arrival[] | null; error: boolean };
try {
const data = await getArrivals(group.join(","), 60);
Iif (
!data ||
"errorMessage" in data ||
!Array.isArray(data.location) ||
(data.arrival != null && !Array.isArray(data.arrival))
) {
throw new Error("Invalid stop predictions response");
}
result = { arrivals: data.arrival ?? [], error: false };
} catch {
result = { arrivals: null, error: true };
}
if (active)
setState((previous) => {
Iif (!previous || previous.key !== key) return previous;
const batches = previous.batches.map((batch) =>
batch.ids.join(",") === group.join(",")
? {
...batch,
arrivals: result.error ? batch.arrivals : result.arrivals,
error: result.error,
loading: false,
}
: batch,
);
return {
key,
batches,
loading: batches.some((batch) => batch.loading),
};
});
}),
);
pending = false;
}
load();
const timer = window.setInterval(load, 30000);
return () => {
active = false;
window.clearInterval(timer);
};
}, [key, canFetch, retry]);
const current = state?.key === key ? state : undefined;
const hasError = current?.batches.some((batch) => batch.error);
const hasRepeatedStops = remainingStopsOnRoute.some((stop) =>
repeatedStopIds.includes(stop.locid),
);
return (
<StopPredictionList
updateNote={
canFetch && (
<>
{timezone === "utc"
? "UTC"
: timezone === "local"
? "Device local time"
: "Pacific time"}
{" ยท "}Updates every 30 seconds
</>
)
}
onRefresh={canFetch ? () => setRetry((value) => value + 1) : undefined}
refreshLabel={
!current || current.loading
? "Retry"
: hasError
? "Try again"
: "Refresh"
}
loading={
canFetch &&
(!current ||
current.batches.some((batch) => batch.loading && !batch.arrivals))
}
error={
hasError &&
"Some stop predictions could not be loaded or refreshed. Last received times are labeled; try again."
}
notices={[
...(selectedArrival && !selectedArrival.tripID
? ["This departure has no trip ID; stop times are not reported."]
: []),
...(hasRepeatedStops
? ["Times for repeated stops cannot be matched reliably."]
: []),
]}
stops={remainingStopsOnRoute.map((routeDirectionStop) => {
const repeated = repeatedStopIds.includes(routeDirectionStop.locid);
const batch = current?.batches.find((item) =>
item.ids.includes(routeDirectionStop.locid),
);
const prediction =
!repeated && selectedArrival && batch?.arrivals
? getMatchingStopTime(
selectedArrival,
batch.arrivals,
routeDirectionStop.locid,
)
: undefined;
const predictionLabel = !selectedArrival
? "Select a departure"
: repeated ||
!selectedArrival.tripID ||
!reportedTime(selectedArrival)
? "Not reported"
: !batch || (batch.loading && !batch.arrivals)
? "Loading..."
: batch.error
? "Unavailable"
: "Not reported";
return {
id: `${routeDirectionStop.locid}-${routeDirectionStop.seq}`,
name: routeDirectionStop.desc,
stopId: routeDirectionStop.locid,
prediction,
predictionLabel,
stale: !!batch?.error,
routes: <StopRoutes routeDirectionStop={routeDirectionStop} />,
};
})}
/>
);
}
|