Skip to content

Commit

Permalink
Merge branch 'dev' into fix-zoom-itin-click
Browse files Browse the repository at this point in the history
  • Loading branch information
daniel-heppner-ibigroup authored Nov 7, 2024
2 parents 29cf298 + f2b0a69 commit 31fd2c6
Show file tree
Hide file tree
Showing 17 changed files with 2,717 additions and 4,944 deletions.
543 changes: 543 additions & 0 deletions __tests__/components/viewers/__snapshots__/nearby-view.js.snap

Large diffs are not rendered by default.

28 changes: 27 additions & 1 deletion craco.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,8 @@ module.exports = {
findBackwardsCompatibleEnvVar('JS_CONFIG')
backwardsCompatibleEnv.HTML_FILE =
findBackwardsCompatibleEnvVar('HTML_FILE')
backwardsCompatibleEnv.PLAN_QUERY_RESOURCE_URI =
findBackwardsCompatibleEnvVar('PLAN_QUERY_RESOURCE_URI')
backwardsCompatibleEnv.CUSTOM_CSS =
findBackwardsCompatibleEnvVar('CUSTOM_CSS')

Expand All @@ -65,6 +67,13 @@ module.exports = {
}
addBeforeLoader(webpackConfig, loaderByName('file-loader'), yamlLoader)

// Support import of raw GraphQL files
const graphqlLoader = {
loader: ['raw-loader'],
test: /\.graphql$/
}
addBeforeLoader(webpackConfig, loaderByName('file-loader'), graphqlLoader)

// Support webfonts (for font awesome)
const webfontLoader = {
loader: ['url-loader'],
Expand All @@ -82,7 +91,7 @@ module.exports = {
loader.exclude = /node_modules/
})

// Gather the CSS, HTML, YAML, and JS override files.
// Gather the CSS, HTML, YAML, GraphQL, and JS override files.
const CUSTOM_CSS =
(process.env && process.env.CUSTOM_CSS) ||
backwardsCompatibleEnv.CUSTOM_CSS ||
Expand All @@ -91,6 +100,22 @@ module.exports = {
(process.env && process.env.HTML_FILE) ||
backwardsCompatibleEnv.HTML_FILE ||
'lib/index.tpl.html'
// resolve the custom GraphQL file. If it is present, copy the file to a
// temporary folder within this project so that it can be bundled and loaded at runtime.
let customPlanGraphQLFile = './planQuery.graphql'
const PLAN_QUERY_RESOURCE_URI =
(process.env && process.env.PLAN_QUERY_RESOURCE_URI) ||
backwardsCompatibleEnv.PLAN_QUERY_RESOURCE_URI ||
'node_modules/@opentripplanner/core-utils/src/planQuery.graphql'
if (PLAN_QUERY_RESOURCE_URI) {
const splitPath = PLAN_QUERY_RESOURCE_URI.split(path.sep)
customPlanGraphQLFile = `../tmp/${splitPath[splitPath.length - 1]}`
// copy location is relative to root, while js file for app is relative to lib
fs.copySync(
PLAN_QUERY_RESOURCE_URI,
`./tmp/${splitPath[splitPath.length - 1]}`
)
}
const YAML_CONFIG =
(process.env && process.env.YAML_CONFIG) ||
backwardsCompatibleEnv.YAML_CONFIG ||
Expand Down Expand Up @@ -143,6 +168,7 @@ module.exports = {
new webpack.DefinePlugin({
CSS: JSON.stringify(CUSTOM_CSS),
JS_CONFIG: JSON.stringify(customJsFile),
PLAN_QUERY_RESOURCE: JSON.stringify(customPlanGraphQLFile),
// Optionally override the default config files with some other
// files.
YAML_CONFIG: JSON.stringify(YAML_CONFIG)
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
31 changes: 25 additions & 6 deletions lib/actions/apiV2.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import {
isValidSubsequence,
queryIsValid
} from '../util/state'
import { getCurrentServiceWeek } from '../util/current-service-week'
import {
getRouteColorBasedOnSettings,
getRouteIdForPattern,
Expand Down Expand Up @@ -380,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 @@ -437,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 @@ -475,7 +481,7 @@ export const fetchNearby = (position, radius) => {
}
}
}`,
{ lat, lon, radius },
{ currentServiceWeek, lat, lon, radius },
fetchNearbyResponse,
fetchNearbyError,
{
Expand Down Expand Up @@ -858,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 @@ -876,7 +890,7 @@ export function findRoutes() {
}
}
`,
{},
{ currentServiceWeek },
findRoutesResponse,
findRoutesError,
{
Expand Down Expand Up @@ -964,6 +978,8 @@ export function routingQuery(searchId = null, updateSearchInReducer) {
return function (dispatch, getState) {
const state = getState()
const { config, currentQuery, modeSettingDefinitions } = state.otp
const { planQuery } = config.api
const { loggedInUser } = state.user
const persistenceMode = getPersistenceMode(config.persistence)
const activeItinerary =
getActiveItinerary(state) ||
Expand Down Expand Up @@ -1047,6 +1063,9 @@ export function routingQuery(searchId = null, updateSearchInReducer) {
...currentQuery,
numItineraries: numItineraries || getDefaultNumItineraries(config)
}
if (config.mobilityProfile) {
baseQuery.mobilityProfile = loggedInUser?.mobilityProfile?.mobilityMode
}
// Generate combinations if the modes for query are not specified in the query
// FIXME: BICYCLE_RENT does not appear in this list unless TRANSIT is also enabled.
// This is likely due to the fact that BICYCLE_RENT is treated as a transit submode.
Expand All @@ -1070,7 +1089,7 @@ export function routingQuery(searchId = null, updateSearchInReducer) {
const query = generateOtp2Query(combo)
dispatch(
createGraphQLQueryAction(
query.query,
planQuery || query.query,
query.variables,
(response) => {
const dispatchedRoutingResponse = routingResponse(response)
Expand Down
20 changes: 19 additions & 1 deletion lib/actions/user.js
Original file line number Diff line number Diff line change
Expand Up @@ -270,7 +270,8 @@ function setUser(user, fetchTrips) {
return function (dispatch, getState) {
positionHomeAndWorkFirst(user)
// If mobility profile is enabled, set a default selection for "no mobility devices".
if (getState().otp.config.mobilityProfile) {
const hasMobilityProfile = !!getState().otp.config.mobilityProfile
if (hasMobilityProfile) {
setAtLeastNoMobilityDevice(user)
}
dispatch(setCurrentUser(user))
Expand All @@ -287,6 +288,23 @@ function setUser(user, fetchTrips) {
if (!isBlank(preferredLocale)) {
dispatch(setLocale(preferredLocale))
}

// Also replan itinerary search for the current user profile.
if (
hasMobilityProfile &&
!getState().router.location.pathname.startsWith('/account')
) {
// TODO: Refactor below.
// This prevents some kind of race condition whose origin I can't figure
// out. Unless this is called after redux catches up with routing to the '/'
// path, then the old path will be used and the screen won't change.
// Therefore, this timeout occurs so that the view of the homepage has time
// to render itself.
// FIXME: remove hack
setTimeout(() => {
dispatch(routingQuery())
}, 300)
}
}
}

Expand Down
27 changes: 8 additions & 19 deletions lib/components/user/mobility-profile/mobility-pane.tsx
Original file line number Diff line number Diff line change
@@ -1,24 +1,17 @@
import { Button } from 'react-bootstrap'
import { connect } from 'react-redux'
import { FormattedList, FormattedMessage } from 'react-intl'
import { FormikProps } from 'formik'
import React, { useCallback } from 'react'
import React from 'react'

import * as uiActions from '../../../actions/ui'
import { EditedUser } from '../types'
import { NONE_SINGLETON } from '../../../util/user'

interface Props extends FormikProps<EditedUser> {
routeTo: (url: string) => void
}
import Link from '../../util/link'

/**
* Renders a button to show the mobility profile settings.
*/
const MobilityPane = ({ routeTo, values: userData }: Props): JSX.Element => {
const handleClick = useCallback(() => {
routeTo('/account/mobilityProfile/')
}, [routeTo])
const MobilityPane = ({
values: userData
}: FormikProps<EditedUser>): JSX.Element => {
const {
isMobilityLimited,
mobilityDevices = [],
Expand Down Expand Up @@ -54,15 +47,11 @@ const MobilityPane = ({ routeTo, values: userData }: Props): JSX.Element => {
id={`components.MobilityProfile.LimitationsPane.visionLimitations.${visionLimitation}`}
/>
</p>
<Button bsStyle="primary" onClick={handleClick}>
<Link className="btn btn-primary" to="/account/mobilityProfile/">
<FormattedMessage id="components.MobilityProfile.MobilityPane.button" />
</Button>
</Link>
</div>
)
}

const mapDispatchToProps = {
routeTo: uiActions.routeTo
}

export default connect(null, mapDispatchToProps)(MobilityPane)
export default MobilityPane
1 change: 1 addition & 0 deletions lib/components/user/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ export type VisionLimitation = typeof visionLimitations[number]
export interface MobilityProfile {
isMobilityLimited: boolean
mobilityDevices: string[]
mobilityMode: string
visionLimitation: VisionLimitation
}

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
Loading

0 comments on commit 31fd2c6

Please sign in to comment.