@opentripplanner/trip-details 1.3.2 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/index.tsx ADDED
@@ -0,0 +1,402 @@
1
+ import flatten from "flat";
2
+ // @ts-expect-error FIXME: Create TypeScript types for core-utils packages.
3
+ import coreUtils from "@opentripplanner/core-utils";
4
+ import { FlexBookingInfo } from "@opentripplanner/types";
5
+ import React, { ReactElement } from "react";
6
+ import { FormattedMessage, FormattedNumber } from "react-intl";
7
+ import { CalendarAlt } from "@styled-icons/fa-solid/CalendarAlt";
8
+ import { HandPaper } from "@styled-icons/fa-solid/HandPaper";
9
+ import { Heartbeat } from "@styled-icons/fa-solid/Heartbeat";
10
+ import { MoneyBillAlt } from "@styled-icons/fa-solid/MoneyBillAlt";
11
+ import { PhoneVolume } from "@styled-icons/fa-solid/PhoneVolume";
12
+ import { Route } from "@styled-icons/fa-solid/Route";
13
+
14
+ import * as S from "./styled";
15
+ import TripDetail from "./trip-detail";
16
+
17
+ import {
18
+ CaloriesDetailsProps,
19
+ TransitFareProps,
20
+ TripDetailsProps
21
+ } from "./types";
22
+
23
+ // Load the default messages.
24
+ import defaultEnglishMessages from "../i18n/en-US.yml";
25
+
26
+ // HACK: We should flatten the messages loaded above because
27
+ // the YAML loaders behave differently between webpack and our version of jest:
28
+ // - the yaml loader for webpack returns a nested object,
29
+ // - the yaml loader for jest returns messages with flattened ids.
30
+ const defaultMessages: Record<string, string> = flatten(defaultEnglishMessages);
31
+
32
+ /**
33
+ * Format text bold (used with FormattedMessage).
34
+ */
35
+ // TODO: Find a better place for this utility.
36
+ function boldText(contents: ReactElement): ReactElement {
37
+ return <strong>{contents}</strong>;
38
+ }
39
+
40
+ /**
41
+ * Render formatted fare.
42
+ * @param currencyCode The ISO currency code to use (USD, GBP, EUR).
43
+ * @param fare The fare value, in currency units, to be shown.
44
+ * @returns The formatted fare value according to the selected locale.
45
+ */
46
+ function renderFare(currencyCode: string, fare: number): ReactElement {
47
+ return (
48
+ <FormattedNumber
49
+ currency={currencyCode}
50
+ // For dollars in locales such as 'fr',
51
+ // this will limit the display to just the dollar sign
52
+ // (otherwise it will render e.g. '2,50 $US' instead of '2,50 $').
53
+ currencyDisplay="narrowSymbol"
54
+ value={fare}
55
+ // eslint-disable-next-line react/style-prop-object
56
+ style="currency"
57
+ />
58
+ );
59
+ }
60
+
61
+ /**
62
+ * Helper function to specify the link to dietary table.
63
+ */
64
+ function dietaryLink(contents: ReactElement): ReactElement {
65
+ return (
66
+ <a
67
+ href="https://health.gov/dietaryguidelines/dga2005/document/html/chapter3.htm#table4"
68
+ rel="noopener noreferrer"
69
+ target="_blank"
70
+ >
71
+ {contents}
72
+ </a>
73
+ );
74
+ }
75
+
76
+ /**
77
+ * Helper function that assembles values for flex pickup/dropoff messages.
78
+ */
79
+ function getFlexMessageValues(info: FlexBookingInfo) {
80
+ return {
81
+ hasLeadTime: coreUtils.itinerary.isAdvanceBookingRequired(info),
82
+ hasPhone: !!info?.contactInfo?.phoneNumber,
83
+ leadDays: info.latestBookingTime.daysPrior,
84
+ phoneNumber: info?.contactInfo?.phoneNumber
85
+ };
86
+ }
87
+
88
+ /**
89
+ * Default rendering if no component is provided for the CaloriesDetails
90
+ * slot in the TripDetails component.
91
+ */
92
+ function DefaultCaloriesDetails({
93
+ bikeSeconds,
94
+ calories,
95
+ walkSeconds
96
+ }: CaloriesDetailsProps): ReactElement {
97
+ return (
98
+ <FormattedMessage
99
+ defaultMessage={defaultMessages["otpUi.TripDetails.caloriesDescription"]}
100
+ description="Text describing how the calories relate to the walking and biking duration of a trip."
101
+ id="otpUi.TripDetails.caloriesDescription"
102
+ values={{
103
+ bikeMinutes: Math.round(bikeSeconds / 60),
104
+ calories: Math.round(calories),
105
+ dietaryLink,
106
+ strong: boldText,
107
+ walkMinutes: Math.round(walkSeconds / 60)
108
+ }}
109
+ />
110
+ );
111
+ }
112
+
113
+ /**
114
+ * Helper component that renders a transit fare entry.
115
+ */
116
+ const TransitFare = ({
117
+ fareKey,
118
+ fareNameFallback,
119
+ fareKeyNameMap,
120
+ transitFares
121
+ }: TransitFareProps): ReactElement => {
122
+ const currentFare = transitFares[fareKey];
123
+
124
+ return (
125
+ <span>
126
+ <FormattedMessage
127
+ defaultMessage={defaultMessages["otpUi.TripDetails.transitFareEntry"]}
128
+ description="Text showing the price of tickets on public transportation."
129
+ id="otpUi.TripDetails.transitFareEntry"
130
+ values={{
131
+ name: fareKeyNameMap[fareKey] || fareNameFallback || fareKey,
132
+ strong: boldText,
133
+ value: renderFare(
134
+ currentFare.currencyCode,
135
+ currentFare.transitFare / 100
136
+ )
137
+ }}
138
+ />
139
+ </span>
140
+ );
141
+ };
142
+
143
+ /**
144
+ * Renders trip details such as departure instructions, fare amount, and calories spent.
145
+ */
146
+ export function TripDetails({
147
+ CaloriesDetails = DefaultCaloriesDetails,
148
+ className = "",
149
+ DepartureDetails = null,
150
+ defaultFareKey = "regular",
151
+ FareDetails = null,
152
+ fareKeyNameMap = {},
153
+ itinerary
154
+ }: TripDetailsProps): ReactElement {
155
+ // process the transit fare
156
+ const fareResult = coreUtils.itinerary.calculateFares(itinerary, true);
157
+ const { maxTNCFare, minTNCFare, tncCurrencyCode, transitFares } = fareResult;
158
+
159
+ let defaultFare = defaultFareKey;
160
+ if (!transitFares[defaultFareKey]) {
161
+ defaultFare = "regular";
162
+ }
163
+
164
+ let companies = "";
165
+ itinerary.legs.forEach(leg => {
166
+ if (leg.tncData) {
167
+ companies = leg.tncData.company;
168
+ }
169
+ });
170
+ let fare;
171
+
172
+ const fareKeys = transitFares && Object.keys(transitFares).sort();
173
+
174
+ if (transitFares && fareKeys.length > 0) {
175
+ // Depending on if there are additional fares to display either render a <span> or a <details>
176
+ const TransitFareWrapper =
177
+ transitFares && fareKeys.length > 1 ? S.TransitFare : S.TransitFareSingle;
178
+
179
+ fare = (
180
+ <S.Fare>
181
+ <TransitFareWrapper>
182
+ <summary style={{ display: fareKeys.length > 1 ? "list-item" : "" }}>
183
+ <TransitFare
184
+ fareNameFallback={
185
+ <FormattedMessage
186
+ defaultMessage={
187
+ defaultMessages["otpUi.TripDetails.transitFare"]
188
+ }
189
+ description="Text showing the price of tickets on public transportation."
190
+ id="otpUi.TripDetails.transitFare"
191
+ />
192
+ }
193
+ fareKey={defaultFare}
194
+ fareKeyNameMap={fareKeyNameMap}
195
+ transitFares={transitFares}
196
+ />
197
+ </summary>
198
+ {fareKeys.map(fareKey => {
199
+ // Don't show the default fare twice!
200
+ if (fareKey === defaultFare) {
201
+ return null;
202
+ }
203
+ return (
204
+ <TransitFare
205
+ fareKey={fareKey}
206
+ key={fareKey}
207
+ fareKeyNameMap={fareKeyNameMap}
208
+ transitFares={transitFares}
209
+ />
210
+ );
211
+ })}
212
+ </TransitFareWrapper>
213
+ {minTNCFare !== 0 && (
214
+ <S.TNCFare>
215
+ <br />
216
+ <FormattedMessage
217
+ defaultMessage={defaultMessages["otpUi.TripDetails.tncFare"]}
218
+ description="Text showing the price paid to transportation network companies."
219
+ id="otpUi.TripDetails.tncFare"
220
+ values={{
221
+ companies: (
222
+ // S.TNCFareCompanies capitalizes the TNC company ID (e.g. "COMPANY")
223
+ // after it is converted to lowercase, so it renders as "Company".
224
+ <S.TNCFareCompanies>
225
+ {companies.toLowerCase()}
226
+ </S.TNCFareCompanies>
227
+ ),
228
+ maxTNCFare: renderFare(tncCurrencyCode, maxTNCFare),
229
+ minTNCFare: renderFare(tncCurrencyCode, minTNCFare),
230
+ strong: boldText
231
+ }}
232
+ />
233
+ </S.TNCFare>
234
+ )}
235
+ </S.Fare>
236
+ );
237
+ }
238
+
239
+ const departureDate = new Date(itinerary.startTime);
240
+
241
+ // Compute calories burned.
242
+ const {
243
+ bikeDuration,
244
+ caloriesBurned,
245
+ walkDuration
246
+ } = coreUtils.itinerary.calculatePhysicalActivity(itinerary);
247
+
248
+ // Parse flex info and generate appropriate strings
249
+ const containsFlex = itinerary.legs.some(coreUtils.itinerary.isFlex);
250
+ const pickupBookingInfo = itinerary.legs
251
+ .map(leg => leg.pickupBookingInfo)
252
+ .filter(info => !!info);
253
+ const dropOffBookingInfo = itinerary.legs
254
+ .map(leg => leg.dropOffBookingInfo)
255
+ .filter(info => !!info);
256
+
257
+ return (
258
+ <S.TripDetails className={className}>
259
+ <S.TripDetailsHeader>
260
+ <FormattedMessage
261
+ defaultMessage={defaultMessages["otpUi.TripDetails.title"]}
262
+ description="Title (heading) text of the component."
263
+ id="otpUi.TripDetails.title"
264
+ />
265
+ </S.TripDetailsHeader>
266
+ <S.TripDetailsBody>
267
+ <TripDetail
268
+ // Any custom description for the Departure message needs to be handled by the slot.
269
+ description={
270
+ DepartureDetails && (
271
+ <DepartureDetails departureDate={departureDate} />
272
+ )
273
+ }
274
+ icon={<CalendarAlt size={17} />}
275
+ summary={
276
+ <S.Timing>
277
+ <FormattedMessage
278
+ defaultMessage={defaultMessages["otpUi.TripDetails.departure"]}
279
+ description="Text showing the departure date/time for a trip."
280
+ id="otpUi.TripDetails.departure"
281
+ values={{
282
+ departureDate,
283
+ strong: boldText
284
+ }}
285
+ />
286
+ </S.Timing>
287
+ }
288
+ />
289
+ {fare && (
290
+ <TripDetail
291
+ // Any custom description for the transit fare needs to be handled by the slot.
292
+ description={
293
+ FareDetails && (
294
+ <FareDetails
295
+ maxTNCFare={maxTNCFare}
296
+ minTNCFare={minTNCFare}
297
+ transitFares={transitFares}
298
+ />
299
+ )
300
+ }
301
+ icon={<MoneyBillAlt size={17} />}
302
+ summary={fare}
303
+ />
304
+ )}
305
+ {caloriesBurned > 0 && (
306
+ <TripDetail
307
+ icon={<Heartbeat size={17} />}
308
+ summary={
309
+ <S.CaloriesSummary>
310
+ <FormattedMessage
311
+ defaultMessage={defaultMessages["otpUi.TripDetails.calories"]}
312
+ description="Text showing the number of calories for the walking and biking legs of a trip."
313
+ id="otpUi.TripDetails.calories"
314
+ values={{
315
+ calories: caloriesBurned,
316
+ strong: boldText
317
+ }}
318
+ />
319
+ </S.CaloriesSummary>
320
+ }
321
+ description={
322
+ CaloriesDetails && (
323
+ <CaloriesDetails
324
+ bikeSeconds={bikeDuration}
325
+ calories={caloriesBurned}
326
+ walkSeconds={walkDuration}
327
+ />
328
+ )
329
+ }
330
+ />
331
+ )}
332
+ {containsFlex && (
333
+ <TripDetail
334
+ summary={
335
+ <S.FlexSummary>
336
+ <FormattedMessage
337
+ defaultMessage={
338
+ defaultMessages["otpUi.TripDetails.tripIncludesFlex"]
339
+ }
340
+ description="Text stating that portions of the trip include a flex (on-demand) transit service."
341
+ id="otpUi.TripDetails.tripIncludesFlex"
342
+ />
343
+ </S.FlexSummary>
344
+ }
345
+ icon={<Route size={17} />}
346
+ />
347
+ )}
348
+ {pickupBookingInfo &&
349
+ pickupBookingInfo.map(info => (
350
+ <TripDetail
351
+ key={info.pickupMessage}
352
+ icon={<PhoneVolume size={17} />}
353
+ summary={
354
+ <S.FlexPickupSummary>
355
+ <FormattedMessage
356
+ defaultMessage={
357
+ defaultMessages["otpUi.TripDetails.flexPickupMessage"]
358
+ }
359
+ description="Instructions for booking and boarding the flex (on-demand) transit service."
360
+ id="otpUi.TripDetails.flexPickupMessage"
361
+ values={getFlexMessageValues(info)}
362
+ />
363
+ </S.FlexPickupSummary>
364
+ }
365
+ description={info.pickupMessage}
366
+ />
367
+ ))}
368
+ {dropOffBookingInfo &&
369
+ dropOffBookingInfo.map(info => (
370
+ <TripDetail
371
+ description={info.dropOffMessage}
372
+ icon={
373
+ coreUtils.itinerary.isAdvanceBookingRequired(info) ? (
374
+ <PhoneVolume size={17} />
375
+ ) : (
376
+ <HandPaper size={17} />
377
+ )
378
+ }
379
+ key={info.dropOffMessage}
380
+ summary={
381
+ <S.FlexDropOffSummary>
382
+ <FormattedMessage
383
+ defaultMessage={
384
+ defaultMessages["otpUi.TripDetails.flexDropOffMessage"]
385
+ }
386
+ description="Instructions for getting off the flex (on-demand) transit service."
387
+ id="otpUi.TripDetails.flexDropOffMessage"
388
+ values={getFlexMessageValues(info)}
389
+ />
390
+ </S.FlexDropOffSummary>
391
+ }
392
+ />
393
+ ))}
394
+ </S.TripDetailsBody>
395
+ </S.TripDetails>
396
+ );
397
+ }
398
+
399
+ export default TripDetails;
400
+
401
+ // Rename styled components for export
402
+ export { S as Styled };
@@ -44,7 +44,23 @@ export const TNCFareCompanies = styled.span`
44
44
 
45
45
  export const Timing = styled.span``;
46
46
 
47
- export const TransitFare = styled.span``;
47
+ export const TransitFare = styled.details`
48
+ display: inline-block;
49
+
50
+ > span {
51
+ display: block;
52
+ /* This may seem wrong, but this value gives the most aligned results */
53
+ /* see: https://github.com/opentripplanner/otp-ui/pull/294#discussion_r742045851 */
54
+ padding-left: 1.75ch;
55
+ }
56
+ `;
57
+ export const TransitFareSingle = styled.span``;
58
+
59
+ export const FlexSummary = styled.span``;
60
+
61
+ export const FlexPickupSummary = styled.span``;
62
+
63
+ export const FlexDropOffSummary = styled.span``;
48
64
 
49
65
  export const TripDetail = styled.div`
50
66
  margin-top: 6px;
@@ -81,4 +97,6 @@ export const TripDetailsHeader = styled.div`
81
97
  export const TripDetailSummary = styled.div`
82
98
  margin-left: 28px;
83
99
  padding-top: 2px;
100
+ display: flex;
101
+ align-items: baseline;
84
102
  `;
@@ -0,0 +1,70 @@
1
+ import React, { Component, ReactElement } from "react";
2
+ import { QuestionCircle } from "@styled-icons/fa-solid/QuestionCircle";
3
+ import { TimesCircle } from "@styled-icons/fa-solid/TimesCircle";
4
+ import { VelocityTransitionGroup } from "velocity-react";
5
+
6
+ import * as S from "./styled";
7
+
8
+ type Props = {
9
+ description?: ReactElement | string;
10
+ icon: ReactElement;
11
+ summary: ReactElement | string;
12
+ };
13
+
14
+ type State = {
15
+ expanded: boolean;
16
+ };
17
+
18
+ export default class TripDetail extends Component<Props, State> {
19
+ constructor(props: Props) {
20
+ super(props);
21
+ this.state = {
22
+ expanded: false
23
+ };
24
+ }
25
+
26
+ toggle = (): void => {
27
+ const { expanded } = this.state;
28
+ if (expanded) this.onHideClick();
29
+ else this.onExpandClick();
30
+ };
31
+
32
+ onExpandClick = (): void => {
33
+ this.setState({ expanded: true });
34
+ };
35
+
36
+ onHideClick = (): void => {
37
+ this.setState({ expanded: false });
38
+ };
39
+
40
+ render(): ReactElement {
41
+ const { icon, summary, description } = this.props;
42
+ const { expanded } = this.state;
43
+ return (
44
+ <S.TripDetail>
45
+ <S.TripDetailIcon>{icon}</S.TripDetailIcon>
46
+ <S.TripDetailSummary>
47
+ {summary}
48
+ {description && (
49
+ <S.ExpandButton onClick={this.toggle}>
50
+ <QuestionCircle size="0.92em" />
51
+ </S.ExpandButton>
52
+ )}
53
+ </S.TripDetailSummary>
54
+ <VelocityTransitionGroup
55
+ enter={{ animation: "slideDown" }}
56
+ leave={{ animation: "slideUp" }}
57
+ >
58
+ {expanded && (
59
+ <S.TripDetailDescription>
60
+ <S.HideButton onClick={this.onHideClick}>
61
+ <TimesCircle size="0.92em" />
62
+ </S.HideButton>
63
+ {description}
64
+ </S.TripDetailDescription>
65
+ )}
66
+ </VelocityTransitionGroup>
67
+ </S.TripDetail>
68
+ );
69
+ }
70
+ }
package/src/types.ts ADDED
@@ -0,0 +1,69 @@
1
+ // Prettier does not recognize the import type syntax.
2
+ // eslint-disable-next-line prettier/prettier
3
+ import type { Itinerary } from "@opentripplanner/types";
4
+ import type { ReactElement } from "react";
5
+
6
+ export interface CaloriesDetailsProps {
7
+ bikeSeconds: number;
8
+ calories: number;
9
+ walkSeconds: number;
10
+ }
11
+
12
+ export interface DepartureDetailsProps {
13
+ departureDate: Date;
14
+ }
15
+
16
+ export interface TransitFareData {
17
+ [key: string]: {
18
+ currencyCode: string;
19
+ transitFare: number;
20
+ }
21
+ }
22
+
23
+ export interface FareDetailsProps {
24
+ maxTNCFare: number;
25
+ minTNCFare: number;
26
+ transitFares: TransitFareData;
27
+ }
28
+
29
+ export interface TransitFareProps {
30
+ fareKey: string;
31
+ fareNameFallback?: ReactElement;
32
+ fareKeyNameMap: {
33
+ [key: string]: string;
34
+ };
35
+ transitFares: TransitFareData;
36
+ }
37
+
38
+ export interface TripDetailsProps {
39
+ /**
40
+ * Slot for a custom component to render the expandable section for calories.
41
+ */
42
+ CaloriesDetails?: React.ElementType<CaloriesDetailsProps>;
43
+ /**
44
+ * Used for additional styling with styled components for example.
45
+ */
46
+ className?: string;
47
+ /**
48
+ * Determines which transit fare should be displayed by default, should there be multiple transit fare types.
49
+ */
50
+ defaultFareKey?: string;
51
+ /**
52
+ * Slot for a custom component to render the expandable section for departure.
53
+ */
54
+ DepartureDetails?: React.ElementType<DepartureDetailsProps>;
55
+ /**
56
+ * Slot for a custom component to render the expandable section for fares.
57
+ */
58
+ FareDetails?: React.ElementType<FareDetailsProps>;
59
+ /**
60
+ * Mapping between fare keys and human-readable names for them.
61
+ */
62
+ fareKeyNameMap?: {
63
+ [name: string]: string;
64
+ };
65
+ /**
66
+ * Itinerary that the user has selected to view, contains multiple legs.
67
+ */
68
+ itinerary: Itinerary;
69
+ }
package/tsconfig.json ADDED
@@ -0,0 +1,15 @@
1
+ {
2
+ "extends": "../../tsconfig.json",
3
+ "compilerOptions": {
4
+ "composite": true,
5
+ "outDir": "./lib",
6
+ "rootDir": "./src",
7
+ "skipLibCheck": true
8
+ },
9
+ "include": ["src/**/*"],
10
+ "references": [
11
+ {
12
+ "path": "../types"
13
+ }
14
+ ]
15
+ }