table.tsx 16 KB

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