groupList.tsx 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  1. import {Component, Fragment} from 'react';
  2. // eslint-disable-next-line no-restricted-imports
  3. import {browserHistory, withRouter, WithRouterProps} from 'react-router';
  4. import isEqual from 'lodash/isEqual';
  5. import omit from 'lodash/omit';
  6. import * as qs from 'query-string';
  7. import {fetchOrgMembers, indexMembersByProject} from 'sentry/actionCreators/members';
  8. import {Client} from 'sentry/api';
  9. import EmptyStateWarning from 'sentry/components/emptyStateWarning';
  10. import LoadingError from 'sentry/components/loadingError';
  11. import LoadingIndicator from 'sentry/components/loadingIndicator';
  12. import Pagination from 'sentry/components/pagination';
  13. import {Panel, PanelBody} from 'sentry/components/panels';
  14. import {parseSearch, Token} from 'sentry/components/searchSyntax/parser';
  15. import {treeResultLocator} from 'sentry/components/searchSyntax/utils';
  16. import StreamGroup, {
  17. DEFAULT_STREAM_GROUP_STATS_PERIOD,
  18. } from 'sentry/components/stream/group';
  19. import {t} from 'sentry/locale';
  20. import GroupStore from 'sentry/stores/groupStore';
  21. import {Group} from 'sentry/types';
  22. import withApi from 'sentry/utils/withApi';
  23. import {TimePeriodType} from 'sentry/views/alerts/rules/metric/details/constants';
  24. import {RELATED_ISSUES_BOOLEAN_QUERY_ERROR} from 'sentry/views/alerts/rules/metric/details/relatedIssuesNotAvailable';
  25. import GroupListHeader from './groupListHeader';
  26. const defaultProps = {
  27. canSelectGroups: true,
  28. withChart: true,
  29. withPagination: true,
  30. useFilteredStats: true,
  31. useTintRow: true,
  32. narrowGroups: false,
  33. };
  34. type Props = WithRouterProps & {
  35. api: Client;
  36. endpointPath: string;
  37. orgId: string;
  38. query: string;
  39. customStatsPeriod?: TimePeriodType;
  40. onFetchSuccess?: (
  41. groupListState: State,
  42. onCursor: (
  43. cursor: string,
  44. path: string,
  45. query: Record<string, any>,
  46. pageDiff: number
  47. ) => void
  48. ) => void;
  49. queryFilterDescription?: string;
  50. queryParams?: Record<string, number | string | string[] | undefined | null>;
  51. renderEmptyMessage?: () => React.ReactNode;
  52. renderErrorMessage?: (props: {detail: string}, retry: () => void) => React.ReactNode;
  53. // where the group list is rendered
  54. source?: string;
  55. } & Partial<typeof defaultProps>;
  56. type State = {
  57. error: boolean;
  58. errorData: {detail: string} | null;
  59. groups: Group[];
  60. loading: boolean;
  61. pageLinks: string | null;
  62. memberList?: ReturnType<typeof indexMembersByProject>;
  63. };
  64. class GroupList extends Component<Props, State> {
  65. static defaultProps = defaultProps;
  66. state: State = {
  67. loading: true,
  68. error: false,
  69. errorData: null,
  70. groups: [],
  71. pageLinks: null,
  72. };
  73. componentDidMount() {
  74. this.fetchData();
  75. }
  76. shouldComponentUpdate(nextProps: Props, nextState: State) {
  77. return (
  78. !isEqual(this.state, nextState) ||
  79. nextProps.endpointPath !== this.props.endpointPath ||
  80. nextProps.query !== this.props.query ||
  81. !isEqual(nextProps.queryParams, this.props.queryParams)
  82. );
  83. }
  84. componentDidUpdate(prevProps: Props) {
  85. const ignoredQueryParams = ['end'];
  86. if (
  87. prevProps.orgId !== this.props.orgId ||
  88. prevProps.endpointPath !== this.props.endpointPath ||
  89. prevProps.query !== this.props.query ||
  90. !isEqual(
  91. omit(prevProps.queryParams, ignoredQueryParams),
  92. omit(this.props.queryParams, ignoredQueryParams)
  93. )
  94. ) {
  95. this.fetchData();
  96. }
  97. }
  98. componentWillUnmount() {
  99. GroupStore.reset();
  100. this.listener?.();
  101. }
  102. listener = GroupStore.listen(() => this.onGroupChange(), undefined);
  103. fetchData = async () => {
  104. GroupStore.loadInitialData([]);
  105. const {api, orgId, queryParams} = this.props;
  106. api.clear();
  107. this.setState({loading: true, error: false, errorData: null});
  108. fetchOrgMembers(api, orgId).then(members => {
  109. this.setState({memberList: indexMembersByProject(members)});
  110. });
  111. const endpoint = this.getGroupListEndpoint();
  112. const parsedQuery = parseSearch((queryParams ?? this.getQueryParams()).query);
  113. const hasLogicBoolean = parsedQuery
  114. ? treeResultLocator<boolean>({
  115. tree: parsedQuery,
  116. noResultValue: false,
  117. visitorTest: ({token, returnResult}) => {
  118. return token.type === Token.LogicBoolean ? returnResult(true) : null;
  119. },
  120. })
  121. : false;
  122. // Check if the alert rule query has AND or OR
  123. // logic queries haven't been implemented for issue search yet
  124. if (hasLogicBoolean) {
  125. this.setState({
  126. error: true,
  127. errorData: {detail: RELATED_ISSUES_BOOLEAN_QUERY_ERROR},
  128. loading: false,
  129. });
  130. return;
  131. }
  132. try {
  133. const [data, , jqXHR] = await api.requestPromise(endpoint, {
  134. includeAllArgs: true,
  135. });
  136. GroupStore.add(data);
  137. this.setState(
  138. {
  139. error: false,
  140. errorData: null,
  141. loading: false,
  142. pageLinks: jqXHR?.getResponseHeader('Link') ?? null,
  143. },
  144. () => {
  145. this.props.onFetchSuccess?.(this.state, this.handleCursorChange);
  146. }
  147. );
  148. } catch (error) {
  149. this.setState({error: true, errorData: error.responseJSON, loading: false});
  150. }
  151. };
  152. getGroupListEndpoint() {
  153. const {orgId, endpointPath, queryParams} = this.props;
  154. const path = endpointPath ?? `/organizations/${orgId}/issues/`;
  155. const queryParameters = queryParams ?? this.getQueryParams();
  156. return `${path}?${qs.stringify(queryParameters)}`;
  157. }
  158. getQueryParams() {
  159. const {location, query} = this.props;
  160. const queryParams = location.query;
  161. queryParams.limit = 50;
  162. queryParams.sort = 'new';
  163. queryParams.query = query;
  164. return queryParams;
  165. }
  166. handleCursorChange(
  167. cursor: string | undefined,
  168. path: string,
  169. query: Record<string, any>,
  170. pageDiff: number
  171. ) {
  172. const queryPageInt = parseInt(query.page, 10);
  173. let nextPage: number | undefined = isNaN(queryPageInt)
  174. ? pageDiff
  175. : queryPageInt + pageDiff;
  176. // unset cursor and page when we navigate back to the first page
  177. // also reset cursor if somehow the previous button is enabled on
  178. // first page and user attempts to go backwards
  179. if (nextPage <= 0) {
  180. cursor = undefined;
  181. nextPage = undefined;
  182. }
  183. browserHistory.push({
  184. pathname: path,
  185. query: {...query, cursor, page: nextPage},
  186. });
  187. }
  188. onGroupChange() {
  189. const groups = GroupStore.getAllItems() as Group[];
  190. if (!isEqual(groups, this.state.groups)) {
  191. this.setState({groups});
  192. }
  193. }
  194. render() {
  195. const {
  196. canSelectGroups,
  197. withChart,
  198. renderEmptyMessage,
  199. renderErrorMessage,
  200. withPagination,
  201. useFilteredStats,
  202. useTintRow,
  203. customStatsPeriod,
  204. queryParams,
  205. queryFilterDescription,
  206. narrowGroups,
  207. source,
  208. } = this.props;
  209. const {loading, error, errorData, groups, memberList, pageLinks} = this.state;
  210. if (loading) {
  211. return <LoadingIndicator />;
  212. }
  213. if (error) {
  214. if (typeof renderErrorMessage === 'function' && errorData) {
  215. return renderErrorMessage(errorData, this.fetchData);
  216. }
  217. return <LoadingError onRetry={this.fetchData} />;
  218. }
  219. if (groups.length === 0) {
  220. if (typeof renderEmptyMessage === 'function') {
  221. return renderEmptyMessage();
  222. }
  223. return (
  224. <Panel>
  225. <PanelBody>
  226. <EmptyStateWarning>
  227. <p>{t("There don't seem to be any events fitting the query.")}</p>
  228. </EmptyStateWarning>
  229. </PanelBody>
  230. </Panel>
  231. );
  232. }
  233. const statsPeriod =
  234. queryParams?.groupStatsPeriod === 'auto'
  235. ? queryParams?.groupStatsPeriod
  236. : DEFAULT_STREAM_GROUP_STATS_PERIOD;
  237. return (
  238. <Fragment>
  239. <Panel>
  240. <GroupListHeader withChart={!!withChart} narrowGroups={narrowGroups} />
  241. <PanelBody>
  242. {groups.map(({id, project}) => {
  243. const members = memberList?.hasOwnProperty(project.slug)
  244. ? memberList[project.slug]
  245. : undefined;
  246. return (
  247. <StreamGroup
  248. key={id}
  249. id={id}
  250. canSelect={canSelectGroups}
  251. withChart={withChart}
  252. memberList={members}
  253. useFilteredStats={useFilteredStats}
  254. useTintRow={useTintRow}
  255. customStatsPeriod={customStatsPeriod}
  256. statsPeriod={statsPeriod}
  257. queryFilterDescription={queryFilterDescription}
  258. narrowGroups={narrowGroups}
  259. source={source}
  260. />
  261. );
  262. })}
  263. </PanelBody>
  264. </Panel>
  265. {withPagination && (
  266. <Pagination pageLinks={pageLinks} onCursor={this.handleCursorChange} />
  267. )}
  268. </Fragment>
  269. );
  270. }
  271. }
  272. export {GroupList};
  273. export default withApi(withRouter(GroupList));