controls.tsx 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256
  1. import type {RouteComponentProps} from 'react-router';
  2. import {useTheme} from '@emotion/react';
  3. import styled from '@emotion/styled';
  4. import type {LocationDescriptorObject} from 'history';
  5. import pick from 'lodash/pick';
  6. import moment from 'moment-timezone';
  7. import SelectControl from 'sentry/components/forms/controls/selectControl';
  8. import TeamSelector from 'sentry/components/teamSelector';
  9. import type {ChangeData} from 'sentry/components/timeRangeSelector';
  10. import {TimeRangeSelector} from 'sentry/components/timeRangeSelector';
  11. import {t} from 'sentry/locale';
  12. import {space} from 'sentry/styles/space';
  13. import type {DateString} from 'sentry/types/core';
  14. import type {TeamWithProjects} from 'sentry/types/project';
  15. import {uniq} from 'sentry/utils/array/uniq';
  16. import {isActiveSuperuser} from 'sentry/utils/isActiveSuperuser';
  17. import localStorage from 'sentry/utils/localStorage';
  18. import useOrganization from 'sentry/utils/useOrganization';
  19. import useProjects from 'sentry/utils/useProjects';
  20. import {dataDatetime} from './utils';
  21. const INSIGHTS_DEFAULT_STATS_PERIOD = '8w';
  22. const relativeOptions = {
  23. '14d': t('Last 2 weeks'),
  24. '4w': t('Last 4 weeks'),
  25. [INSIGHTS_DEFAULT_STATS_PERIOD]: t('Last 8 weeks'),
  26. '12w': t('Last 12 weeks'),
  27. };
  28. const PAGE_QUERY_PARAMS = [
  29. 'pageStatsPeriod',
  30. 'pageStart',
  31. 'pageEnd',
  32. 'pageUtc',
  33. 'dataCategory',
  34. 'transform',
  35. 'sort',
  36. 'query',
  37. 'cursor',
  38. 'team',
  39. 'environment',
  40. ];
  41. type Props = Pick<RouteComponentProps<{}, {}>, 'router' | 'location'> & {
  42. currentEnvironment?: string;
  43. currentTeam?: TeamWithProjects;
  44. showEnvironment?: boolean;
  45. };
  46. function TeamStatsControls({
  47. location,
  48. router,
  49. currentTeam,
  50. currentEnvironment,
  51. showEnvironment,
  52. }: Props) {
  53. const {projects} = useProjects({
  54. slugs: currentTeam?.projects?.map(project => project.slug) ?? [],
  55. });
  56. const organization = useOrganization();
  57. const isSuperuser = isActiveSuperuser();
  58. const theme = useTheme();
  59. const query = location?.query ?? {};
  60. const localStorageKey = `teamInsightsSelectedTeamId:${organization.slug}`;
  61. function handleChangeTeam(teamId: string) {
  62. localStorage.setItem(localStorageKey, teamId);
  63. // TODO(workflow): Preserve environment if it exists for the new team
  64. setStateOnUrl({team: teamId, environment: undefined});
  65. }
  66. function handleEnvironmentChange({value}: {label: string; value: string}) {
  67. if (value === '') {
  68. setStateOnUrl({environment: undefined});
  69. } else {
  70. setStateOnUrl({environment: value});
  71. }
  72. }
  73. function handleUpdateDatetime(datetime: ChangeData): LocationDescriptorObject {
  74. const {start, end, relative, utc} = datetime;
  75. if (start && end) {
  76. const parser = utc ? moment.utc : moment;
  77. return setStateOnUrl({
  78. pageStatsPeriod: undefined,
  79. pageStart: parser(start).format(),
  80. pageEnd: parser(end).format(),
  81. pageUtc: utc ?? undefined,
  82. });
  83. }
  84. return setStateOnUrl({
  85. pageStatsPeriod: relative || undefined,
  86. pageStart: undefined,
  87. pageEnd: undefined,
  88. pageUtc: undefined,
  89. });
  90. }
  91. function setStateOnUrl(nextState: {
  92. environment?: string;
  93. pageEnd?: DateString;
  94. pageStart?: DateString;
  95. pageStatsPeriod?: string | null;
  96. pageUtc?: boolean | null;
  97. team?: string;
  98. }): LocationDescriptorObject {
  99. const nextQueryParams = pick(nextState, PAGE_QUERY_PARAMS);
  100. const nextLocation = {
  101. ...location,
  102. query: {
  103. ...query,
  104. ...nextQueryParams,
  105. },
  106. };
  107. router.push(nextLocation);
  108. return nextLocation;
  109. }
  110. const {period, start, end, utc} = dataDatetime(query);
  111. const environmentOptions = uniq(projects.flatMap(project => project.environments)).map(
  112. env => ({label: env, value: env})
  113. );
  114. // org:admin is a unique scope that only org owners have
  115. const isOrgOwner = organization.access.includes('org:admin');
  116. return (
  117. <ControlsWrapper showEnvironment={showEnvironment}>
  118. <TeamSelector
  119. name="select-team"
  120. inFieldLabel={t('Team: ')}
  121. value={currentTeam?.slug}
  122. onChange={choice => handleChangeTeam(choice.actor.id)}
  123. teamFilter={
  124. isSuperuser || isOrgOwner ? undefined : filterTeam => filterTeam.isMember
  125. }
  126. styles={{
  127. singleValue(provided: any) {
  128. const custom = {
  129. display: 'flex',
  130. justifyContent: 'space-between',
  131. alignItems: 'center',
  132. fontSize: theme.fontSizeMedium,
  133. ':before': {
  134. ...provided[':before'],
  135. color: theme.textColor,
  136. marginRight: space(1.5),
  137. marginLeft: space(0.5),
  138. },
  139. };
  140. return {...provided, ...custom};
  141. },
  142. input: (provided: any, state: any) => ({
  143. ...provided,
  144. display: 'grid',
  145. gridTemplateColumns: 'max-content 1fr',
  146. alignItems: 'center',
  147. gridGap: space(1),
  148. ':before': {
  149. backgroundColor: state.theme.backgroundSecondary,
  150. height: 24,
  151. width: 38,
  152. borderRadius: 3,
  153. content: '""',
  154. display: 'block',
  155. },
  156. }),
  157. }}
  158. />
  159. {showEnvironment && (
  160. <SelectControl
  161. options={[
  162. {
  163. value: '',
  164. label: t('All'),
  165. },
  166. ...environmentOptions,
  167. ]}
  168. value={currentEnvironment ?? ''}
  169. onChange={handleEnvironmentChange}
  170. styles={{
  171. input: (provided: any) => ({
  172. ...provided,
  173. display: 'grid',
  174. gridTemplateColumns: 'max-content 1fr',
  175. alignItems: 'center',
  176. gridGap: space(1),
  177. ':before': {
  178. height: 24,
  179. width: 90,
  180. borderRadius: 3,
  181. content: '""',
  182. display: 'block',
  183. },
  184. }),
  185. control: (base: any) => ({
  186. ...base,
  187. boxShadow: 'none',
  188. }),
  189. singleValue: (base: any) => ({
  190. ...base,
  191. fontSize: theme.fontSizeMedium,
  192. display: 'flex',
  193. ':before': {
  194. ...base[':before'],
  195. color: theme.textColor,
  196. marginRight: space(1.5),
  197. },
  198. }),
  199. }}
  200. inFieldLabel={t('Environment:')}
  201. />
  202. )}
  203. <StyledTimeRangeSelector
  204. relative={period ?? ''}
  205. start={start ?? null}
  206. end={end ?? null}
  207. utc={utc ?? null}
  208. onChange={handleUpdateDatetime}
  209. showAbsolute={false}
  210. relativeOptions={relativeOptions}
  211. triggerLabel={period && relativeOptions[period]}
  212. triggerProps={{prefix: t('Date Range')}}
  213. />
  214. </ControlsWrapper>
  215. );
  216. }
  217. export default TeamStatsControls;
  218. const ControlsWrapper = styled('div')<{showEnvironment?: boolean}>`
  219. display: grid;
  220. align-items: center;
  221. gap: ${space(2)};
  222. margin-bottom: ${space(2)};
  223. @media (min-width: ${p => p.theme.breakpoints.small}) {
  224. grid-template-columns: 246px ${p => (p.showEnvironment ? '246px' : '')} 1fr;
  225. }
  226. `;
  227. const StyledTimeRangeSelector = styled(TimeRangeSelector)`
  228. div {
  229. min-height: unset;
  230. }
  231. `;