table.tsx 16 KB

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