-
Notifications
You must be signed in to change notification settings - Fork 53
/
Copy pathresponsive-webapp.js
398 lines (370 loc) · 14 KB
/
responsive-webapp.js
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
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
import { Auth0Provider } from '@auth0/auth0-react'
import { ConnectedRouter } from 'connected-react-router'
import { createHashHistory } from 'history'
import isEqual from 'lodash.isequal'
import coreUtils from '@opentripplanner/core-utils'
import PropTypes from 'prop-types'
import qs from 'qs'
import React, { Component } from 'react'
import { Col, Grid, Row } from 'react-bootstrap'
import { connect } from 'react-redux'
import { Route, Switch, withRouter } from 'react-router'
import * as authActions from '../../actions/auth'
import * as callTakerActions from '../../actions/call-taker'
import * as configActions from '../../actions/config'
import * as formActions from '../../actions/form'
import * as locationActions from '../../actions/location'
import * as mapActions from '../../actions/map'
import * as uiActions from '../../actions/ui'
import PrintFieldTripLayout from '../admin/print-field-trip-layout'
import { frame } from '../app/app-frame'
import { RedirectWithQuery } from '../form/connected-links'
import Map from '../map/map'
import MobileMain from '../mobile/main'
import { getAuth0Config } from '../../util/auth'
import {
ACCOUNT_PATH,
AUTH0_AUDIENCE,
AUTH0_SCOPE,
ACCOUNT_SETTINGS_PATH,
CREATE_ACCOUNT_PATH,
CREATE_ACCOUNT_PLACES_PATH,
CREATE_ACCOUNT_VERIFY_PATH,
PLACES_PATH,
TERMS_OF_SERVICE_PATH,
TERMS_OF_STORAGE_PATH,
TRIPS_PATH,
URL_ROOT
} from '../../util/constants'
import { ComponentContext } from '../../util/contexts'
import { getActiveItinerary, getTitle } from '../../util/state'
import AfterSignInScreen from '../user/after-signin-screen'
import BeforeSignInScreen from '../user/before-signin-screen'
import FavoritePlaceScreen from '../user/places/favorite-place-screen'
import SavedTripList from '../user/monitored-trip/saved-trip-list'
import SavedTripScreen from '../user/monitored-trip/saved-trip-screen'
import UserAccountScreen from '../user/user-account-screen'
import withLoggedInUserSupport from '../user/with-logged-in-user-support'
import PrintLayout from './print-layout'
import DesktopNav from './desktop-nav'
const { isMobile } = coreUtils.ui
class ResponsiveWebapp extends Component {
static propTypes = {
initZoomOnLocate: PropTypes.number,
query: PropTypes.object
}
static contextType = ComponentContext
/** Lifecycle methods **/
componentDidUpdate (prevProps) {
const { currentPosition, location, query, title } = this.props
document.title = title
const urlParams = coreUtils.query.getUrlParams()
const newSearchId = urlParams.ui_activeSearch
// Determine if trip is being replanned by checking the active search ID
// against the ID found in the URL params. If they are different, a new one
// has been routed to (see handleBackButtonPress) and there is no need to
// trigger a form change because necessarily the query will be different
// from the previous query.
const replanningTrip = newSearchId && this.props.activeSearchId && newSearchId !== this.props.activeSearchId
if (!isEqual(prevProps.query, query) && !replanningTrip) {
// Trigger on form change action if previous query is different from
// current one AND trip is not being replanned already. This will
// determine whether a search needs to be made, the mobile view needs
// updating, etc.
this.props.formChanged(prevProps.query, query)
}
// check if device position changed (typically only set once, on initial page load)
if (currentPosition !== prevProps.currentPosition) {
if (currentPosition.error || !currentPosition.coords) return
const pt = {
lat: currentPosition.coords.latitude,
lon: currentPosition.coords.longitude
}
// if in mobile mode and from field is not set, use current location as from and recenter map
if (isMobile() && this.props.query.from === null) {
this.props.setLocationToCurrent({ locationType: 'from' })
this.props.setMapCenter(pt)
if (this.props.initZoomOnLocate) {
this.props.setMapZoom({ zoom: this.props.initZoomOnLocate })
}
}
}
// If the path changes (e.g., via a back button press) check whether the
// main content needs to switch between, for example, a viewer and a search.
if (!isEqual(location.pathname, prevProps.location.pathname)) {
// console.log('url changed to', location.pathname)
this.props.matchContentToUrl(location)
}
// Check for change between ITINERARY and PROFILE routingTypes
// TODO: restore this for profile mode
/* if (query.routingType !== nextProps.query.routingType) {
let queryModes = nextProps.query.mode.split(',')
// If we are entering 'ITINERARY' mode, ensure that one and only one access mode is selected
if (nextProps.query.routingType === 'ITINERARY') {
queryModes = ensureSingleAccessMode(queryModes)
this.props.setQueryParam({ mode: queryModes.join(',') })
}
// If we are entering 'PROFILE' mode, ensure that CAR_HAIL is not selected
// TODO: make this more generic, i.e. introduce concept of mode->routingType permissions
if (nextProps.query.routingType === 'ITINERARY') {
queryModes = queryModes.filter(mode => mode !== 'CAR_HAIL')
this.props.setQueryParam({ mode: queryModes.join(',') })
}
} */
}
componentDidMount () {
const {
getCurrentPosition,
handleBackButtonPress,
initializeModules,
location,
matchContentToUrl,
parseUrlQueryString,
receivedPositionResponse,
title
} = this.props
// Add on back button press behavior.
window.addEventListener('popstate', handleBackButtonPress)
document.title = title
// If a URL is detected without hash routing (e.g., http://localhost:9966?sessionId=test),
// window.location.search will have a value. In this case, we need to redirect to the URL root with the
// search reconstructed for use with the hash router.
// Exception: Do not redirect after auth0 login, which sets the URL in the form
// http://localhost:9966/?code=xxxxxxx&state=yyyyyyyyy that we want to preserve.
const search = window.location.search
if (search) {
const searchParams = qs.parse(search, { ignoreQueryPrefix: true })
if (!(searchParams.code && searchParams.state)) {
window.location.href = `${URL_ROOT}/#/${search}`
return
}
}
if (isMobile()) {
// If on mobile browser, check position on load
getCurrentPosition()
// Also, watch for changes in position on mobile
navigator.geolocation.watchPosition(
// On success
position => { receivedPositionResponse({ position }) },
// On error
error => { console.log('error in watchPosition', error) },
// Options
{ enableHighAccuracy: true }
)
}
// Handle routing to a specific part of the app (e.g. stop viewer) on page
// load. (This happens prior to routing request in case special routerId is
// set from URL.)
matchContentToUrl(location)
if (location && location.search) {
// Set search params and plan trip if routing enabled and a query exists
// in the URL.
parseUrlQueryString()
}
// Initialize call taker/field trip modules (check for valid auth session).
initializeModules()
}
componentWillUnmount () {
// Remove on back button press listener.
window.removeEventListener('popstate', this.props.handleBackButtonPress)
}
renderDesktopView = () => {
const { MainControls, MainPanel, MapWindows } = this.context
return (
<div className='otp'>
<DesktopNav />
<Grid>
<Row className='main-row'>
<Col sm={6} md={4} className='sidebar'>
{/*
Note: the main tag provides a way for users of screen readers
to skip to the primary page content.
TODO: Find a better place.
*/}
<main>
{<MainPanel />}
</main>
</Col>
{MainControls && <MainControls />}
<Col sm={6} md={8} className='map-container'>
{MapWindows && <MapWindows />}
<Map />
</Col>
</Row>
</Grid>
</div>
)
}
renderMobileView = () => {
return (
// <main> Needed for accessibility checks. TODO: Find a better place.
<main>
<MobileMain />
</main>
)
}
render () {
return isMobile() ? this.renderMobileView() : this.renderDesktopView()
}
}
// connect to the redux store
const mapStateToProps = (state, ownProps) => {
const title = getTitle(state)
return {
activeItinerary: getActiveItinerary(state),
activeSearchId: state.otp.activeSearchId,
currentPosition: state.otp.location.currentPosition,
initZoomOnLocate: state.otp.config.map && state.otp.config.map.initZoomOnLocate,
mobileScreen: state.otp.ui.mobileScreen,
modeGroups: state.otp.config.modeGroups,
query: state.otp.currentQuery,
searches: state.otp.searches,
title
}
}
const mapDispatchToProps = {
formChanged: formActions.formChanged,
getCurrentPosition: locationActions.getCurrentPosition,
handleBackButtonPress: uiActions.handleBackButtonPress,
initializeModules: callTakerActions.initializeModules,
matchContentToUrl: uiActions.matchContentToUrl,
parseUrlQueryString: formActions.parseUrlQueryString,
receivedPositionResponse: locationActions.receivedPositionResponse,
setLocationToCurrent: mapActions.setLocationToCurrent,
setMapCenter: configActions.setMapCenter,
setMapZoom: configActions.setMapZoom
}
const history = createHashHistory()
const WebappWithRouter = withRouter(
withLoggedInUserSupport(
connect(mapStateToProps, mapDispatchToProps)(ResponsiveWebapp)
)
)
/**
* The routing component for the application.
* This is the top-most "standard" component,
* and we initialize the Auth0Provider here
* so that Auth0 services are available everywhere.
*/
class RouterWrapperWithAuth0 extends Component {
render () {
const {
auth0Config,
components,
processSignIn,
routerConfig,
showAccessTokenError,
showLoginError
} = this.props
const router = (
<ComponentContext.Provider value={components}>
<ConnectedRouter
basename={routerConfig && routerConfig.basename}
history={history}>
<Switch>
<Route
exact
path={[
// App root
'/',
// Load app with preset lat/lon/zoom and optional router
// NOTE: All params will be cast to :id in matchContentToUrl due
// to a quirk with react-router.
// https://github.com/ReactTraining/react-router/issues/5870#issuecomment-394194338
'/@/:latLonZoomRouter',
'/start/:latLonZoomRouter',
// Route viewer (and route ID).
'/route',
'/route/:id',
// Stop viewer (and stop ID).
'/stop',
'/stop/:id'
]}
render={() => <WebappWithRouter {...this.props} />}
/>
<Route
component={FavoritePlaceScreen}
path={[`${CREATE_ACCOUNT_PLACES_PATH}/:id`, `${PLACES_PATH}/:id`]}
/>
<Route
component={SavedTripScreen}
path={`${TRIPS_PATH}/:id`}
/>
<Route exact path={ACCOUNT_PATH}>
<RedirectWithQuery to={TRIPS_PATH} />
</Route>
<Route exact path={CREATE_ACCOUNT_PATH}>
<RedirectWithQuery to={CREATE_ACCOUNT_VERIFY_PATH} />
</Route>
<Route
// This route lets new or existing users edit or set up their account.
component={UserAccountScreen}
path={[`${CREATE_ACCOUNT_PATH}/:step`, ACCOUNT_SETTINGS_PATH]}
/>
<Route
component={frame(components.TermsOfService)}
path={TERMS_OF_SERVICE_PATH}
/>
<Route
component={frame(components.TermsOfStorage)}
path={TERMS_OF_STORAGE_PATH}
/>
<Route
component={SavedTripList}
path={TRIPS_PATH}
/>
<Route
// This route is called immediately after login by Auth0
// and by the onRedirectCallback function from /lib/util/auth.js.
// For new users, it displays the account setup form.
// For existing users, it takes the browser back to the itinerary search prior to login.
component={AfterSignInScreen}
path='/signedin'
/>
<Route
component={PrintLayout}
path='/print'
/>
<Route
component={PrintFieldTripLayout}
path='/printFieldTrip'
/>
{/* For any other route, simply return the web app. */}
<Route
render={() => <WebappWithRouter {...this.props} />}
/>
</Switch>
</ConnectedRouter>
</ComponentContext.Provider>
)
return (
auth0Config
? (
<Auth0Provider
audience={AUTH0_AUDIENCE}
clientId={auth0Config.clientId}
domain={auth0Config.domain}
onAccessTokenError={showAccessTokenError}
onLoginError={showLoginError}
onRedirectCallback={processSignIn}
onRedirecting={BeforeSignInScreen}
redirectUri={URL_ROOT}
scope={AUTH0_SCOPE}
>
{router}
</Auth0Provider>
)
: router
)
}
}
const mapStateToWrapperProps = (state, ownProps) => ({
auth0Config: getAuth0Config(state.otp.config.persistence),
routerConfig: state.otp.config.reactRouter
})
const mapWrapperDispatchToProps = {
processSignIn: authActions.processSignIn,
showAccessTokenError: authActions.showAccessTokenError,
showLoginError: authActions.showLoginError
}
export default connect(mapStateToWrapperProps, mapWrapperDispatchToProps)(RouterWrapperWithAuth0)