resultGrid.tsx 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589
  1. import {Component} from 'react';
  2. import styled from '@emotion/styled';
  3. import type {Location} from 'history';
  4. import type {Client} from 'sentry/api';
  5. import {CompactSelect} from 'sentry/components/compactSelect';
  6. import {Alert} from 'sentry/components/core/alert';
  7. import {Button} from 'sentry/components/core/button';
  8. import {Input} from 'sentry/components/core/input';
  9. import EmptyMessage from 'sentry/components/emptyMessage';
  10. import LoadingIndicator from 'sentry/components/loadingIndicator';
  11. import Pagination from 'sentry/components/pagination';
  12. import Panel from 'sentry/components/panels/panel';
  13. import PanelHeader from 'sentry/components/panels/panelHeader';
  14. import {IconList, IconSearch} from 'sentry/icons';
  15. import {t} from 'sentry/locale';
  16. import ConfigStore from 'sentry/stores/configStore';
  17. import {space} from 'sentry/styles/space';
  18. import type {WithRouterProps} from 'sentry/types/legacyReactRouter';
  19. import type {Region} from 'sentry/types/system';
  20. import {browserHistory} from 'sentry/utils/browserHistory';
  21. import withApi from 'sentry/utils/withApi';
  22. // eslint-disable-next-line no-restricted-imports
  23. import withSentryRouter from 'sentry/utils/withSentryRouter';
  24. import ResultTable from 'admin/components/resultTable';
  25. type Option = [key: string, label: string];
  26. type FilterProps = {
  27. name: string;
  28. options: Option[];
  29. queryKey: string;
  30. value: string;
  31. location?: Location;
  32. path?: string;
  33. };
  34. function Filter({name, queryKey, options, path, location, value}: FilterProps) {
  35. const {query, pathname} = location ?? {};
  36. const resolvedPath = path ?? pathname ?? '';
  37. const allOptions = [
  38. {value: '', label: 'Any'},
  39. ...options.map(item => ({value: item[0], label: item[1]})),
  40. ];
  41. const onFilter = (filter: any) => {
  42. const newQuery = {
  43. ...query,
  44. [queryKey]: filter,
  45. cursor: '', // reset cursor for pagination
  46. };
  47. browserHistory.push({pathname: resolvedPath, query: newQuery});
  48. };
  49. return (
  50. <CompactSelect
  51. triggerProps={{prefix: name, size: 'xs'}}
  52. value={value}
  53. onChange={opt => onFilter(opt.value)}
  54. options={allOptions}
  55. />
  56. );
  57. }
  58. type SortFn = (value: string, path: string, query: Location['query']) => void;
  59. type SortByProps = {
  60. options: Option[];
  61. path: string;
  62. value: string;
  63. location?: Location;
  64. onSort?: SortFn;
  65. };
  66. const defaultOnSort: SortFn = (value, path, query) => {
  67. const newQuery = {
  68. ...query,
  69. sortBy: value,
  70. cursor: '', // reset cursor for pagination
  71. };
  72. browserHistory.push({pathname: path, query: newQuery});
  73. };
  74. function SortBy({options, path, location, value, onSort = defaultOnSort}: SortByProps) {
  75. const {query, pathname} = location ?? {};
  76. const resolvedPath = path ?? pathname;
  77. return (
  78. <CompactSelect
  79. triggerProps={{icon: <IconList size="xs" />, prefix: 'Sort By'}}
  80. value={value}
  81. onChange={opt => onSort(opt.value, resolvedPath, query ?? {})}
  82. options={options.map(item => ({value: item[0], label: item[1]}))}
  83. />
  84. );
  85. }
  86. type FilterDescriptor = {
  87. name: string;
  88. options: Option[];
  89. };
  90. interface ResultGridProps extends WithRouterProps {
  91. api: Client;
  92. /**
  93. * A list of table header column labels
  94. */
  95. columns: React.ReactNode[];
  96. /**
  97. * The API path to get the grid data from
  98. */
  99. endpoint: string;
  100. /**
  101. * The relative path to map result URLs to
  102. */
  103. path: string;
  104. /**
  105. * Button on the right side of the header
  106. */
  107. buttonGroup?: React.ReactNode;
  108. /**
  109. * Maps the row result into columns
  110. */
  111. columnsForRow?: (row: any, allRows: any[], state: State) => React.ReactNode[];
  112. /**
  113. * Additional default parameters to use when making the API requests
  114. */
  115. defaultParams?: Record<string, string | number>;
  116. /**
  117. * The default sorting to use when one hasn't been selected yet
  118. */
  119. defaultSort?: string;
  120. /**
  121. * A definition of filters
  122. */
  123. filters?: Record<string, FilterDescriptor>;
  124. /**
  125. * Should the results be paginated?
  126. *
  127. * @default true
  128. */
  129. hasPagination?: boolean;
  130. /**
  131. * Does the result grid have a search bar
  132. *
  133. * @default false
  134. */
  135. hasSearch?: boolean;
  136. /**
  137. * Wrap the table in a panel.
  138. *
  139. * If a react component is passed that component will be rendered as the
  140. * wrapping panel
  141. */
  142. inPanel?: boolean | React.ComponentType<{children?: React.ReactNode}>;
  143. /**
  144. * Is this a regional endpoint? If so, a region selector will be rendered
  145. *
  146. * @default false
  147. */
  148. isRegional?: boolean;
  149. /**
  150. * Get's the row key from the row
  151. *
  152. * Defaults to picking the `id` property
  153. */
  154. keyForRow?: (row: any) => string;
  155. /**
  156. * The method used when making a request to the API path
  157. */
  158. method?: 'GET' | 'POST';
  159. /**
  160. * Forwards the error message received when trying to load the data.
  161. */
  162. onError?: (res: any) => void;
  163. /**
  164. * Fires each time the API successfully updates the data. Does not forward the data itself.
  165. */
  166. onLoad?: () => void;
  167. /**
  168. * When wrapped with inPanel may be used to set the panel title
  169. */
  170. panelTitle?: string;
  171. /**
  172. * Translates the data object from the request into rows
  173. */
  174. rowsFromData?: (data: any, region: Region | undefined) => any[];
  175. /**
  176. * Allowed sorting options
  177. */
  178. sortOptions?: Option[];
  179. /**
  180. * TODO
  181. */
  182. useQueryString?: boolean;
  183. }
  184. export type State = {
  185. cursor: string;
  186. error: boolean;
  187. filters: Location['query'];
  188. loading: boolean;
  189. pageLinks: string | null;
  190. query: string;
  191. region: Region | undefined;
  192. rows: any[];
  193. sortBy: string;
  194. };
  195. const extractQuery = (query: Location['query'][string], defaultVal = '') =>
  196. (Array.isArray(query) ? query[0] : query) ?? defaultVal;
  197. class ResultGrid extends Component<ResultGridProps, State> {
  198. static defaultProps: Partial<ResultGridProps> = {
  199. method: 'GET',
  200. endpoint: '',
  201. path: '',
  202. columns: [],
  203. filters: {},
  204. defaultSort: '',
  205. keyForRow: function (row) {
  206. return row.id;
  207. },
  208. columnsForRow: function () {
  209. return [];
  210. },
  211. defaultParams: {
  212. per_page: 50,
  213. },
  214. hasPagination: true,
  215. isRegional: false,
  216. useQueryString: true,
  217. };
  218. constructor(props: any) {
  219. super(props);
  220. const queryParams = this.props.location?.query ?? {};
  221. const {cursor, query, sortBy} = queryParams;
  222. this.state = {
  223. rows: [],
  224. loading: true,
  225. error: false,
  226. pageLinks: null,
  227. cursor: extractQuery(cursor),
  228. query: extractQuery(query),
  229. region: this.props.isRegional ? ConfigStore.get('regions')[0] : undefined,
  230. sortBy: extractQuery(sortBy, this.props.defaultSort),
  231. filters: Object.assign({}, queryParams),
  232. };
  233. }
  234. componentDidMount() {
  235. this.fetchData();
  236. }
  237. componentDidUpdate(prevProps: ResultGridProps) {
  238. if (!this.props.useQueryString || this.props.location === prevProps.location) {
  239. return;
  240. }
  241. const queryParams = this.props.location?.query ?? {};
  242. const {cursor, query, sortBy} = queryParams;
  243. this.setState(
  244. {
  245. cursor: extractQuery(cursor),
  246. query: extractQuery(query),
  247. sortBy: extractQuery(sortBy, this.props.defaultSort),
  248. filters: Object.assign({}, queryParams),
  249. pageLinks: null,
  250. loading: true,
  251. error: false,
  252. },
  253. this.fetchData
  254. );
  255. }
  256. refresh() {
  257. this.setState({loading: true}, this.fetchData);
  258. }
  259. fetchData = () => {
  260. // Avoid slow-fetch race conditions
  261. this.props.api.clear();
  262. // TODO(dcramer): this should whitelist filters/sortBy/cursor/perPage
  263. const queryParams = {
  264. ...this.props.defaultParams,
  265. ...(this.props.useQueryString ? (this.props.location?.query ?? {}) : {}),
  266. sortBy: this.state.sortBy,
  267. cursor: this.state.cursor,
  268. };
  269. this.props.api.request(this.props.endpoint, {
  270. method: this.props.method,
  271. host: this.state.region ? this.state.region.url : undefined,
  272. data: queryParams,
  273. success: (data, _, resp) => {
  274. this.setState({
  275. loading: false,
  276. error: false,
  277. rows: this.props.rowsFromData?.(data, this.state.region) ?? data,
  278. pageLinks: resp?.getResponseHeader('Link') ?? '',
  279. });
  280. if (this.props.onLoad) {
  281. this.props.onLoad();
  282. }
  283. },
  284. error: res => {
  285. this.setState({
  286. loading: false,
  287. error: true,
  288. });
  289. if (this.props.onError) {
  290. this.props.onError(res);
  291. }
  292. },
  293. });
  294. };
  295. // TODO(dcramer): doesnt correctly respect filters without query strings
  296. onSearch = (e: React.FormEvent) => {
  297. const queryParams = this.props.location?.query ?? {};
  298. const query = {
  299. query: this.state.query,
  300. cursor: '', // reset cursor for pagination since we have a new search
  301. };
  302. e.preventDefault();
  303. if (this.props.useQueryString) {
  304. browserHistory.push({
  305. pathname: this.props.path,
  306. query: {...queryParams, ...query},
  307. });
  308. } else {
  309. this.setState({loading: true, ...query}, this.fetchData);
  310. }
  311. };
  312. onQueryChange = (evt: React.ChangeEvent<HTMLInputElement>) => {
  313. this.setState({query: evt.target.value});
  314. };
  315. onCursor = (cursor: string | undefined) => {
  316. // NOTE: Sets pagination cursor and refetches data
  317. this.setState({cursor: cursor ?? '', loading: true}, this.fetchData);
  318. };
  319. renderLoading() {
  320. return (
  321. <tr>
  322. <td colSpan={this.props.columns.length}>
  323. <LoadingIndicator>Hold on to your butts!</LoadingIndicator>
  324. </td>
  325. </tr>
  326. );
  327. }
  328. renderError() {
  329. return (
  330. <tr>
  331. <td colSpan={this.props.columns.length}>
  332. <ErrorAlert type="error" showIcon>
  333. Something bad happened :/
  334. </ErrorAlert>
  335. </td>
  336. </tr>
  337. );
  338. }
  339. renderNoResults() {
  340. return (
  341. <tr>
  342. <td colSpan={this.props.columns.length}>
  343. <EmptyMessage>No results</EmptyMessage>
  344. </td>
  345. </tr>
  346. );
  347. }
  348. renderResults() {
  349. return this.state.rows.map((row, i) => (
  350. <tr key={this.props.keyForRow?.(row) ?? i}>
  351. {this.props.columnsForRow?.(row, this.state.rows, this.state)}
  352. </tr>
  353. ));
  354. }
  355. render() {
  356. const {
  357. filters,
  358. useQueryString,
  359. sortOptions,
  360. path,
  361. location,
  362. columns,
  363. hasPagination,
  364. hasSearch,
  365. inPanel,
  366. panelTitle,
  367. } = this.props;
  368. const ensuredFilters = filters ?? {};
  369. const resultTable = (
  370. <ResultTable>
  371. <thead>
  372. <tr>{columns}</tr>
  373. </thead>
  374. <tbody>
  375. {this.state.loading
  376. ? this.renderLoading()
  377. : this.state.error
  378. ? this.renderError()
  379. : this.state.rows.length === 0
  380. ? this.renderNoResults()
  381. : this.renderResults()}
  382. </tbody>
  383. </ResultTable>
  384. );
  385. const CustomPanel = inPanel;
  386. const table = CustomPanel ? (
  387. CustomPanel === true ? (
  388. <Panel>
  389. {panelTitle && (
  390. <PanelHeader hasButtons={!!this.props.buttonGroup}>
  391. {panelTitle}
  392. {this.props.buttonGroup}
  393. </PanelHeader>
  394. )}
  395. {resultTable}
  396. </Panel>
  397. ) : (
  398. <CustomPanel>{resultTable}</CustomPanel>
  399. )
  400. ) : (
  401. resultTable
  402. );
  403. return (
  404. <ResultGridContainer data-test-id="result-grid">
  405. <SortSearchForm onSubmit={this.onSearch}>
  406. {this.props.isRegional && (
  407. <CompactSelect
  408. triggerProps={{prefix: t('Region')}}
  409. value={this.state.region ? this.state.region.url : undefined}
  410. options={ConfigStore.get('regions').map((r: any) => ({
  411. label: r.name,
  412. value: r.url,
  413. }))}
  414. onChange={opt => {
  415. const region = ConfigStore.get('regions').find(
  416. (r: any) => r.url === opt.value
  417. );
  418. if (region === undefined) {
  419. return;
  420. }
  421. this.setState(
  422. {
  423. region,
  424. },
  425. this.fetchData
  426. );
  427. }}
  428. />
  429. )}
  430. {sortOptions && sortOptions.length > 0 && (
  431. <SortBy
  432. options={sortOptions ?? []}
  433. value={this.state.sortBy}
  434. path={path}
  435. location={location}
  436. />
  437. )}
  438. {hasSearch && (
  439. <SearchBar>
  440. <SearchInput
  441. type="text"
  442. placeholder="Search"
  443. name="query"
  444. autoComplete="off"
  445. value={this.state.query}
  446. onChange={this.onQueryChange}
  447. />
  448. <Button
  449. type="submit"
  450. icon={<IconSearch />}
  451. priority="primary"
  452. size="sm"
  453. aria-label={t('Search')}
  454. />
  455. </SearchBar>
  456. )}
  457. </SortSearchForm>
  458. {Object.keys(ensuredFilters).length > 0 && (
  459. <FilterList>
  460. {Object.keys(ensuredFilters).map(filterKey => (
  461. <Filter
  462. key={filterKey}
  463. queryKey={filterKey}
  464. value={extractQuery(this.state.filters[filterKey]!)}
  465. path={path}
  466. location={location}
  467. {...ensuredFilters[filterKey]!}
  468. />
  469. ))}
  470. </FilterList>
  471. )}
  472. {table}
  473. {hasPagination && this.state.pageLinks && (
  474. <StyledPagination
  475. pageLinks={this.state.pageLinks}
  476. onCursor={useQueryString ? undefined : this.onCursor}
  477. />
  478. )}
  479. </ResultGridContainer>
  480. );
  481. }
  482. }
  483. const ResultGridContainer = styled('div')``;
  484. const SortSearchForm = styled('form')`
  485. display: flex;
  486. gap: ${space(1.5)};
  487. &:not(:empty) {
  488. margin-bottom: ${space(1)};
  489. }
  490. /* Gross hack to fix z-index of dropdowns on top of each other */
  491. > div > button + div {
  492. z-index: ${p => p.theme.zIndex.dropdownAutocomplete.menu + 2};
  493. }
  494. `;
  495. const FilterList = styled('div')`
  496. width: 100%;
  497. margin-bottom: ${space(1)};
  498. display: flex;
  499. gap: ${space(0.5)};
  500. flex-wrap: wrap;
  501. align-items: center;
  502. /* Gross hack to fix z-index of dropdowns on top of each other */
  503. > div > button + div {
  504. z-index: ${p => p.theme.zIndex.dropdownAutocomplete.menu + 2};
  505. }
  506. `;
  507. const SearchBar = styled('div')`
  508. width: 100%;
  509. display: flex;
  510. gap: ${space(0.5)};
  511. align-items: center;
  512. `;
  513. export const SearchInput = styled(Input)`
  514. font-size: ${p => p.theme.fontSizeMedium};
  515. padding: ${space(0.5)} ${space(1)};
  516. height: 100%;
  517. &:focus-visible {
  518. box-shadow: inset 0 0 0 1px ${p => p.theme.focusBorder};
  519. }
  520. `;
  521. const StyledPagination = styled(Pagination)`
  522. margin-bottom: ${space(3)};
  523. `;
  524. const ErrorAlert = styled(Alert)`
  525. margin-top: ${space(0.5)};
  526. margin-bottom: ${space(1.5)};
  527. `;
  528. export default withApi(
  529. // TODO(TS): Type cast added as part of react 18 upgrade, can remove after?
  530. withSentryRouter(ResultGrid) as React.ComponentType<
  531. Omit<ResultGridProps, keyof WithRouterProps>
  532. >
  533. );