@opentripplanner/trip-details 1.6.0 → 2.0.2-alpha.1

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