-
Notifications
You must be signed in to change notification settings - Fork 55
/
Copy pathuser-settings.js
440 lines (412 loc) · 13 KB
/
user-settings.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
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
/* eslint-disable @typescript-eslint/no-use-before-define */
/* eslint-disable react/prop-types */
import { Button } from 'react-bootstrap'
import { connect } from 'react-redux'
import { differenceInSeconds } from 'date-fns'
import { FormattedMessage, injectIntl, useIntl } from 'react-intl'
import coreUtils from '@opentripplanner/core-utils'
import React, { Component, useCallback } from 'react'
import * as apiActions from '../../actions/api'
import * as formActions from '../../actions/form'
import * as uiActions from '../../actions/ui'
import * as userActions from '../../actions/user'
import {
getPlaceDetail,
getPlaceMainText,
isOtpMiddleware
} from '../../util/user'
import { StyledMainPanelPlace } from '../user/places/styled'
import Link from '../util/link'
import PlaceShortcut from '../user/places/place-shortcut'
import { summarizeQuery } from './user-settings-i18n'
import { UnpaddedList } from './styled'
const { toHoursMinutesSeconds } = coreUtils.time
/**
* Formats elapsed time from the specified timestamp to now,
* as in "5 hours ago" or the localized equivalent.
*/
function formatElapsedTime(timestamp, intl) {
const ellapsedSeconds = differenceInSeconds(new Date(), new Date(timestamp))
const { hours: allHours, minutes } = toHoursMinutesSeconds(ellapsedSeconds)
// TODO: add a day component to OTP-UI's toHoursMinutesSeconds?
const hours = allHours % 24
const days = (allHours - hours) / 24
// This text can be shown in a tooltip as well as within HTML tags, therefore
// it is obtained using formatMessage rather than <FormattedfMessage>.
let duration
if (days !== 0) {
duration = intl.formatMessage(
{ id: 'common.time.duration.nDays' },
{ days }
)
} else if (hours !== 0) {
duration = intl.formatMessage(
{ id: 'common.time.duration.nHours' },
{ hours }
)
} else if (minutes !== 0) {
duration = intl.formatMessage(
{ id: 'common.time.duration.nMinutes' },
{ minutes }
)
} else {
duration = intl.formatMessage({
id: 'common.time.duration.aFewSeconds'
})
}
return intl.formatMessage({ id: 'common.time.durationAgo' }, { duration })
}
/**
* Helper to ensure the home and work locations are correctly populated,
* or a placeholder is created.
*/
function addOrEditPlaceIfNeeded(locations, type, icon) {
const editedLocation = locations.find((loc) => loc.type === type)
if (editedLocation) {
// Define the address field, if not already set, so that the place appears as non-blank in the main pane
// (i.e. so that the address is shown instead of "Set your home/work location").
if (!editedLocation.address) editedLocation.address = editedLocation.name
} else {
locations.push({
address: '',
icon,
id: type,
type
})
}
}
class UserSettings extends Component {
_disableTracking = () => {
const { intl, localUser, toggleTracking } = this.props
const { recentPlaces, recentSearches, storeTripHistory } = localUser
if (!storeTripHistory) return
const hasRecents = recentPlaces?.length > 0 || recentSearches?.length > 0
// If user has recents and does not confirm deletion, return without doing
// anything.
if (
hasRecents &&
!window.confirm(
intl.formatMessage({ id: 'components.UserSettings.confirmDeletion' })
)
) {
return
}
// Disable tracking if we reach this statement.
toggleTracking(false)
}
_enableTracking = () =>
!this.props.localUser.storeTripHistory && this.props.toggleTracking(true)
_getLocalStorageOnlyContent = () => {
const {
deleteLocalUserRecentPlace,
forgetSearch,
forgetStop,
intl,
localUser,
setQueryParam,
setUrlSearch,
setViewedStop
} = this.props
const { favoriteStops, recentPlaces, recentSearches, storeTripHistory } =
localUser
return (
<>
{/* Favorite stops are shown regardless of tracking. */}
<Places
getDetailText={(location) => {
return intl.formatMessage(
{ id: 'components.UserSettings.stopId' },
{ stopId: location.id }
)
}}
getMainText={(location) => location.address}
header={
<FormattedMessage id="components.UserSettings.favoriteStops" />
}
onDelete={forgetStop}
onView={setViewedStop}
places={favoriteStops}
textIfEmpty={
<FormattedMessage id="components.UserSettings.noFavoriteStops" />
}
/>
{storeTripHistory && (
<Places
getDetailText={(location) => {
return formatElapsedTime(location.timestamp, intl)
}}
getMainText={(location) => location.address}
header={
<FormattedMessage id="components.UserSettings.recentPlaces" />
}
onDelete={deleteLocalUserRecentPlace}
places={recentPlaces}
/>
)}
{storeTripHistory && (
<RecentTrips
forgetSearch={forgetSearch}
setQueryParam={setQueryParam}
setUrlSearch={setUrlSearch}
tripRequests={recentSearches}
user={localUser}
/>
)}
<hr />
<div className="remember-settings">
<div className="section-header">
<FormattedMessage id="components.UserSettings.myPreferences" />
</div>
<small>
<FormattedMessage id="components.UserSettings.rememberSearches" />{' '}
</small>
<Button
bsSize="xsmall"
bsStyle="link"
className={storeTripHistory ? 'active' : ''}
onClick={this._enableTracking}
>
<FormattedMessage id="common.forms.yes" />
</Button>
<Button
bsSize="xsmall"
bsStyle="link"
className={!storeTripHistory ? 'active' : ''}
onClick={this._disableTracking}
>
<FormattedMessage id="common.forms.no" />
</Button>
</div>
<div>
<hr />
<div className="disclaimer">
<FormattedMessage id="components.UserSettings.storageDisclaimer" />
</div>
</div>
</>
)
}
_getLocations = (user) => {
const locations = [...user.savedLocations]
addOrEditPlaceIfNeeded(locations, 'home', 'home')
addOrEditPlaceIfNeeded(locations, 'work', 'briefcase')
return locations
}
_deleteUserPlace = (place) => {
const { deleteUserPlace, intl } = this.props
deleteUserPlace(place, intl)
}
render() {
const {
className = '',
forgetSearch,
intl,
isUsingOtpMiddleware,
localUser,
loggedInUser,
loggedInUserTripRequests,
setQueryParam,
style
} = this.props
const userNotLoggedIn = isUsingOtpMiddleware && !loggedInUser
if (userNotLoggedIn) return null
// Clone locations in order to prevent blank locations from seeping into the
// app state/store.
const locations = this._getLocations(
isUsingOtpMiddleware ? loggedInUser : localUser
)
const order = ['home', 'work', 'suggested', 'stop', 'recent']
const sortedLocations = isUsingOtpMiddleware
? locations
: locations.sort((a, b) => order.indexOf(a.type) - order.indexOf(b.type))
return (
<div className={`user-settings ${className}`} style={style}>
{/* Sorted locations are shown regardless of tracking. */}
<Places
getDetailText={(location) => getPlaceDetail(location, intl)}
getMainText={(location) => getPlaceMainText(location, intl)}
header={
isUsingOtpMiddleware && (
<FormattedMessage
id="components.UserSettings.mySavedPlaces"
values={{
manageLink: (linkText) => (
<span className="manage-link">
<Link to="/account/settings">{linkText}</Link>
</span>
)
}}
/>
)
}
onDelete={this._deleteUserPlace}
places={sortedLocations}
separator={false}
/>
{isUsingOtpMiddleware ? (
<RecentTrips
forgetSearch={forgetSearch}
setQueryParam={setQueryParam}
tripRequests={loggedInUserTripRequests}
user={loggedInUser}
/>
) : (
this._getLocalStorageOnlyContent()
)}
</div>
)
}
}
/**
* Displays a list of places with a header.
*/
const Places = ({
getDetailText,
getMainText,
header,
onDelete,
onView,
places,
separator = true,
textIfEmpty
}) => {
const shouldRender = textIfEmpty || (places && places.length > 0)
return (
shouldRender && (
<>
{separator && <hr />}
{header && <div className="section-header">{header}</div>}
<UnpaddedList>
{places.length > 0
? places.map((location, index) => {
// using the `return` syntax instead of `=>` to please both
// prettier and react/jsx rules, otherwise they conflict.
return (
<PlaceShortcut
detailText={getDetailText(location)}
icon={location.icon}
index={index}
key={location.id || index}
mainText={getMainText(location)}
onDelete={onDelete}
onView={onView}
place={location}
/>
)
})
: textIfEmpty && <small>{textIfEmpty}</small>}
</UnpaddedList>
</>
)
)
}
/**
* Wrapper for recent trip requests.
*/
const TripRequest = ({
forgetSearch,
setQueryParam,
setUrlSearch,
tripRequest,
user
}) => {
const { canDelete = true, query, timestamp } = tripRequest
const _onSelect = useCallback(
// Update query params and initiate search.
() => {
// In previous versions of this code, tripRequest.id was passed to setQueryParam,
// however that causes an extra entry to be added to the recent searches on click,
// in addition to the entry added when clicking the "Plan" (magnifying glass) button.
// Also, exclude the mode and date/time setting of the the selected search
// to not overwrite settings the user was using prior to this action.
const { date, departArrive, modes, time, ...queryWithoutModes } = query
setQueryParam(queryWithoutModes)
if (query.modeButtons) {
setUrlSearch({ modeButtons: query.modeButtons })
}
if (query.modeSettings) {
setUrlSearch({ modeSettings: query.modeSettings })
}
},
[setQueryParam, setUrlSearch, query]
)
const _onForget = useCallback(
() => forgetSearch(tripRequest),
[forgetSearch, tripRequest]
)
const intl = useIntl()
const mainText = summarizeQuery(query, intl, user.savedLocations).trim()
return (
<StyledMainPanelPlace
className="place-item"
detailText={formatElapsedTime(timestamp, intl)}
icon="clock-o"
mainText={mainText}
onClick={_onSelect}
onDelete={canDelete ? _onForget : null}
/>
)
}
/**
* Renders a list of recent trip requests, most recent first,
* if permitted by user.
*/
const RecentTrips = ({
forgetSearch,
setQueryParam,
setUrlSearch,
tripRequests = null,
user
}) =>
// Note: tripRequests can be undefined,
// so we have to coerce it to null above to make a valid render.
user.storeTripHistory &&
tripRequests &&
tripRequests.length > 0 && (
<div className="recent-searches-container">
<hr />
<div className="section-header">
<FormattedMessage id="components.UserSettings.recentSearches" />
</div>
<UnpaddedList>
{tripRequests
.sort((a, b) => b.timestamp - a.timestamp)
.map((tripReq) => (
<TripRequest
forgetSearch={forgetSearch}
key={tripReq.id}
setQueryParam={setQueryParam}
setUrlSearch={setUrlSearch}
tripRequest={tripReq}
user={user}
/>
))}
</UnpaddedList>
</div>
)
// connect to redux store
const mapStateToProps = (state) => {
const { config, currentQuery } = state.otp
const { localUser, loggedInUser, loggedInUserTripRequests } = state.user
return {
isUsingOtpMiddleware: isOtpMiddleware(config.persistence),
localUser,
loggedInUser,
loggedInUserTripRequests,
query: currentQuery
}
}
const mapDispatchToProps = {
deleteLocalUserRecentPlace: userActions.deleteLocalUserRecentPlace,
deleteUserPlace: userActions.deleteUserPlace,
forgetSearch: apiActions.forgetSearch,
forgetStop: userActions.forgetStop,
setQueryParam: formActions.setQueryParam,
setUrlSearch: apiActions.setUrlSearch,
setViewedStop: uiActions.setViewedStop,
toggleTracking: apiActions.toggleTracking
}
export default connect(
mapStateToProps,
mapDispatchToProps
)(injectIntl(UserSettings))