index.tsx 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271
  1. import * as React from 'react';
  2. import type {OnChangeProps, RangeWithKey} from 'react-date-range';
  3. import {withRouter, WithRouterProps} from 'react-router';
  4. import {withTheme} from '@emotion/react';
  5. import styled from '@emotion/styled';
  6. import moment from 'moment';
  7. import Checkbox from 'sentry/components/checkbox';
  8. import LoadingIndicator from 'sentry/components/loadingIndicator';
  9. import TimePicker from 'sentry/components/organizations/timeRangeSelector/timePicker';
  10. import Placeholder from 'sentry/components/placeholder';
  11. import {MAX_PICKABLE_DAYS} from 'sentry/constants';
  12. import {t} from 'sentry/locale';
  13. import space from 'sentry/styles/space';
  14. import {Organization} from 'sentry/types';
  15. import {analytics} from 'sentry/utils/analytics';
  16. import {
  17. getEndOfDay,
  18. getStartOfPeriodAgo,
  19. isValidTime,
  20. setDateToTime,
  21. } from 'sentry/utils/dates';
  22. import getRouteStringFromRoutes from 'sentry/utils/getRouteStringFromRoutes';
  23. import {Theme} from 'sentry/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 = {end?: Date; hasDateRangeErrors?: boolean; start?: Date};
  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 = WithRouterProps & {
  41. /**
  42. * End date value for absolute date selector
  43. */
  44. end: Date | null;
  45. /**
  46. * Callback when value changes
  47. */
  48. onChange: (data: ChangeData) => void;
  49. /**
  50. * handle UTC checkbox change
  51. */
  52. onChangeUtc: () => void;
  53. /**
  54. * Just used for metrics
  55. */
  56. organization: Organization;
  57. /**
  58. * Start date value for absolute date selector
  59. */
  60. start: Date | null;
  61. theme: Theme;
  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. hasEndErrors: boolean;
  74. hasStartErrors: boolean;
  75. };
  76. class BaseDateRange 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 {className, maxPickableDays, utc, showTimePicker, onChangeUtc, theme} =
  149. this.props;
  150. const start = this.props.start ?? '';
  151. const end = this.props.end ?? '';
  152. const startTime = getTimeStringFromDate(new Date(start));
  153. const endTime = getTimeStringFromDate(new Date(end));
  154. // Restraints on the time range that you can select
  155. // Can't select dates in the future b/c we're not fortune tellers (yet)
  156. //
  157. // We want `maxPickableDays` - 1 (if today is Jan 5, max is 3 days, the minDate should be Jan 3)
  158. // Subtract additional day because we force the end date to be inclusive,
  159. // so when you pick Jan 1 the time becomes Jan 1 @ 23:59:59,
  160. // (or really, Jan 2 @ 00:00:00 - 1 second), while the start time is at 00:00
  161. const minDate = getStartOfPeriodAgo(
  162. 'days',
  163. (maxPickableDays ?? MAX_PICKABLE_DAYS) - 2
  164. );
  165. const maxDate = new Date();
  166. return (
  167. <div className={className} data-test-id="date-range">
  168. <React.Suspense
  169. fallback={
  170. <Placeholder width="342px" height="254px">
  171. <LoadingIndicator />
  172. </Placeholder>
  173. }
  174. >
  175. <DateRangePicker
  176. rangeColors={[theme.purple300]}
  177. ranges={[
  178. {
  179. startDate: moment(start).local().toDate(),
  180. endDate: moment(end).local().toDate(),
  181. key: 'selection',
  182. },
  183. ]}
  184. minDate={minDate}
  185. maxDate={maxDate}
  186. onChange={this.handleSelectDateRange}
  187. />
  188. </React.Suspense>
  189. {showTimePicker && (
  190. <TimeAndUtcPicker>
  191. <TimePicker
  192. start={startTime}
  193. end={endTime}
  194. onChangeStart={this.handleChangeStart}
  195. onChangeEnd={this.handleChangeEnd}
  196. />
  197. <UtcPicker>
  198. {t('Use UTC')}
  199. <Checkbox
  200. onChange={onChangeUtc}
  201. checked={utc || false}
  202. style={{
  203. margin: '0 0 0 0.5em',
  204. }}
  205. />
  206. </UtcPicker>
  207. </TimeAndUtcPicker>
  208. )}
  209. </div>
  210. );
  211. }
  212. }
  213. const DateRange = styled(withTheme(withRouter(BaseDateRange)))`
  214. display: flex;
  215. flex-direction: column;
  216. border-left: 1px solid ${p => p.theme.border};
  217. `;
  218. const TimeAndUtcPicker = styled('div')`
  219. display: flex;
  220. align-items: center;
  221. padding: ${space(0.25)} ${space(2)};
  222. border-top: 1px solid ${p => p.theme.innerBorder};
  223. `;
  224. const UtcPicker = styled('div')`
  225. color: ${p => p.theme.gray300};
  226. white-space: nowrap;
  227. display: flex;
  228. align-items: center;
  229. justify-content: flex-end;
  230. flex: 1;
  231. `;
  232. export default DateRange;