table.tsx 15 KB

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