table.tsx 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476
  1. import {Component, Fragment} from 'react';
  2. import {browserHistory} from 'react-router';
  3. import styled from '@emotion/styled';
  4. import {Location, LocationDescriptorObject} from 'history';
  5. import GridEditable, {
  6. COL_WIDTH_UNDEFINED,
  7. GridColumn,
  8. } from 'sentry/components/gridEditable';
  9. import SortLink from 'sentry/components/gridEditable/sortLink';
  10. import Link from 'sentry/components/links/link';
  11. import Pagination from 'sentry/components/pagination';
  12. import Tag from 'sentry/components/tag';
  13. import {IconStar} from 'sentry/icons';
  14. import {t} from 'sentry/locale';
  15. import {Organization, Project} from 'sentry/types';
  16. import {trackAnalyticsEvent} from 'sentry/utils/analytics';
  17. import EventView, {
  18. EventData,
  19. EventsMetaType,
  20. isFieldSortable,
  21. } from 'sentry/utils/discover/eventView';
  22. import {getFieldRenderer} from 'sentry/utils/discover/fieldRenderers';
  23. import {
  24. fieldAlignment,
  25. getAggregateAlias,
  26. Sort,
  27. WebVital,
  28. } from 'sentry/utils/discover/fields';
  29. import VitalsDetailsTableQuery, {
  30. TableData,
  31. TableDataRow,
  32. } from 'sentry/utils/performance/vitals/vitalsDetailsTableQuery';
  33. import {MutableSearch} from 'sentry/utils/tokenizeSearch';
  34. import CellAction, {Actions, updateQuery} from 'sentry/views/eventsV2/table/cellAction';
  35. import {TableColumn} from 'sentry/views/eventsV2/table/types';
  36. import {DisplayModes} from '../transactionSummary/transactionOverview/charts';
  37. import {
  38. normalizeSearchConditionsWithTransactionName,
  39. TransactionFilterOptions,
  40. transactionSummaryRouteWithQuery,
  41. } from '../transactionSummary/utils';
  42. import {getSelectedProjectPlatforms} from '../utils';
  43. import {
  44. getVitalDetailTableMehStatusFunction,
  45. getVitalDetailTablePoorStatusFunction,
  46. vitalAbbreviations,
  47. vitalNameFromLocation,
  48. VitalState,
  49. vitalStateColors,
  50. } from './utils';
  51. const COLUMN_TITLES = ['Transaction', 'Project', 'Unique Users', 'Count'];
  52. const getTableColumnTitle = (index: number, vitalName: WebVital) => {
  53. const abbrev = vitalAbbreviations[vitalName];
  54. const titles = [
  55. ...COLUMN_TITLES,
  56. `p50(${abbrev})`,
  57. `p75(${abbrev})`,
  58. `p95(${abbrev})`,
  59. `Status`,
  60. ];
  61. return titles[index];
  62. };
  63. export function getProjectID(
  64. eventData: EventData,
  65. projects: Project[]
  66. ): string | undefined {
  67. const projectSlug = (eventData?.project as string) || undefined;
  68. if (typeof projectSlug === undefined) {
  69. return undefined;
  70. }
  71. const project = projects.find(currentProject => currentProject.slug === projectSlug);
  72. if (!project) {
  73. return undefined;
  74. }
  75. return project.id;
  76. }
  77. type Props = {
  78. eventView: EventView;
  79. location: Location;
  80. organization: Organization;
  81. projects: Project[];
  82. setError: (msg: string | undefined) => void;
  83. summaryConditions: string;
  84. };
  85. type State = {
  86. widths: number[];
  87. };
  88. class Table extends Component<Props, State> {
  89. state: State = {
  90. widths: [],
  91. };
  92. handleCellAction = (column: TableColumn<keyof TableDataRow>) => {
  93. return (action: Actions, value: React.ReactText) => {
  94. const {eventView, location, organization} = this.props;
  95. trackAnalyticsEvent({
  96. eventKey: 'performance_views.overview.cellaction',
  97. eventName: 'Performance Views: Cell Action Clicked',
  98. organization_id: parseInt(organization.id, 10),
  99. action,
  100. });
  101. const searchConditions = normalizeSearchConditionsWithTransactionName(
  102. eventView.query
  103. );
  104. updateQuery(searchConditions, action, column, value);
  105. browserHistory.push({
  106. pathname: location.pathname,
  107. query: {
  108. ...location.query,
  109. cursor: undefined,
  110. query: searchConditions.formatString(),
  111. },
  112. });
  113. };
  114. };
  115. renderBodyCell(
  116. tableData: TableData | null,
  117. column: TableColumn<keyof TableDataRow>,
  118. dataRow: TableDataRow,
  119. vitalName: WebVital
  120. ): React.ReactNode {
  121. const {eventView, organization, projects, location, summaryConditions} = this.props;
  122. if (!tableData || !tableData.meta?.fields) {
  123. return dataRow[column.key];
  124. }
  125. const tableMeta = tableData.meta?.fields;
  126. const field = String(column.key);
  127. if (field === getVitalDetailTablePoorStatusFunction(vitalName)) {
  128. if (dataRow[field]) {
  129. return (
  130. <UniqueTagCell>
  131. <PoorTag>{t('Poor')}</PoorTag>
  132. </UniqueTagCell>
  133. );
  134. }
  135. if (dataRow[getVitalDetailTableMehStatusFunction(vitalName)]) {
  136. return (
  137. <UniqueTagCell>
  138. <MehTag>{t('Meh')}</MehTag>
  139. </UniqueTagCell>
  140. );
  141. }
  142. return (
  143. <UniqueTagCell>
  144. <GoodTag>{t('Good')}</GoodTag>
  145. </UniqueTagCell>
  146. );
  147. }
  148. const fieldRenderer = getFieldRenderer(field, tableMeta, false);
  149. const rendered = fieldRenderer(dataRow, {organization, location});
  150. const allowActions = [
  151. Actions.ADD,
  152. Actions.EXCLUDE,
  153. Actions.SHOW_GREATER_THAN,
  154. Actions.SHOW_LESS_THAN,
  155. ];
  156. if (field === 'transaction') {
  157. const projectID = getProjectID(dataRow, projects);
  158. const summaryView = eventView.clone();
  159. const conditions = new MutableSearch(summaryConditions);
  160. conditions.addFilterValues('has', [`${vitalName}`]);
  161. summaryView.query = conditions.formatString();
  162. const transaction = String(dataRow.transaction) || '';
  163. const target = transactionSummaryRouteWithQuery({
  164. orgSlug: organization.slug,
  165. transaction,
  166. query: summaryView.generateQueryStringObject(),
  167. projectID,
  168. showTransactions: TransactionFilterOptions.RECENT,
  169. display: DisplayModes.VITALS,
  170. });
  171. return (
  172. <CellAction
  173. column={column}
  174. dataRow={dataRow}
  175. handleCellAction={this.handleCellAction(column)}
  176. allowActions={allowActions}
  177. >
  178. <Link
  179. to={target}
  180. aria-label={t('See transaction summary of the transaction %s', transaction)}
  181. onClick={this.handleSummaryClick}
  182. >
  183. {rendered}
  184. </Link>
  185. </CellAction>
  186. );
  187. }
  188. if (field.startsWith('team_key_transaction')) {
  189. return rendered;
  190. }
  191. return (
  192. <CellAction
  193. column={column}
  194. dataRow={dataRow}
  195. handleCellAction={this.handleCellAction(column)}
  196. allowActions={allowActions}
  197. >
  198. {rendered}
  199. </CellAction>
  200. );
  201. }
  202. renderBodyCellWithData = (tableData: TableData | null, vitalName: WebVital) => {
  203. return (
  204. column: TableColumn<keyof TableDataRow>,
  205. dataRow: TableDataRow
  206. ): React.ReactNode => this.renderBodyCell(tableData, column, dataRow, vitalName);
  207. };
  208. renderHeadCell(
  209. column: TableColumn<keyof TableDataRow>,
  210. title: React.ReactNode,
  211. tableMeta?: EventsMetaType['fields']
  212. ): React.ReactNode {
  213. const {eventView, location} = this.props;
  214. // TODO: Need to map table meta keys to aggregate alias since eventView sorting still expects
  215. // aggregate aliases for now. We'll need to refactor event view to get rid of all aggregate
  216. // alias references and then we can remove this.
  217. const aggregateAliasTableMeta: EventsMetaType['fields'] | undefined = tableMeta
  218. ? {}
  219. : undefined;
  220. if (tableMeta) {
  221. Object.keys(tableMeta).forEach(key => {
  222. aggregateAliasTableMeta![getAggregateAlias(key)] = tableMeta[key];
  223. });
  224. }
  225. const align = fieldAlignment(column.name, column.type, aggregateAliasTableMeta);
  226. const field = {field: column.name, width: column.width};
  227. function generateSortLink(): LocationDescriptorObject | undefined {
  228. if (!aggregateAliasTableMeta) {
  229. return undefined;
  230. }
  231. const nextEventView = eventView.sortOnField(field, aggregateAliasTableMeta);
  232. const queryStringObject = nextEventView.generateQueryStringObject();
  233. return {
  234. ...location,
  235. query: {...location.query, sort: queryStringObject.sort},
  236. };
  237. }
  238. const currentSort = eventView.sortForField(field, aggregateAliasTableMeta);
  239. const canSort = isFieldSortable(field, aggregateAliasTableMeta);
  240. return (
  241. <SortLink
  242. align={align}
  243. title={title || field.field}
  244. direction={currentSort ? currentSort.kind : undefined}
  245. canSort={canSort}
  246. generateSortLink={generateSortLink}
  247. />
  248. );
  249. }
  250. renderHeadCellWithMeta = (
  251. vitalName: WebVital,
  252. tableMeta?: EventsMetaType['fields']
  253. ) => {
  254. return (column: TableColumn<keyof TableDataRow>, index: number): React.ReactNode =>
  255. this.renderHeadCell(column, getTableColumnTitle(index, vitalName), tableMeta);
  256. };
  257. renderPrependCellWithData = (tableData: TableData | null, vitalName: WebVital) => {
  258. const {eventView} = this.props;
  259. const teamKeyTransactionColumn = eventView
  260. .getColumns()
  261. .find((col: TableColumn<React.ReactText>) => col.name === 'team_key_transaction');
  262. return (isHeader: boolean, dataRow?: any) => {
  263. if (teamKeyTransactionColumn) {
  264. if (isHeader) {
  265. const star = (
  266. <IconStar
  267. key="keyTransaction"
  268. color="yellow300"
  269. isSolid
  270. data-test-id="key-transaction-header"
  271. />
  272. );
  273. return [
  274. this.renderHeadCell(teamKeyTransactionColumn, star, tableData?.meta?.fields),
  275. ];
  276. }
  277. return [
  278. this.renderBodyCell(tableData, teamKeyTransactionColumn, dataRow, vitalName),
  279. ];
  280. }
  281. return [];
  282. };
  283. };
  284. handleSummaryClick = () => {
  285. const {organization, projects, location} = this.props;
  286. trackAnalyticsEvent({
  287. eventKey: 'performance_views.overview.navigate.summary',
  288. eventName: 'Performance Views: Overview view summary',
  289. organization_id: parseInt(organization.id, 10),
  290. project_platforms: getSelectedProjectPlatforms(location, projects),
  291. });
  292. };
  293. handleResizeColumn = (columnIndex: number, nextColumn: GridColumn) => {
  294. const widths: number[] = [...this.state.widths];
  295. widths[columnIndex] = nextColumn.width
  296. ? Number(nextColumn.width)
  297. : COL_WIDTH_UNDEFINED;
  298. this.setState({widths});
  299. };
  300. getSortedEventView(vitalName: WebVital) {
  301. const {eventView} = this.props;
  302. const aggregateFieldPoor = getAggregateAlias(
  303. getVitalDetailTablePoorStatusFunction(vitalName)
  304. );
  305. const aggregateFieldMeh = getAggregateAlias(
  306. getVitalDetailTableMehStatusFunction(vitalName)
  307. );
  308. const isSortingByStatus = eventView.sorts.some(
  309. sort =>
  310. sort.field.includes(aggregateFieldPoor) || sort.field.includes(aggregateFieldMeh)
  311. );
  312. const additionalSorts: Sort[] = isSortingByStatus
  313. ? []
  314. : [
  315. {
  316. field: 'team_key_transaction',
  317. kind: 'desc',
  318. },
  319. {
  320. field: aggregateFieldPoor,
  321. kind: 'desc',
  322. },
  323. {
  324. field: aggregateFieldMeh,
  325. kind: 'desc',
  326. },
  327. ];
  328. return eventView.withSorts([...additionalSorts, ...eventView.sorts]);
  329. }
  330. render() {
  331. const {eventView, organization, location} = this.props;
  332. const {widths} = this.state;
  333. const fakeColumnView = eventView.clone();
  334. fakeColumnView.fields = [...eventView.fields];
  335. const columnOrder = fakeColumnView
  336. .getColumns()
  337. // remove key_transactions from the column order as we'll be rendering it
  338. // via a prepended column
  339. .filter((col: TableColumn<React.ReactText>) => col.name !== 'team_key_transaction')
  340. .slice(0, -1)
  341. .map((col: TableColumn<React.ReactText>, i: number) => {
  342. if (typeof widths[i] === 'number') {
  343. return {...col, width: widths[i]};
  344. }
  345. return col;
  346. });
  347. const vitalName = vitalNameFromLocation(location);
  348. const sortedEventView = this.getSortedEventView(vitalName);
  349. const columnSortBy = sortedEventView.getSorts();
  350. return (
  351. <div>
  352. <VitalsDetailsTableQuery
  353. eventView={sortedEventView}
  354. orgSlug={organization.slug}
  355. location={location}
  356. limit={10}
  357. referrer="api.performance.vital-detail"
  358. >
  359. {({pageLinks, isLoading, tableData}) => (
  360. <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(
  369. vitalName,
  370. tableData?.meta?.fields
  371. ) as any,
  372. renderBodyCell: this.renderBodyCellWithData(
  373. tableData,
  374. vitalName
  375. ) as any,
  376. renderPrependColumns: this.renderPrependCellWithData(
  377. tableData,
  378. vitalName
  379. ) as any,
  380. prependColumnWidths: ['max-content'],
  381. }}
  382. location={location}
  383. />
  384. <Pagination pageLinks={pageLinks} />
  385. </Fragment>
  386. )}
  387. </VitalsDetailsTableQuery>
  388. </div>
  389. );
  390. }
  391. }
  392. const UniqueTagCell = styled('div')`
  393. text-align: right;
  394. justify-self: flex-end;
  395. flex-grow: 1;
  396. `;
  397. const GoodTag = styled(Tag)`
  398. div {
  399. background-color: ${p => p.theme[vitalStateColors[VitalState.GOOD]]};
  400. }
  401. span {
  402. color: ${p => p.theme.white};
  403. }
  404. `;
  405. const MehTag = styled(Tag)`
  406. div {
  407. background-color: ${p => p.theme[vitalStateColors[VitalState.MEH]]};
  408. }
  409. span {
  410. color: ${p => p.theme.white};
  411. }
  412. `;
  413. const PoorTag = styled(Tag)`
  414. div {
  415. background-color: ${p => p.theme[vitalStateColors[VitalState.POOR]]};
  416. }
  417. span {
  418. color: ${p => p.theme.white};
  419. }
  420. `;
  421. export default Table;