table.tsx 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482
  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 {getMEPQueryParams} from './landing/widgets/utils';
  33. import TransactionThresholdModal, {
  34. modalCss,
  35. TransactionThresholdMetric,
  36. } from './transactionSummary/transactionThresholdModal';
  37. import {
  38. normalizeSearchConditionsWithTransactionName,
  39. transactionSummaryRouteWithQuery,
  40. } from './transactionSummary/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. if (dataRow['http.method']) {
  154. summaryView.additionalConditions.setFilterValues('http.method', [
  155. dataRow['http.method'] as string,
  156. ]);
  157. }
  158. summaryView.query = summaryView.getQueryWithAdditionalConditions();
  159. const isUnparameterizedRow = dataRow.transaction === UNPARAMETERIZED_TRANSACTION;
  160. const target = isUnparameterizedRow
  161. ? createUnnamedTransactionsDiscoverTarget({
  162. organization,
  163. location,
  164. })
  165. : transactionSummaryRouteWithQuery({
  166. orgSlug: organization.slug,
  167. transaction: String(dataRow.transaction) || '',
  168. query: summaryView.generateQueryStringObject(),
  169. projectID,
  170. });
  171. return (
  172. <CellAction
  173. column={column}
  174. dataRow={dataRow}
  175. handleCellAction={this.handleCellAction(column, dataRow)}
  176. allowActions={cellActions}
  177. >
  178. <Link
  179. to={target}
  180. onClick={this.handleSummaryClick}
  181. style={{display: `block`, width: `100%`}}
  182. >
  183. {rendered}
  184. </Link>
  185. </CellAction>
  186. );
  187. }
  188. if (field.startsWith('team_key_transaction')) {
  189. // don't display per cell actions for team_key_transaction
  190. return rendered;
  191. }
  192. const fieldName = getAggregateAlias(field);
  193. const value = dataRow[fieldName];
  194. if (tableMeta[fieldName] === 'integer' && defined(value) && value > 999) {
  195. return (
  196. <Tooltip
  197. title={value.toLocaleString()}
  198. containerDisplayMode="block"
  199. position="right"
  200. >
  201. <CellAction
  202. column={column}
  203. dataRow={dataRow}
  204. handleCellAction={this.handleCellAction(column, dataRow)}
  205. allowActions={cellActions}
  206. >
  207. {rendered}
  208. </CellAction>
  209. </Tooltip>
  210. );
  211. }
  212. return (
  213. <CellAction
  214. column={column}
  215. dataRow={dataRow}
  216. handleCellAction={this.handleCellAction(column, dataRow)}
  217. allowActions={cellActions}
  218. >
  219. {rendered}
  220. </CellAction>
  221. );
  222. }
  223. renderBodyCellWithData = (tableData: TableData | null) => {
  224. return (
  225. column: TableColumn<keyof TableDataRow>,
  226. dataRow: TableDataRow
  227. ): React.ReactNode => this.renderBodyCell(tableData, column, dataRow);
  228. };
  229. onSortClick(currentSortKind?: string, currentSortField?: string) {
  230. const {organization} = this.props;
  231. trackAdvancedAnalyticsEvent('performance_views.landingv2.transactions.sort', {
  232. organization,
  233. field: currentSortField,
  234. direction: currentSortKind,
  235. });
  236. }
  237. paginationAnalyticsEvent = (direction: string) => {
  238. const {organization} = this.props;
  239. trackAdvancedAnalyticsEvent('performance_views.landingv3.table_pagination', {
  240. organization,
  241. direction,
  242. });
  243. };
  244. renderHeadCell(
  245. tableMeta: TableData['meta'],
  246. column: TableColumn<keyof TableDataRow>,
  247. title: React.ReactNode
  248. ): React.ReactNode {
  249. const {eventView, location} = this.props;
  250. const align = fieldAlignment(column.name, column.type, tableMeta);
  251. const field = {field: column.name, width: column.width};
  252. const aggregateAliasTableMeta: MetaType = {};
  253. if (tableMeta) {
  254. Object.keys(tableMeta).forEach(key => {
  255. aggregateAliasTableMeta[getAggregateAlias(key)] = tableMeta[key];
  256. });
  257. }
  258. function generateSortLink(): LocationDescriptorObject | undefined {
  259. if (!tableMeta) {
  260. return undefined;
  261. }
  262. const nextEventView = eventView.sortOnField(field, aggregateAliasTableMeta);
  263. const queryStringObject = nextEventView.generateQueryStringObject();
  264. return {
  265. ...location,
  266. query: {...location.query, sort: queryStringObject.sort},
  267. };
  268. }
  269. const currentSort = eventView.sortForField(field, aggregateAliasTableMeta);
  270. const canSort = isFieldSortable(field, aggregateAliasTableMeta);
  271. const currentSortKind = currentSort ? currentSort.kind : undefined;
  272. const currentSortField = currentSort ? currentSort.field : undefined;
  273. const sortLink = (
  274. <SortLink
  275. align={align}
  276. title={title || field.field}
  277. direction={currentSortKind}
  278. canSort={canSort}
  279. generateSortLink={generateSortLink}
  280. onClick={() => this.onSortClick(currentSortKind, currentSortField)}
  281. />
  282. );
  283. if (field.field.startsWith('user_misery')) {
  284. return (
  285. <GuideAnchor target="project_transaction_threshold" position="top">
  286. {sortLink}
  287. </GuideAnchor>
  288. );
  289. }
  290. return sortLink;
  291. }
  292. renderHeadCellWithMeta = (tableMeta: TableData['meta']) => {
  293. const columnTitles = this.props.columnTitles ?? COLUMN_TITLES;
  294. return (column: TableColumn<keyof TableDataRow>, index: number): React.ReactNode =>
  295. this.renderHeadCell(tableMeta, column, columnTitles[index]);
  296. };
  297. renderPrependCellWithData = (tableData: TableData | null) => {
  298. const {eventView} = this.props;
  299. const teamKeyTransactionColumn = eventView
  300. .getColumns()
  301. .find((col: TableColumn<React.ReactText>) => col.name === 'team_key_transaction');
  302. return (isHeader: boolean, dataRow?: any) => {
  303. if (teamKeyTransactionColumn) {
  304. if (isHeader) {
  305. const star = (
  306. <TeamKeyTransactionWrapper>
  307. <IconStar
  308. key="keyTransaction"
  309. color="yellow400"
  310. isSolid
  311. data-test-id="team-key-transaction-header"
  312. />
  313. </TeamKeyTransactionWrapper>
  314. );
  315. return [this.renderHeadCell(tableData?.meta, teamKeyTransactionColumn, star)];
  316. }
  317. return [this.renderBodyCell(tableData, teamKeyTransactionColumn, dataRow)];
  318. }
  319. return [];
  320. };
  321. };
  322. handleSummaryClick = () => {
  323. const {organization, location, projects} = this.props;
  324. trackAdvancedAnalyticsEvent('performance_views.overview.navigate.summary', {
  325. organization,
  326. project_platforms: getSelectedProjectPlatforms(location, projects),
  327. });
  328. };
  329. handleResizeColumn = (columnIndex: number, nextColumn: GridColumn) => {
  330. const widths: number[] = [...this.state.widths];
  331. widths[columnIndex] = nextColumn.width
  332. ? Number(nextColumn.width)
  333. : COL_WIDTH_UNDEFINED;
  334. this.setState({widths});
  335. };
  336. getSortedEventView() {
  337. const {eventView} = this.props;
  338. return eventView.withSorts([
  339. {
  340. field: 'team_key_transaction',
  341. kind: 'desc',
  342. },
  343. ...eventView.sorts,
  344. ]);
  345. }
  346. render() {
  347. const {eventView, organization, location, setError} = this.props;
  348. const {widths, transaction, transactionThreshold} = this.state;
  349. const columnOrder = eventView
  350. .getColumns()
  351. // remove team_key_transactions from the column order as we'll be rendering it
  352. // via a prepended column
  353. .filter(
  354. (col: TableColumn<React.ReactText>) =>
  355. col.name !== 'team_key_transaction' &&
  356. !col.name.startsWith('count_miserable') &&
  357. col.name !== 'project_threshold_config'
  358. )
  359. .map((col: TableColumn<React.ReactText>, i: number) => {
  360. if (typeof widths[i] === 'number') {
  361. return {...col, width: widths[i]};
  362. }
  363. return col;
  364. });
  365. const sortedEventView = this.getSortedEventView();
  366. const columnSortBy = sortedEventView.getSorts();
  367. const prependColumnWidths = ['max-content'];
  368. return (
  369. <GuideAnchor target="performance_table" position="top-start">
  370. <div data-test-id="performance-table">
  371. <MEPConsumer>
  372. {value => {
  373. return (
  374. <DiscoverQuery
  375. eventView={sortedEventView}
  376. orgSlug={organization.slug}
  377. location={location}
  378. setError={error => setError(error?.message)}
  379. referrer="api.performance.landing-table"
  380. transactionName={transaction}
  381. transactionThreshold={transactionThreshold}
  382. queryExtras={getMEPQueryParams(value)}
  383. >
  384. {({pageLinks, isLoading, tableData}) => (
  385. <Fragment>
  386. <VisuallyCompleteWithData
  387. id="PerformanceTable"
  388. hasData={
  389. !isLoading && !!tableData?.data && tableData.data.length > 0
  390. }
  391. >
  392. <GridEditable
  393. isLoading={isLoading}
  394. data={tableData ? tableData.data : []}
  395. columnOrder={columnOrder}
  396. columnSortBy={columnSortBy}
  397. grid={{
  398. onResizeColumn: this.handleResizeColumn,
  399. renderHeadCell: this.renderHeadCellWithMeta(
  400. tableData?.meta
  401. ) as any,
  402. renderBodyCell: this.renderBodyCellWithData(tableData) as any,
  403. renderPrependColumns: this.renderPrependCellWithData(
  404. tableData
  405. ) as any,
  406. prependColumnWidths,
  407. }}
  408. location={location}
  409. />
  410. </VisuallyCompleteWithData>
  411. <Pagination
  412. pageLinks={pageLinks}
  413. paginationAnalyticsEvent={this.paginationAnalyticsEvent}
  414. />
  415. </Fragment>
  416. )}
  417. </DiscoverQuery>
  418. );
  419. }}
  420. </MEPConsumer>
  421. </div>
  422. </GuideAnchor>
  423. );
  424. }
  425. }
  426. function Table(props: Omit<Props, 'summaryConditions'> & {summaryConditions?: string}) {
  427. const summaryConditions =
  428. props.summaryConditions ?? props.eventView.getQueryWithAdditionalConditions();
  429. return <_Table {...props} summaryConditions={summaryConditions} />;
  430. }
  431. // Align the contained IconStar with the IconStar buttons in individual table
  432. // rows, which have 2px padding + 1px border.
  433. const TeamKeyTransactionWrapper = styled('div')`
  434. padding: 3px;
  435. `;
  436. export default Table;