table.tsx 13 KB

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