table.tsx 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438
  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 DiscoverOrMetricsQuery from 'sentry/utils/discover/discoverOrMetricsQuery';
  21. import {TableData, TableDataRow} from 'sentry/utils/discover/discoverQuery';
  22. import EventView, {EventData, isFieldSortable} from 'sentry/utils/discover/eventView';
  23. import {getFieldRenderer} from 'sentry/utils/discover/fieldRenderers';
  24. import {fieldAlignment, getAggregateAlias} from 'sentry/utils/discover/fields';
  25. import {MutableSearch} from 'sentry/utils/tokenizeSearch';
  26. import CellAction, {Actions, updateQuery} from 'sentry/views/eventsV2/table/cellAction';
  27. import {TableColumn} from 'sentry/views/eventsV2/table/types';
  28. import TransactionThresholdModal, {
  29. modalCss,
  30. TransactionThresholdMetric,
  31. } from './transactionSummary/transactionThresholdModal';
  32. import {transactionSummaryRouteWithQuery} from './transactionSummary/utils';
  33. import {COLUMN_TITLES} from './data';
  34. export function getProjectID(
  35. eventData: EventData,
  36. projects: Project[]
  37. ): string | undefined {
  38. const projectSlug = (eventData?.project as string) || undefined;
  39. if (typeof projectSlug === undefined) {
  40. return undefined;
  41. }
  42. const project = projects.find(currentProject => currentProject.slug === projectSlug);
  43. if (!project) {
  44. return undefined;
  45. }
  46. return project.id;
  47. }
  48. type Props = {
  49. eventView: EventView;
  50. location: Location;
  51. organization: Organization;
  52. projects: Project[];
  53. setError: (msg: string | undefined) => void;
  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 React.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. trackAdvancedAnalyticsEvent('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, backdrop: 'static'}
  111. );
  112. return;
  113. }
  114. const searchConditions = new MutableSearch(eventView.query);
  115. // remove any event.type queries since it is implied to apply to only transactions
  116. searchConditions.removeFilter('event.type');
  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} = 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);
  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. if (field === 'transaction') {
  149. const projectID = getProjectID(dataRow, projects);
  150. const summaryView = eventView.clone();
  151. if (dataRow['http.method']) {
  152. summaryView.additionalConditions.setFilterValues('http.method', [
  153. dataRow['http.method'] as string,
  154. ]);
  155. }
  156. summaryView.query = summaryView.getQueryWithAdditionalConditions();
  157. const target = transactionSummaryRouteWithQuery({
  158. orgSlug: organization.slug,
  159. transaction: String(dataRow.transaction) || '',
  160. query: summaryView.generateQueryStringObject(),
  161. projectID,
  162. });
  163. return (
  164. <CellAction
  165. column={column}
  166. dataRow={dataRow}
  167. handleCellAction={this.handleCellAction(column, dataRow)}
  168. allowActions={allowActions}
  169. >
  170. <Link
  171. to={target}
  172. onClick={this.handleSummaryClick}
  173. style={{display: `block`, width: `100%`}}
  174. >
  175. {rendered}
  176. </Link>
  177. </CellAction>
  178. );
  179. }
  180. if (field.startsWith('team_key_transaction')) {
  181. // don't display per cell actions for team_key_transaction
  182. return rendered;
  183. }
  184. const fieldName = getAggregateAlias(field);
  185. const value = dataRow[fieldName];
  186. if (tableMeta[fieldName] === 'integer' && defined(value) && value > 999) {
  187. return (
  188. <Tooltip
  189. title={value.toLocaleString()}
  190. containerDisplayMode="block"
  191. position="right"
  192. >
  193. <CellAction
  194. column={column}
  195. dataRow={dataRow}
  196. handleCellAction={this.handleCellAction(column, dataRow)}
  197. allowActions={allowActions}
  198. >
  199. {rendered}
  200. </CellAction>
  201. </Tooltip>
  202. );
  203. }
  204. return (
  205. <CellAction
  206. column={column}
  207. dataRow={dataRow}
  208. handleCellAction={this.handleCellAction(column, dataRow)}
  209. allowActions={allowActions}
  210. >
  211. {rendered}
  212. </CellAction>
  213. );
  214. }
  215. renderBodyCellWithData = (tableData: TableData | null) => {
  216. return (
  217. column: TableColumn<keyof TableDataRow>,
  218. dataRow: TableDataRow
  219. ): React.ReactNode => this.renderBodyCell(tableData, column, dataRow);
  220. };
  221. onSortClick(currentSortKind?: string, currentSortField?: string) {
  222. const {organization} = this.props;
  223. trackAdvancedAnalyticsEvent('performance_views.landingv2.transactions.sort', {
  224. organization,
  225. field: currentSortField,
  226. direction: currentSortKind,
  227. });
  228. }
  229. renderHeadCell(
  230. tableMeta: TableData['meta'],
  231. column: TableColumn<keyof TableDataRow>,
  232. title: React.ReactNode
  233. ): React.ReactNode {
  234. const {eventView, location} = this.props;
  235. const align = fieldAlignment(column.name, column.type, tableMeta);
  236. const field = {field: column.name, width: column.width};
  237. function generateSortLink(): LocationDescriptorObject | undefined {
  238. if (!tableMeta) {
  239. return undefined;
  240. }
  241. const nextEventView = eventView.sortOnField(field, tableMeta);
  242. const queryStringObject = nextEventView.generateQueryStringObject();
  243. return {
  244. ...location,
  245. query: {...location.query, sort: queryStringObject.sort},
  246. };
  247. }
  248. const currentSort = eventView.sortForField(field, tableMeta);
  249. const canSort = isFieldSortable(field, tableMeta);
  250. const currentSortKind = currentSort ? currentSort.kind : undefined;
  251. const currentSortField = currentSort ? currentSort.field : undefined;
  252. const sortLink = (
  253. <SortLink
  254. align={align}
  255. title={title || field.field}
  256. direction={currentSortKind}
  257. canSort={canSort}
  258. generateSortLink={generateSortLink}
  259. onClick={() => this.onSortClick(currentSortKind, currentSortField)}
  260. />
  261. );
  262. if (field.field.startsWith('user_misery')) {
  263. return (
  264. <GuideAnchor target="project_transaction_threshold" position="top">
  265. {sortLink}
  266. </GuideAnchor>
  267. );
  268. }
  269. return sortLink;
  270. }
  271. renderHeadCellWithMeta = (tableMeta: TableData['meta']) => {
  272. const columnTitles = this.props.columnTitles ?? COLUMN_TITLES;
  273. return (column: TableColumn<keyof TableDataRow>, index: number): React.ReactNode =>
  274. this.renderHeadCell(tableMeta, column, columnTitles[index]);
  275. };
  276. renderPrependCellWithData = (tableData: TableData | null) => {
  277. const {eventView} = this.props;
  278. const teamKeyTransactionColumn = eventView
  279. .getColumns()
  280. .find((col: TableColumn<React.ReactText>) => col.name === 'team_key_transaction');
  281. return (isHeader: boolean, dataRow?: any) => {
  282. if (teamKeyTransactionColumn) {
  283. if (isHeader) {
  284. const star = (
  285. <GuideAnchor target="team_key_transaction_header" position="top">
  286. <IconStar
  287. key="keyTransaction"
  288. color="yellow300"
  289. isSolid
  290. data-test-id="team-key-transaction-header"
  291. />
  292. </GuideAnchor>
  293. );
  294. return [this.renderHeadCell(tableData?.meta, teamKeyTransactionColumn, star)];
  295. }
  296. return [this.renderBodyCell(tableData, teamKeyTransactionColumn, dataRow)];
  297. }
  298. return [];
  299. };
  300. };
  301. handleSummaryClick = () => {
  302. const {organization} = this.props;
  303. trackAdvancedAnalyticsEvent('performance_views.overview.navigate.summary', {
  304. organization,
  305. });
  306. };
  307. handleResizeColumn = (columnIndex: number, nextColumn: GridColumn) => {
  308. const widths: number[] = [...this.state.widths];
  309. widths[columnIndex] = nextColumn.width
  310. ? Number(nextColumn.width)
  311. : COL_WIDTH_UNDEFINED;
  312. this.setState({widths});
  313. };
  314. getSortedEventView() {
  315. const {eventView} = this.props;
  316. return eventView.withSorts([
  317. {
  318. field: 'team_key_transaction',
  319. kind: 'desc',
  320. },
  321. ...eventView.sorts,
  322. ]);
  323. }
  324. render() {
  325. const {eventView, organization, location, setError} = this.props;
  326. const {widths, transaction, transactionThreshold, transactionThresholdMetric} =
  327. this.state;
  328. const columnOrder = eventView
  329. .getColumns()
  330. // remove team_key_transactions from the column order as we'll be rendering it
  331. // via a prepended column
  332. .filter(
  333. (col: TableColumn<React.ReactText>) =>
  334. col.name !== 'team_key_transaction' &&
  335. !col.name.startsWith('count_miserable') &&
  336. col.name !== 'project_threshold_config'
  337. )
  338. .map((col: TableColumn<React.ReactText>, i: number) => {
  339. if (typeof widths[i] === 'number') {
  340. return {...col, width: widths[i]};
  341. }
  342. return col;
  343. });
  344. const sortedEventView = this.getSortedEventView();
  345. const columnSortBy = sortedEventView.getSorts();
  346. const prependColumnWidths = ['max-content'];
  347. return (
  348. <div>
  349. <DiscoverOrMetricsQuery
  350. eventView={sortedEventView}
  351. orgSlug={organization.slug}
  352. location={location}
  353. setError={setError}
  354. referrer="api.performance.landing-table"
  355. transactionName={transaction}
  356. transactionThreshold={transactionThreshold}
  357. transactionThresholdMetric={transactionThresholdMetric}
  358. >
  359. {({pageLinks, isLoading, tableData}) => (
  360. <React.Fragment>
  361. <GridEditable
  362. isLoading={isLoading}
  363. data={tableData ? tableData.data : []}
  364. columnOrder={columnOrder}
  365. columnSortBy={columnSortBy}
  366. grid={{
  367. onResizeColumn: this.handleResizeColumn,
  368. renderHeadCell: this.renderHeadCellWithMeta(tableData?.meta) as any,
  369. renderBodyCell: this.renderBodyCellWithData(tableData) as any,
  370. renderPrependColumns: this.renderPrependCellWithData(tableData) as any,
  371. prependColumnWidths,
  372. }}
  373. location={location}
  374. />
  375. <Pagination pageLinks={pageLinks} />
  376. </React.Fragment>
  377. )}
  378. </DiscoverOrMetricsQuery>
  379. </div>
  380. );
  381. }
  382. }
  383. function Table(props: Omit<Props, 'summaryConditions'> & {summaryConditions?: string}) {
  384. const summaryConditions =
  385. props.summaryConditions ?? props.eventView.getQueryWithAdditionalConditions();
  386. return <_Table {...props} summaryConditions={summaryConditions} />;
  387. }
  388. export default Table;