table.tsx 16 KB

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