groupList.tsx 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313
  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 {callIfFunction} from 'sentry/utils/callIfFunction';
  23. import StreamManager from 'sentry/utils/streamManager';
  24. import withApi from 'sentry/utils/withApi';
  25. import {TimePeriodType} from 'sentry/views/alerts/rules/metric/details/constants';
  26. import {RELATED_ISSUES_BOOLEAN_QUERY_ERROR} from 'sentry/views/alerts/rules/metric/details/relatedIssuesNotAvailable';
  27. import GroupListHeader from './groupListHeader';
  28. const defaultProps = {
  29. canSelectGroups: true,
  30. withChart: true,
  31. withPagination: true,
  32. useFilteredStats: true,
  33. useTintRow: true,
  34. narrowGroups: false,
  35. };
  36. type Props = WithRouterProps & {
  37. api: Client;
  38. endpointPath: string;
  39. orgId: string;
  40. query: string;
  41. customStatsPeriod?: TimePeriodType;
  42. onFetchSuccess?: (
  43. groupListState: State,
  44. onCursor: (
  45. cursor: string,
  46. path: string,
  47. query: Record<string, any>,
  48. pageDiff: number
  49. ) => void
  50. ) => void;
  51. queryFilterDescription?: string;
  52. queryParams?: Record<string, number | string | string[] | undefined | null>;
  53. renderEmptyMessage?: () => React.ReactNode;
  54. renderErrorMessage?: ({detail: string}, retry: () => void) => React.ReactNode;
  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. callIfFunction(this.listener);
  101. }
  102. listener = GroupStore.listen(() => this.onGroupChange(), undefined);
  103. private _streamManager = new StreamManager(GroupStore);
  104. fetchData = async () => {
  105. GroupStore.loadInitialData([]);
  106. const {api, orgId, queryParams} = this.props;
  107. api.clear();
  108. this.setState({loading: true, error: false, errorData: null});
  109. fetchOrgMembers(api, orgId).then(members => {
  110. this.setState({memberList: indexMembersByProject(members)});
  111. });
  112. const endpoint = this.getGroupListEndpoint();
  113. const parsedQuery = parseSearch((queryParams ?? this.getQueryParams()).query);
  114. const hasLogicBoolean = parsedQuery
  115. ? treeResultLocator<boolean>({
  116. tree: parsedQuery,
  117. noResultValue: false,
  118. visitorTest: ({token, returnResult}) => {
  119. return token.type === Token.LogicBoolean ? returnResult(true) : null;
  120. },
  121. })
  122. : false;
  123. // Check if the alert rule query has AND or OR
  124. // logic queries haven't been implemented for issue search yet
  125. if (hasLogicBoolean) {
  126. this.setState({
  127. error: true,
  128. errorData: {detail: RELATED_ISSUES_BOOLEAN_QUERY_ERROR},
  129. loading: false,
  130. });
  131. return;
  132. }
  133. try {
  134. const [data, , jqXHR] = await api.requestPromise(endpoint, {
  135. includeAllArgs: true,
  136. });
  137. this._streamManager.push(data);
  138. this.setState(
  139. {
  140. error: false,
  141. errorData: null,
  142. loading: false,
  143. pageLinks: jqXHR?.getResponseHeader('Link') ?? null,
  144. },
  145. () => {
  146. this.props.onFetchSuccess?.(this.state, this.handleCursorChange);
  147. }
  148. );
  149. } catch (error) {
  150. this.setState({error: true, errorData: error.responseJSON, loading: false});
  151. }
  152. };
  153. getGroupListEndpoint() {
  154. const {orgId, endpointPath, queryParams} = this.props;
  155. const path = endpointPath ?? `/organizations/${orgId}/issues/`;
  156. const queryParameters = queryParams ?? this.getQueryParams();
  157. return `${path}?${qs.stringify(queryParameters)}`;
  158. }
  159. getQueryParams() {
  160. const {location, query} = this.props;
  161. const queryParams = location.query;
  162. queryParams.limit = 50;
  163. queryParams.sort = 'new';
  164. queryParams.query = query;
  165. return queryParams;
  166. }
  167. handleCursorChange(
  168. cursor: string | undefined,
  169. path: string,
  170. query: Record<string, any>,
  171. pageDiff: number
  172. ) {
  173. const queryPageInt = parseInt(query.page, 10);
  174. let nextPage: number | undefined = isNaN(queryPageInt)
  175. ? pageDiff
  176. : queryPageInt + pageDiff;
  177. // unset cursor and page when we navigate back to the first page
  178. // also reset cursor if somehow the previous button is enabled on
  179. // first page and user attempts to go backwards
  180. if (nextPage <= 0) {
  181. cursor = undefined;
  182. nextPage = undefined;
  183. }
  184. browserHistory.push({
  185. pathname: path,
  186. query: {...query, cursor, page: nextPage},
  187. });
  188. }
  189. onGroupChange() {
  190. const groups = this._streamManager.getAllItems();
  191. if (!isEqual(groups, this.state.groups)) {
  192. this.setState({groups});
  193. }
  194. }
  195. render() {
  196. const {
  197. canSelectGroups,
  198. withChart,
  199. renderEmptyMessage,
  200. renderErrorMessage,
  201. withPagination,
  202. useFilteredStats,
  203. useTintRow,
  204. customStatsPeriod,
  205. queryParams,
  206. queryFilterDescription,
  207. narrowGroups,
  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. />
  260. );
  261. })}
  262. </PanelBody>
  263. </Panel>
  264. {withPagination && (
  265. <Pagination pageLinks={pageLinks} onCursor={this.handleCursorChange} />
  266. )}
  267. </Fragment>
  268. );
  269. }
  270. }
  271. export {GroupList};
  272. export default withApi(withRouter(GroupList));