table.tsx 14 KB

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