table.tsx 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438
  1. import {Component, Fragment} from 'react';
  2. import {browserHistory} from 'react-router';
  3. import styled from '@emotion/styled';
  4. import {Location, LocationDescriptorObject} from 'history';
  5. import {addSuccessMessage} from 'sentry/actionCreators/indicator';
  6. import {openModal} from 'sentry/actionCreators/modal';
  7. import GuideAnchor from 'sentry/components/assistant/guideAnchor';
  8. import GridEditable, {
  9. COL_WIDTH_UNDEFINED,
  10. GridColumn,
  11. } from 'sentry/components/gridEditable';
  12. import SortLink from 'sentry/components/gridEditable/sortLink';
  13. import Link from 'sentry/components/links/link';
  14. import Pagination from 'sentry/components/pagination';
  15. import {Tooltip} from 'sentry/components/tooltip';
  16. import {IconStar} from 'sentry/icons';
  17. import {tct} from 'sentry/locale';
  18. import {Organization, Project} from 'sentry/types';
  19. import DiscoverQuery, {
  20. TableData,
  21. TableDataRow,
  22. } from 'sentry/utils/discover/discoverQuery';
  23. import EventView, {isFieldSortable, MetaType} from 'sentry/utils/discover/eventView';
  24. import {getFieldRenderer} from 'sentry/utils/discover/fieldRenderers';
  25. import {fieldAlignment, getAggregateAlias} from 'sentry/utils/discover/fields';
  26. import {VisuallyCompleteWithData} from 'sentry/utils/performanceForSentry';
  27. import CellAction, {Actions, updateQuery} from 'sentry/views/discover/table/cellAction';
  28. import {TableColumn} from 'sentry/views/discover/table/types';
  29. import TransactionThresholdModal, {
  30. modalCss,
  31. TransactionThresholdMetric,
  32. } from 'sentry/views/performance/transactionSummary/transactionThresholdModal';
  33. import {
  34. normalizeSearchConditionsWithTransactionName,
  35. transactionSummaryRouteWithQuery,
  36. } from 'sentry/views/performance/transactionSummary/utils';
  37. const COLUMN_TITLES = ['endpoint', 'tpm', 'p50(duration)', 'p95(duration)'];
  38. import {getProjectID} from 'sentry/views/performance/utils';
  39. import {
  40. createUnnamedTransactionsDiscoverTarget,
  41. UNPARAMETERIZED_TRANSACTION,
  42. } from '../utils/createUnnamedTransactionsDiscoverTarget';
  43. type Props = {
  44. eventView: EventView;
  45. location: Location;
  46. organization: Organization;
  47. projects: Project[];
  48. setError: (msg: string | undefined) => void;
  49. withStaticFilters: boolean;
  50. columnTitles?: string[];
  51. summaryConditions?: string;
  52. };
  53. type State = {
  54. transaction: string | undefined;
  55. transactionThreshold: number | undefined;
  56. transactionThresholdMetric: TransactionThresholdMetric | undefined;
  57. widths: number[];
  58. };
  59. class _Table extends Component<Props, State> {
  60. state: State = {
  61. widths: [],
  62. transaction: undefined,
  63. transactionThreshold: undefined,
  64. transactionThresholdMetric: undefined,
  65. };
  66. handleCellAction = (column: TableColumn<keyof TableDataRow>, dataRow: TableDataRow) => {
  67. return (action: Actions, value: React.ReactText) => {
  68. const {eventView, location, organization, projects} = this.props;
  69. if (action === Actions.EDIT_THRESHOLD) {
  70. const project_threshold = dataRow.project_threshold_config;
  71. const transactionName = dataRow.transaction as string;
  72. const projectID = getProjectID(dataRow, projects);
  73. openModal(
  74. modalProps => (
  75. <TransactionThresholdModal
  76. {...modalProps}
  77. organization={organization}
  78. transactionName={transactionName}
  79. eventView={eventView}
  80. project={projectID}
  81. transactionThreshold={project_threshold[1]}
  82. transactionThresholdMetric={project_threshold[0]}
  83. onApply={(threshold, metric) => {
  84. if (
  85. threshold !== project_threshold[1] ||
  86. metric !== project_threshold[0]
  87. ) {
  88. this.setState({
  89. transaction: transactionName,
  90. transactionThreshold: threshold,
  91. transactionThresholdMetric: metric,
  92. });
  93. }
  94. addSuccessMessage(
  95. tct('[transactionName] updated successfully', {
  96. transactionName,
  97. })
  98. );
  99. }}
  100. />
  101. ),
  102. {modalCss, closeEvents: 'escape-key'}
  103. );
  104. return;
  105. }
  106. const searchConditions = normalizeSearchConditionsWithTransactionName(
  107. eventView.query
  108. );
  109. updateQuery(searchConditions, action, column, value);
  110. browserHistory.push({
  111. pathname: location.pathname,
  112. query: {
  113. ...location.query,
  114. cursor: undefined,
  115. query: searchConditions.formatString(),
  116. },
  117. });
  118. };
  119. };
  120. renderBodyCell(
  121. tableData: TableData | null,
  122. column: TableColumn<keyof TableDataRow>,
  123. dataRow: TableDataRow
  124. ): React.ReactNode {
  125. const {eventView, organization, projects, location, withStaticFilters} = this.props;
  126. if (!tableData || !tableData.meta) {
  127. return dataRow[column.key];
  128. }
  129. const tableMeta = tableData.meta;
  130. const field = String(column.key);
  131. const fieldRenderer = getFieldRenderer(field, tableMeta, false);
  132. const rendered = fieldRenderer(dataRow, {organization, location});
  133. const allowActions = [
  134. Actions.ADD,
  135. Actions.EXCLUDE,
  136. Actions.SHOW_GREATER_THAN,
  137. Actions.SHOW_LESS_THAN,
  138. Actions.EDIT_THRESHOLD,
  139. ];
  140. const cellActions = withStaticFilters ? [] : allowActions;
  141. if (field === 'transaction') {
  142. const projectID = getProjectID(dataRow, projects);
  143. const summaryView = eventView.clone();
  144. let prefix = '';
  145. if (dataRow['http.method']) {
  146. summaryView.additionalConditions.setFilterValues('http.method', [
  147. dataRow['http.method'] as string,
  148. ]);
  149. prefix = `${dataRow['http.method']} `;
  150. }
  151. summaryView.query = summaryView.getQueryWithAdditionalConditions();
  152. const isUnparameterizedRow = dataRow.transaction === UNPARAMETERIZED_TRANSACTION;
  153. const target = isUnparameterizedRow
  154. ? createUnnamedTransactionsDiscoverTarget({
  155. organization,
  156. location,
  157. })
  158. : transactionSummaryRouteWithQuery({
  159. orgSlug: organization.slug,
  160. transaction: String(dataRow.transaction) || '',
  161. query: summaryView.generateQueryStringObject(),
  162. projectID,
  163. });
  164. return (
  165. <CellAction
  166. column={column}
  167. dataRow={dataRow}
  168. handleCellAction={this.handleCellAction(column, dataRow)}
  169. allowActions={cellActions}
  170. >
  171. <Link to={target} style={{display: `block`, width: `100%`}}>
  172. {prefix}
  173. {dataRow.transaction}
  174. </Link>
  175. </CellAction>
  176. );
  177. }
  178. if (field === 'project') {
  179. return null;
  180. }
  181. if (field.startsWith('team_key_transaction')) {
  182. // don't display per cell actions for team_key_transaction
  183. return rendered;
  184. }
  185. const fieldName = getAggregateAlias(field);
  186. const value = dataRow[fieldName];
  187. if (tableMeta[fieldName] === 'integer' && typeof value === 'number' && value > 999) {
  188. return (
  189. <Tooltip
  190. title={value.toLocaleString()}
  191. containerDisplayMode="block"
  192. position="right"
  193. >
  194. <CellAction
  195. column={column}
  196. dataRow={dataRow}
  197. handleCellAction={this.handleCellAction(column, dataRow)}
  198. allowActions={cellActions}
  199. >
  200. {rendered}
  201. </CellAction>
  202. </Tooltip>
  203. );
  204. }
  205. return (
  206. <CellAction
  207. column={column}
  208. dataRow={dataRow}
  209. handleCellAction={this.handleCellAction(column, dataRow)}
  210. allowActions={cellActions}
  211. >
  212. {rendered}
  213. </CellAction>
  214. );
  215. }
  216. renderBodyCellWithData = (tableData: TableData | null) => {
  217. return (
  218. column: TableColumn<keyof TableDataRow>,
  219. dataRow: TableDataRow
  220. ): React.ReactNode => this.renderBodyCell(tableData, column, dataRow);
  221. };
  222. renderHeadCell(
  223. tableMeta: TableData['meta'],
  224. column: TableColumn<keyof TableDataRow>,
  225. title: React.ReactNode
  226. ): React.ReactNode {
  227. const {eventView, location} = this.props;
  228. const align = fieldAlignment(column.name, column.type, tableMeta);
  229. const field = {field: column.name, width: column.width};
  230. const aggregateAliasTableMeta: MetaType = {};
  231. if (tableMeta) {
  232. Object.keys(tableMeta).forEach(key => {
  233. aggregateAliasTableMeta[getAggregateAlias(key)] = tableMeta[key];
  234. });
  235. }
  236. function generateSortLink(): LocationDescriptorObject | undefined {
  237. if (!tableMeta) {
  238. return undefined;
  239. }
  240. const nextEventView = eventView.sortOnField(field, aggregateAliasTableMeta);
  241. const queryStringObject = nextEventView.generateQueryStringObject();
  242. return {
  243. ...location,
  244. query: {...location.query, sort: queryStringObject.sort},
  245. };
  246. }
  247. const currentSort = eventView.sortForField(field, aggregateAliasTableMeta);
  248. const canSort = isFieldSortable(field, aggregateAliasTableMeta);
  249. const currentSortKind = currentSort ? currentSort.kind : undefined;
  250. const sortLink = (
  251. <SortLink
  252. align={align}
  253. title={title || field.field}
  254. direction={currentSortKind}
  255. canSort={canSort}
  256. generateSortLink={generateSortLink}
  257. />
  258. );
  259. if (field.field.startsWith('user_misery')) {
  260. return (
  261. <GuideAnchor target="project_transaction_threshold" position="top">
  262. {sortLink}
  263. </GuideAnchor>
  264. );
  265. }
  266. return sortLink;
  267. }
  268. renderHeadCellWithMeta = (tableMeta: TableData['meta']) => {
  269. const columnTitles = this.props.columnTitles ?? COLUMN_TITLES;
  270. return (column: TableColumn<keyof TableDataRow>, index: number): React.ReactNode =>
  271. this.renderHeadCell(tableMeta, column, columnTitles[index]);
  272. };
  273. renderPrependCellWithData = (tableData: TableData | null) => {
  274. const {eventView} = this.props;
  275. const teamKeyTransactionColumn = eventView
  276. .getColumns()
  277. .find((col: TableColumn<React.ReactText>) => col.name === 'team_key_transaction');
  278. return (isHeader: boolean, dataRow?: any) => {
  279. if (teamKeyTransactionColumn) {
  280. if (isHeader) {
  281. const star = (
  282. <TeamKeyTransactionWrapper>
  283. <IconStar
  284. key="keyTransaction"
  285. color="yellow400"
  286. isSolid
  287. data-test-id="team-key-transaction-header"
  288. />
  289. </TeamKeyTransactionWrapper>
  290. );
  291. return [this.renderHeadCell(tableData?.meta, teamKeyTransactionColumn, star)];
  292. }
  293. return [this.renderBodyCell(tableData, teamKeyTransactionColumn, dataRow)];
  294. }
  295. return [];
  296. };
  297. };
  298. handleResizeColumn = (columnIndex: number, nextColumn: GridColumn) => {
  299. const widths: number[] = [...this.state.widths];
  300. widths[columnIndex] = nextColumn.width
  301. ? Number(nextColumn.width)
  302. : COL_WIDTH_UNDEFINED;
  303. this.setState({widths});
  304. };
  305. getSortedEventView() {
  306. const {eventView} = this.props;
  307. return eventView.withSorts([
  308. {
  309. field: 'team_key_transaction',
  310. kind: 'desc',
  311. },
  312. ...eventView.sorts,
  313. ]);
  314. }
  315. render() {
  316. const {eventView, organization, location, setError} = this.props;
  317. const {widths, transaction, transactionThreshold} = this.state;
  318. const columnOrder = eventView
  319. .getColumns()
  320. // remove team_key_transactions from the column order as we'll be rendering it
  321. // via a prepended column
  322. .filter(
  323. (col: TableColumn<React.ReactText>) =>
  324. col.name !== 'team_key_transaction' &&
  325. !col.name.startsWith('count_miserable') &&
  326. col.name !== 'project_threshold_config' &&
  327. col.name !== 'project' &&
  328. col.name !== 'http.method'
  329. )
  330. .map((col: TableColumn<React.ReactText>, i: number) => {
  331. if (typeof widths[i] === 'number') {
  332. return {...col, width: widths[i]};
  333. }
  334. return col;
  335. });
  336. const sortedEventView = this.getSortedEventView();
  337. const columnSortBy = sortedEventView.getSorts();
  338. const prependColumnWidths = ['max-content'];
  339. return (
  340. <GuideAnchor target="performance_table" position="top-start">
  341. <div data-test-id="performance-table">
  342. <DiscoverQuery
  343. eventView={sortedEventView}
  344. orgSlug={organization.slug}
  345. location={location}
  346. setError={error => setError(error?.message)}
  347. referrer="api.performance.landing-table"
  348. transactionName={transaction}
  349. transactionThreshold={transactionThreshold}
  350. queryExtras={{dataset: 'metrics'}}
  351. >
  352. {({pageLinks, isLoading, tableData}) => (
  353. <Fragment>
  354. <VisuallyCompleteWithData
  355. id="PerformanceTable"
  356. hasData={!isLoading && !!tableData?.data && tableData.data.length > 0}
  357. >
  358. <GridEditable
  359. isLoading={isLoading}
  360. data={tableData ? tableData.data : []}
  361. columnOrder={columnOrder}
  362. columnSortBy={columnSortBy}
  363. grid={{
  364. onResizeColumn: this.handleResizeColumn,
  365. renderHeadCell: this.renderHeadCellWithMeta(tableData?.meta) as any,
  366. renderBodyCell: this.renderBodyCellWithData(tableData) as any,
  367. renderPrependColumns: this.renderPrependCellWithData(
  368. tableData
  369. ) as any,
  370. prependColumnWidths,
  371. }}
  372. location={location}
  373. />
  374. </VisuallyCompleteWithData>
  375. <Pagination pageLinks={pageLinks} />
  376. </Fragment>
  377. )}
  378. </DiscoverQuery>
  379. </div>
  380. </GuideAnchor>
  381. );
  382. }
  383. }
  384. function Table(props: Omit<Props, 'summaryConditions'> & {summaryConditions?: string}) {
  385. const summaryConditions =
  386. props.summaryConditions ?? props.eventView.getQueryWithAdditionalConditions();
  387. return <_Table {...props} summaryConditions={summaryConditions} />;
  388. }
  389. // Align the contained IconStar with the IconStar buttons in individual table
  390. // rows, which have 2px padding + 1px border.
  391. const TeamKeyTransactionWrapper = styled('div')`
  392. padding: 3px;
  393. `;
  394. export default Table;