table.tsx 16 KB

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