Skip to content

Commit

Permalink
Merge branch 'dev' into trusted-companions
Browse files Browse the repository at this point in the history
  • Loading branch information
binh-dam-ibigroup authored Nov 7, 2024
2 parents a0fa2c7 + f2b0a69 commit c741d54
Show file tree
Hide file tree
Showing 14 changed files with 2,675 additions and 4,956 deletions.
543 changes: 543 additions & 0 deletions __tests__/components/viewers/__snapshots__/nearby-view.js.snap

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion craco.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ module.exports = {
}
addBeforeLoader(webpackConfig, loaderByName('file-loader'), yamlLoader)

// Support YAML
// Support import of raw GraphQL files
const graphqlLoader = {
loader: ['raw-loader'],
test: /\.graphql$/
Expand Down
2 changes: 2 additions & 0 deletions example-config.yml
Original file line number Diff line number Diff line change
Expand Up @@ -677,6 +677,8 @@ disableSingleItineraryDays: false
# maxRealtimeVehicleAge: 60
# # Interval for refreshing vehicle positions
# vehiclePositionRefreshSeconds: 30 # defaults to 30 seconds.
# # Enable this to restrict listing to routes active within the last to next Sunday
# onlyShowCurrentServiceWeek: true

# API key to make Mapillary API calls. These are used to show street imagery.
# Mapillary calls these "Client Tokens". They can be created at https://www.mapillary.com/dashboard/developers
Expand Down
4 changes: 2 additions & 2 deletions lib/actions/api.js
Original file line number Diff line number Diff line change
Expand Up @@ -370,8 +370,8 @@ export function vehicleRentalQuery(
export const fetchNearbyResponse = createAction('FETCH_NEARBY_RESPONSE')
export const fetchNearbyError = createAction('FETCH_NEARBY_ERROR')

export function fetchNearby(coords, map) {
return executeOTPAction('fetchNearby', coords, map)
export function fetchNearby(coords, map, currentServiceWeek) {
return executeOTPAction('fetchNearby', coords, map, currentServiceWeek)
}

// Single trip lookup query
Expand Down
51 changes: 38 additions & 13 deletions lib/actions/apiV2.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,11 @@ import {
isValidSubsequence,
queryIsValid
} from '../util/state'
import { getCurrentServiceWeek } from '../util/current-service-week'
import {
getRouteColorBasedOnSettings,
getRouteIdForPattern,
getRouteTextColorBasedOnSettings,
routeIsValid
} from '../util/viewer'
import { isLastStop } from '../util/stop-times'
Expand Down Expand Up @@ -379,14 +381,15 @@ export const fetchNearbyFromStopId = (stopId) => {
)
}

export const fetchNearby = (position, radius) => {
export const fetchNearby = (position, radius, currentServiceWeek) => {
const { lat, lon } = position

return createGraphQLQueryAction(
`query Nearby(
$lat: Float!
$lon: Float!
$radius: Int
$currentServiceWeek: LocalDateRangeInput
) {
nearest(lat:$lat, lon:$lon, maxDistance: $radius, first: 100, filterByPlaceTypes: [STOP, VEHICLE_RENT, BIKE_PARK, CAR_PARK]) {
edges {
Expand Down Expand Up @@ -436,11 +439,15 @@ export const fetchNearby = (position, radius) => {
lon
code
gtfsId
stopRoutes: routes (serviceDates: $currentServiceWeek) {
gtfsId
}
stoptimesForPatterns {
pattern {
headsign
desc: name
route {
gtfsId
agency {
name
gtfsId
Expand Down Expand Up @@ -474,7 +481,7 @@ export const fetchNearby = (position, radius) => {
}
}
}`,
{ lat, lon, radius },
{ currentServiceWeek, lat, lon, radius },
fetchNearbyResponse,
fetchNearbyError,
{
Expand Down Expand Up @@ -857,10 +864,18 @@ export const findRoute = (params) =>

export function findRoutes() {
return function (dispatch, getState) {
// Only calculate current service week if the setting for it is enabled
const currentServiceWeek =
getState().otp?.config?.routeViewer?.onlyShowCurrentServiceWeek === true
? getCurrentServiceWeek()
: undefined

dispatch(
createGraphQLQueryAction(
`{
routes {
`query Routes(
$currentServiceWeek: LocalDateRangeInput
) {
routes (serviceDates: $currentServiceWeek) {
id: gtfsId
agency {
id: gtfsId
Expand All @@ -875,7 +890,7 @@ export function findRoutes() {
}
}
`,
{},
{ currentServiceWeek },
findRoutesResponse,
findRoutesError,
{
Expand Down Expand Up @@ -1135,20 +1150,30 @@ export function routingQuery(searchId = null, updateSearchInReducer) {
...itin,
legs: itin.legs
?.map((leg) => {
const routeOperator = getRouteOperator(
{
agencyId: leg?.agency?.id,
id: leg?.route?.id
},
config.transitOperators
)
const routeProperties = {
color: leg?.route?.color,
mode: leg.mode
}

return {
...leg,
origColor: leg?.route?.color,
route: {
...leg.route,
color: getRouteColorBasedOnSettings(
getRouteOperator(
{
agencyId: leg?.agency?.id,
id: leg?.route?.id
},
config.transitOperators
),
{ color: leg?.route?.color, mode: leg.mode }
routeOperator,
routeProperties
).split('#')?.[1],
textColor: getRouteTextColorBasedOnSettings(
routeOperator,
routeProperties
).split('#')?.[1]
}
}
Expand Down
39 changes: 15 additions & 24 deletions lib/components/map/itinerary-summary-overlay.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { Marker } from 'react-map-gl'
import centroid from '@turf/centroid'
import distance from '@turf/distance'
import polyline from '@mapbox/polyline'
import React, { useContext, useState } from 'react'
import React, { useContext } from 'react'
import styled from 'styled-components'

import * as narriativeActions from '../../actions/narrative'
Expand Down Expand Up @@ -147,19 +147,20 @@ const ItinerarySummaryOverlay = ({
// @ts-expect-error React context is populated dynamically
const { LegIcon } = useContext(ComponentContext)

const [sharedTimeout, setSharedTimeout] = useState<null | NodeJS.Timeout>(
null
)

if (!itins || !visible) return <></>
const mergedItins: ItinWithGeometry[] = addTrueIndex(
doMergeItineraries(itins).mergedItineraries.map(addItinLineString)
const indexedItins: ItinWithGeometry[] = addTrueIndex(
itins.map(addItinLineString)
)
const mergedItins: ItinWithGeometry[] =
doMergeItineraries(indexedItins).mergedItineraries

const midPoints = mergedItins.reduce<ItinUniquePoint[]>(
(prev: ItinUniquePoint[], curItin: ItinWithGeometry) => {
prev.push(getUniquePoint(curItin, prev))
return prev
},
[]
)

const midPoints = mergedItins.reduce<ItinUniquePoint[]>((prev, curItin) => {
prev.push(getUniquePoint(curItin, prev))
return prev
}, [])
// The first point is probably not well placed, so let's run the algorithm again
if (midPoints.length > 1) {
midPoints[0] = getUniquePoint(mergedItins[0], midPoints)
Expand All @@ -186,18 +187,8 @@ const ItinerarySummaryOverlay = ({
onClick={() => {
setActive({ index: mp.itin.index })
}}
// TODO: useCallback here (getting weird errors?)
onMouseEnter={() => {
setSharedTimeout(
setTimeout(() => {
setVisible({ index: mp.itin.index })
}, 150)
)
}}
onMouseLeave={() => {
sharedTimeout && clearTimeout(sharedTimeout)
setVisible({ index: null })
}}
// TODO: restore setting visible itinerary on hover without
// causing endless re-render?
>
<MetroItineraryRoutes
expanded={false}
Expand Down
35 changes: 30 additions & 5 deletions lib/components/viewers/nearby/nearby-view.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import * as apiActions from '../../../actions/api'
import * as mapActions from '../../../actions/map'
import * as uiActions from '../../../actions/ui'
import { AppReduxState } from '../../../util/state-types'
import { getCurrentServiceWeek } from '../../../util/current-service-week'
import { SetLocationHandler, ZoomToPlaceHandler } from '../../util/types'
import Loading from '../../narrative/loading'
import MobileContainer from '../../mobile/container'
Expand All @@ -31,13 +32,19 @@ const AUTO_REFRESH_INTERVAL = 15000
// TODO: use lonlat package
type LatLonObj = { lat: number; lon: number }
type CurrentPosition = { coords?: { latitude: number; longitude: number } }
type ServiceWeek = { end: string; start: string }

type Props = {
currentPosition?: CurrentPosition
currentServiceWeek?: ServiceWeek
defaultLatLon: LatLonObj | null
displayedCoords?: LatLonObj
entityId?: string
fetchNearby: (latLon: LatLonObj, radius?: number) => void
fetchNearby: (
latLon: LatLonObj,
radius?: number,
currentServiceWeek?: ServiceWeek
) => void
hideBackButton?: boolean
location: string
mobile?: boolean
Expand Down Expand Up @@ -102,6 +109,7 @@ function getNearbyCoordsFromUrlOrLocationOrMapCenter(

function NearbyView({
currentPosition,
currentServiceWeek,
defaultLatLon,
displayedCoords,
entityId,
Expand Down Expand Up @@ -175,10 +183,10 @@ function NearbyView({
firstItemRef.current?.scrollIntoView({ behavior: 'smooth' })
}
if (finalNearbyCoords) {
fetchNearby(finalNearbyCoords, radius)
fetchNearby(finalNearbyCoords, radius, currentServiceWeek)
setLoading(true)
const interval = setInterval(() => {
fetchNearby(finalNearbyCoords, radius)
fetchNearby(finalNearbyCoords, radius, currentServiceWeek)
setLoading(true)
}, AUTO_REFRESH_INTERVAL)
return function cleanup() {
Expand All @@ -204,6 +212,16 @@ function NearbyView({
finalNearbyCoords?.lat !== displayedCoords?.lat ||
finalNearbyCoords?.lon !== displayedCoords?.lon

// Build list of nearby routes for filtering within the stop card
const nearbyRoutes = Array.from(
new Set(
nearby
?.map((n: any) =>
n.place?.stopRoutes?.map((sr: { gtfsId?: string }) => sr?.gtfsId)
)
.flat(Infinity)
)
)
const nearbyItemList =
nearby?.map &&
nearby?.map((n: any) => (
Expand All @@ -223,7 +241,7 @@ function NearbyView({
/* eslint-disable-next-line jsx-a11y/no-noninteractive-tabindex */
tabIndex={0}
>
{getNearbyItem({ ...n.place, distance: n.distance })}
{getNearbyItem({ ...n.place, distance: n.distance, nearbyRoutes })}
</div>
</li>
))
Expand Down Expand Up @@ -290,15 +308,22 @@ function NearbyView({

const mapStateToProps = (state: AppReduxState) => {
const { config, location, transitIndex, ui } = state.otp
const { map } = state.otp.config
const { map, routeViewer } = config
const { nearbyViewCoords } = ui
const { nearby } = transitIndex
const { entityId } = state.router.location.query
const { currentPosition } = location
const defaultLatLon =
map?.initLat && map?.initLon ? { lat: map.initLat, lon: map.initLon } : null

const currentServiceWeek =
routeViewer?.onlyShowCurrentServiceWeek === true
? getCurrentServiceWeek()
: undefined

return {
currentPosition,
currentServiceWeek,
defaultLatLon,
displayedCoords: nearby?.coords,
entityId: entityId && decodeURIComponent(entityId),
Expand Down
11 changes: 9 additions & 2 deletions lib/components/viewers/nearby/stop.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import { Calendar } from '@styled-icons/fa-solid'
import { connect } from 'react-redux'
import { FormattedMessage } from 'react-intl'
import { TransitOperator } from '@opentripplanner/types'
import coreUtils from '@opentripplanner/core-utils'
import React from 'react'

Expand All @@ -25,7 +24,7 @@ type Props = {
homeTimezone: string
nearbyViewConfig?: NearbyViewConfig
routeSortComparator: (a: PatternStopTime, b: PatternStopTime) => number
stopData: StopData
stopData: StopData & { nearbyRoutes?: string[] }
}

const Stop = ({
Expand Down Expand Up @@ -70,6 +69,14 @@ const Stop = ({
const sortedStopTimes = st.stoptimes.sort(
(a: StopTime, b: StopTime) => fullTimestamp(a) - fullTimestamp(b)
)
if (
// NearbyRoutes if present is populated with a list of routes that appear
// in the current service period.
stopData.nearbyRoutes &&
!stopData.nearbyRoutes.includes(st?.pattern?.route?.gtfsId)
) {
return <></>
}
return (
<PatternRow
alwaysShowLongName={nearbyViewConfig?.alwaysShowLongName}
Expand Down
2 changes: 1 addition & 1 deletion lib/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ const otpConfig = require(YAML_CONFIG)
// eslint-disable-next-line no-undef
const jsConfig = require(JS_CONFIG).configure(otpConfig)

// Plug the plan query into the config (if available)
// If defined, plug custom plan query into the redux config, so it is available from actions.
otpConfig.api.planQuery = jsConfig.planQuery

const history = createHashHistory()
Expand Down
2 changes: 2 additions & 0 deletions lib/util/config-types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -360,6 +360,8 @@ export interface RouteViewerConfig {
hideRouteShapesWithinFlexZones?: boolean
/** Remove vehicles from the map if they haven't sent an update in a number of seconds */
maxRealtimeVehicleAge?: number
/** Use OTP date limiting to only show current service week in list */
onlyShowCurrentServiceWeek?: boolean
/** Disable vehicle highlight if necessary (e.g. custom or inverted icons) */
vehicleIconHighlight?: boolean
/** Customize vehicle icon padding (the default iconPadding is 2px in otp-ui) */
Expand Down
10 changes: 10 additions & 0 deletions lib/util/current-service-week.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { addDays, nextSunday, previousSunday } from 'date-fns'
/** Gets the current service week */
export const getCurrentServiceWeek = (): {
end: string
start: string
} => {
const start = previousSunday(new Date()).toISOString().split('T')[0]
const end = addDays(nextSunday(new Date()), 1).toISOString().split('T')[0]
return { end, start }
}
4 changes: 4 additions & 0 deletions lib/util/viewer.js
Original file line number Diff line number Diff line change
Expand Up @@ -355,6 +355,10 @@ export function getRouteColorBasedOnSettings(operator = {}, route = {}) {
return backgroundColor
}
}
export function getRouteTextColorBasedOnSettings(operator = {}, route = {}) {
const { color } = getColorAndNameFromRoute(operator, route)
return color
}

/**
* Helper method to determine if a stop being viewed is a flex stop. This is not marked by
Expand Down
Loading

0 comments on commit c741d54

Please sign in to comment.