index.tsx 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277
  1. import * as React from 'react';
  2. import type {OnChangeProps, RangeWithKey} from 'react-date-range';
  3. import * as ReactRouter from 'react-router';
  4. import {withTheme} from '@emotion/react';
  5. import styled from '@emotion/styled';
  6. import moment from 'moment';
  7. import Checkbox from 'app/components/checkbox';
  8. import LoadingIndicator from 'app/components/loadingIndicator';
  9. import TimePicker from 'app/components/organizations/timeRangeSelector/timePicker';
  10. import Placeholder from 'app/components/placeholder';
  11. import {MAX_PICKABLE_DAYS} from 'app/constants';
  12. import {t} from 'app/locale';
  13. import space from 'app/styles/space';
  14. import {LightWeightOrganization} from 'app/types';
  15. import {analytics} from 'app/utils/analytics';
  16. import {
  17. getEndOfDay,
  18. getStartOfPeriodAgo,
  19. isValidTime,
  20. setDateToTime,
  21. } from 'app/utils/dates';
  22. import getRouteStringFromRoutes from 'app/utils/getRouteStringFromRoutes';
  23. import {Theme} from 'app/utils/theme';
  24. const DateRangePicker = React.lazy(() => import('./dateRangeWrapper'));
  25. const getTimeStringFromDate = (date: Date) => moment(date).local().format('HH:mm');
  26. // react.date-range doesn't export this as a type.
  27. type RangeSelection = {selection: RangeWithKey};
  28. function isRangeSelection(maybe: OnChangeProps): maybe is RangeSelection {
  29. return (maybe as RangeSelection).selection !== undefined;
  30. }
  31. type ChangeData = {start?: Date; end?: Date; hasDateRangeErrors?: boolean};
  32. const defaultProps = {
  33. showAbsolute: true,
  34. showRelative: false,
  35. /**
  36. * The maximum number of days in the past you can pick
  37. */
  38. maxPickableDays: MAX_PICKABLE_DAYS,
  39. };
  40. type Props = ReactRouter.WithRouterProps & {
  41. theme: Theme;
  42. /**
  43. * Just used for metrics
  44. */
  45. organization: LightWeightOrganization;
  46. /**
  47. * Start date value for absolute date selector
  48. */
  49. start: Date | null;
  50. /**
  51. * End date value for absolute date selector
  52. */
  53. end: Date | null;
  54. /**
  55. * handle UTC checkbox change
  56. */
  57. onChangeUtc: () => void;
  58. /**
  59. * Callback when value changes
  60. */
  61. onChange: (data: ChangeData) => void;
  62. className?: string;
  63. /**
  64. * Should we have a time selector?
  65. */
  66. showTimePicker?: boolean;
  67. /**
  68. * Use UTC
  69. */
  70. utc?: boolean | null;
  71. } & Partial<typeof defaultProps>;
  72. type State = {
  73. hasStartErrors: boolean;
  74. hasEndErrors: boolean;
  75. };
  76. class DateRange extends React.Component<Props, State> {
  77. static defaultProps = defaultProps;
  78. state: State = {
  79. hasStartErrors: false,
  80. hasEndErrors: false,
  81. };
  82. handleSelectDateRange = (changeProps: OnChangeProps) => {
  83. if (!isRangeSelection(changeProps)) {
  84. return;
  85. }
  86. const {selection} = changeProps;
  87. const {onChange} = this.props;
  88. const {startDate, endDate} = selection;
  89. const end = endDate ? getEndOfDay(endDate) : endDate;
  90. onChange({
  91. start: startDate,
  92. end,
  93. });
  94. };
  95. handleChangeStart = (e: React.ChangeEvent<HTMLInputElement>) => {
  96. // Safari does not support "time" inputs, so we don't have access to
  97. // `e.target.valueAsDate`, must parse as string
  98. //
  99. // Time will be in 24hr e.g. "21:00"
  100. const start = this.props.start ?? '';
  101. const end = this.props.end ?? undefined;
  102. const {onChange, organization, router} = this.props;
  103. const startTime = e.target.value;
  104. if (!startTime || !isValidTime(startTime)) {
  105. this.setState({hasStartErrors: true});
  106. onChange({hasDateRangeErrors: true});
  107. return;
  108. }
  109. const newTime = setDateToTime(start, startTime, {local: true});
  110. analytics('dateselector.time_changed', {
  111. field_changed: 'start',
  112. time: startTime,
  113. path: getRouteStringFromRoutes(router.routes),
  114. org_id: parseInt(organization.id, 10),
  115. });
  116. onChange({
  117. start: newTime,
  118. end,
  119. hasDateRangeErrors: this.state.hasEndErrors,
  120. });
  121. this.setState({hasStartErrors: false});
  122. };
  123. handleChangeEnd = (e: React.ChangeEvent<HTMLInputElement>) => {
  124. const start = this.props.start ?? undefined;
  125. const end = this.props.end ?? '';
  126. const {organization, onChange, router} = this.props;
  127. const endTime = e.target.value;
  128. if (!endTime || !isValidTime(endTime)) {
  129. this.setState({hasEndErrors: true});
  130. onChange({hasDateRangeErrors: true});
  131. return;
  132. }
  133. const newTime = setDateToTime(end, endTime, {local: true});
  134. analytics('dateselector.time_changed', {
  135. field_changed: 'end',
  136. time: endTime,
  137. path: getRouteStringFromRoutes(router.routes),
  138. org_id: parseInt(organization.id, 10),
  139. });
  140. onChange({
  141. start,
  142. end: newTime,
  143. hasDateRangeErrors: this.state.hasStartErrors,
  144. });
  145. this.setState({hasEndErrors: false});
  146. };
  147. render() {
  148. const {
  149. className,
  150. maxPickableDays,
  151. utc,
  152. showTimePicker,
  153. onChangeUtc,
  154. theme,
  155. } = this.props;
  156. const start = this.props.start ?? '';
  157. const end = this.props.end ?? '';
  158. const startTime = getTimeStringFromDate(new Date(start));
  159. const endTime = getTimeStringFromDate(new Date(end));
  160. // Restraints on the time range that you can select
  161. // Can't select dates in the future b/c we're not fortune tellers (yet)
  162. //
  163. // We want `maxPickableDays` - 1 (if today is Jan 5, max is 3 days, the minDate should be Jan 3)
  164. // Subtract additional day because we force the end date to be inclusive,
  165. // so when you pick Jan 1 the time becomes Jan 1 @ 23:59:59,
  166. // (or really, Jan 2 @ 00:00:00 - 1 second), while the start time is at 00:00
  167. const minDate = getStartOfPeriodAgo(
  168. 'days',
  169. (maxPickableDays ?? MAX_PICKABLE_DAYS) - 2
  170. );
  171. const maxDate = new Date();
  172. return (
  173. <div className={className} data-test-id="date-range">
  174. <React.Suspense
  175. fallback={
  176. <Placeholder width="342px" height="254px">
  177. <LoadingIndicator />
  178. </Placeholder>
  179. }
  180. >
  181. <DateRangePicker
  182. rangeColors={[theme.purple300]}
  183. ranges={[
  184. {
  185. startDate: moment(start).local().toDate(),
  186. endDate: moment(end).local().toDate(),
  187. key: 'selection',
  188. },
  189. ]}
  190. minDate={minDate}
  191. maxDate={maxDate}
  192. onChange={this.handleSelectDateRange}
  193. />
  194. </React.Suspense>
  195. {showTimePicker && (
  196. <TimeAndUtcPicker>
  197. <TimePicker
  198. start={startTime}
  199. end={endTime}
  200. onChangeStart={this.handleChangeStart}
  201. onChangeEnd={this.handleChangeEnd}
  202. />
  203. <UtcPicker>
  204. {t('Use UTC')}
  205. <Checkbox
  206. onChange={onChangeUtc}
  207. checked={utc || false}
  208. style={{
  209. margin: '0 0 0 0.5em',
  210. }}
  211. />
  212. </UtcPicker>
  213. </TimeAndUtcPicker>
  214. )}
  215. </div>
  216. );
  217. }
  218. }
  219. const StyledDateRange = styled(withTheme(ReactRouter.withRouter(DateRange)))`
  220. display: flex;
  221. flex-direction: column;
  222. border-left: 1px solid ${p => p.theme.border};
  223. `;
  224. const TimeAndUtcPicker = styled('div')`
  225. display: flex;
  226. align-items: center;
  227. padding: ${space(2)};
  228. border-top: 1px solid ${p => p.theme.innerBorder};
  229. `;
  230. const UtcPicker = styled('div')`
  231. color: ${p => p.theme.gray300};
  232. white-space: nowrap;
  233. display: flex;
  234. align-items: center;
  235. justify-content: flex-end;
  236. flex: 1;
  237. `;
  238. export default StyledDateRange;