table.tsx 15 KB

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