controls.tsx 7.3 KB

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