tableView.tsx 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555
  1. import * as React from 'react';
  2. import {browserHistory} from 'react-router';
  3. import styled from '@emotion/styled';
  4. import * as Sentry from '@sentry/react';
  5. import {Location, LocationDescriptorObject} from 'history';
  6. import {openModal} from 'app/actionCreators/modal';
  7. import GridEditable, {
  8. COL_WIDTH_MINIMUM,
  9. COL_WIDTH_UNDEFINED,
  10. } from 'app/components/gridEditable';
  11. import SortLink from 'app/components/gridEditable/sortLink';
  12. import Link from 'app/components/links/link';
  13. import Tooltip from 'app/components/tooltip';
  14. import Truncate from 'app/components/truncate';
  15. import {IconStack} from 'app/icons';
  16. import {t} from 'app/locale';
  17. import {Organization, Project} from 'app/types';
  18. import {defined} from 'app/utils';
  19. import {trackAnalyticsEvent} from 'app/utils/analytics';
  20. import {TableData, TableDataRow} from 'app/utils/discover/discoverQuery';
  21. import EventView, {
  22. isFieldSortable,
  23. pickRelevantLocationQueryStrings,
  24. } from 'app/utils/discover/eventView';
  25. import {getFieldRenderer} from 'app/utils/discover/fieldRenderers';
  26. import {
  27. Column,
  28. fieldAlignment,
  29. getAggregateAlias,
  30. getEquationAliasIndex,
  31. isEquationAlias,
  32. } from 'app/utils/discover/fields';
  33. import {DisplayModes, TOP_N} from 'app/utils/discover/types';
  34. import {eventDetailsRouteWithEventView, generateEventSlug} from 'app/utils/discover/urls';
  35. import {decodeList} from 'app/utils/queryString';
  36. import {MutableSearch} from 'app/utils/tokenizeSearch';
  37. import withProjects from 'app/utils/withProjects';
  38. import {getTraceDetailsUrl} from 'app/views/performance/traceDetails/utils';
  39. import {transactionSummaryRouteWithQuery} from 'app/views/performance/transactionSummary/utils';
  40. import {getExpandedResults, pushEventViewToLocation} from '../utils';
  41. import CellAction, {Actions, updateQuery} from './cellAction';
  42. import ColumnEditModal, {modalCss} from './columnEditModal';
  43. import TableActions from './tableActions';
  44. import {TableColumn} from './types';
  45. export type TableViewProps = {
  46. location: Location;
  47. organization: Organization;
  48. projects: Project[];
  49. isLoading: boolean;
  50. error: string | null;
  51. isFirstPage: boolean;
  52. eventView: EventView;
  53. tableData: TableData | null | undefined;
  54. tagKeys: null | string[];
  55. measurementKeys: null | string[];
  56. spanOperationBreakdownKeys?: string[];
  57. title: string;
  58. onChangeShowTags: () => void;
  59. showTags: boolean;
  60. };
  61. /**
  62. * The `TableView` is marked with leading _ in its method names. It consumes
  63. * the EventView object given in its props to generate new EventView objects
  64. * for actions like resizing column.
  65. * The entire state of the table view (or event view) is co-located within
  66. * the EventView object. This object is fed from the props.
  67. *
  68. * Attempting to modify the state, and therefore, modifying the given EventView
  69. * object given from its props, will generate new instances of EventView objects.
  70. *
  71. * In most cases, the new EventView object differs from the previous EventView
  72. * object. The new EventView object is pushed to the location object.
  73. */
  74. class TableView extends React.Component<TableViewProps> {
  75. /**
  76. * Updates a column on resizing
  77. */
  78. _resizeColumn = (columnIndex: number, nextColumn: TableColumn<keyof TableDataRow>) => {
  79. const {location, eventView} = this.props;
  80. const newWidth = nextColumn.width ? Number(nextColumn.width) : COL_WIDTH_UNDEFINED;
  81. const nextEventView = eventView.withResizedColumn(columnIndex, newWidth);
  82. pushEventViewToLocation({
  83. location,
  84. nextEventView,
  85. extraQuery: pickRelevantLocationQueryStrings(location),
  86. });
  87. };
  88. _renderPrependColumns = (
  89. isHeader: boolean,
  90. dataRow?: any,
  91. rowIndex?: number
  92. ): React.ReactNode[] => {
  93. const {organization, eventView, tableData, location} = this.props;
  94. const hasAggregates = eventView.hasAggregateField();
  95. const hasIdField = eventView.hasIdField();
  96. if (isHeader) {
  97. if (hasAggregates) {
  98. return [
  99. <PrependHeader key="header-icon">
  100. <IconStack size="sm" />
  101. </PrependHeader>,
  102. ];
  103. } else if (!hasIdField) {
  104. return [
  105. <PrependHeader key="header-event-id">
  106. <SortLink
  107. align="left"
  108. title={t('event id')}
  109. direction={undefined}
  110. canSort={false}
  111. generateSortLink={() => undefined}
  112. />
  113. </PrependHeader>,
  114. ];
  115. } else {
  116. return [];
  117. }
  118. }
  119. if (hasAggregates) {
  120. const nextView = getExpandedResults(eventView, {}, dataRow);
  121. const target = {
  122. pathname: location.pathname,
  123. query: nextView.generateQueryStringObject(),
  124. };
  125. return [
  126. <Tooltip key={`eventlink${rowIndex}`} title={t('Open Group')}>
  127. <Link
  128. to={target}
  129. data-test-id="open-group"
  130. onClick={() => {
  131. if (nextView.isEqualTo(eventView)) {
  132. Sentry.captureException(new Error('Failed to drilldown'));
  133. }
  134. }}
  135. >
  136. <StyledIcon size="sm" />
  137. </Link>
  138. </Tooltip>,
  139. ];
  140. } else if (!hasIdField) {
  141. let value = dataRow.id;
  142. if (tableData && tableData.meta) {
  143. const fieldRenderer = getFieldRenderer('id', tableData.meta);
  144. value = fieldRenderer(dataRow, {organization, location});
  145. }
  146. const eventSlug = generateEventSlug(dataRow);
  147. const target = eventDetailsRouteWithEventView({
  148. orgSlug: organization.slug,
  149. eventSlug,
  150. eventView,
  151. });
  152. return [
  153. <Tooltip key={`eventlink${rowIndex}`} title={t('View Event')}>
  154. <StyledLink data-test-id="view-event" to={target}>
  155. {value}
  156. </StyledLink>
  157. </Tooltip>,
  158. ];
  159. } else {
  160. return [];
  161. }
  162. };
  163. _renderGridHeaderCell = (column: TableColumn<keyof TableDataRow>): React.ReactNode => {
  164. const {eventView, location, tableData} = this.props;
  165. const tableMeta = tableData?.meta;
  166. const align = fieldAlignment(column.name, column.type, tableMeta);
  167. const field = {field: column.name, width: column.width};
  168. function generateSortLink(): LocationDescriptorObject | undefined {
  169. if (!tableMeta) {
  170. return undefined;
  171. }
  172. const nextEventView = eventView.sortOnField(field, tableMeta);
  173. const queryStringObject = nextEventView.generateQueryStringObject();
  174. // Need to pull yAxis from location since eventView only stores 1 yAxis field at time
  175. queryStringObject.yAxis = decodeList(location.query.yAxis);
  176. return {
  177. ...location,
  178. query: queryStringObject,
  179. };
  180. }
  181. const currentSort = eventView.sortForField(field, tableMeta);
  182. const canSort = isFieldSortable(field, tableMeta);
  183. const titleText = isEquationAlias(column.name)
  184. ? eventView.getEquations()[getEquationAliasIndex(column.name)]
  185. : column.name;
  186. const title = (
  187. <StyledTooltip title={titleText}>
  188. <Truncate value={titleText} maxLength={60} expandable={false} />
  189. </StyledTooltip>
  190. );
  191. return (
  192. <SortLink
  193. align={align}
  194. title={title}
  195. direction={currentSort ? currentSort.kind : undefined}
  196. canSort={canSort}
  197. generateSortLink={generateSortLink}
  198. />
  199. );
  200. };
  201. _renderGridBodyCell = (
  202. column: TableColumn<keyof TableDataRow>,
  203. dataRow: TableDataRow,
  204. rowIndex: number,
  205. columnIndex: number
  206. ): React.ReactNode => {
  207. const {isFirstPage, eventView, location, organization, tableData} = this.props;
  208. if (!tableData || !tableData.meta) {
  209. return dataRow[column.key];
  210. }
  211. const columnKey = String(column.key);
  212. const fieldRenderer = getFieldRenderer(columnKey, tableData.meta);
  213. const display = eventView.getDisplayMode();
  214. const isTopEvents =
  215. display === DisplayModes.TOP5 || display === DisplayModes.DAILYTOP5;
  216. const count = Math.min(tableData?.data?.length ?? TOP_N, TOP_N);
  217. let cell = fieldRenderer(dataRow, {organization, location});
  218. if (columnKey === 'id') {
  219. const eventSlug = generateEventSlug(dataRow);
  220. const target = eventDetailsRouteWithEventView({
  221. orgSlug: organization.slug,
  222. eventSlug,
  223. eventView,
  224. });
  225. cell = (
  226. <Tooltip title={t('View Event')}>
  227. <StyledLink data-test-id="view-event" to={target}>
  228. {cell}
  229. </StyledLink>
  230. </Tooltip>
  231. );
  232. } else if (columnKey === 'trace') {
  233. const dateSelection = eventView.normalizeDateSelection(location);
  234. if (dataRow.trace) {
  235. const target = getTraceDetailsUrl(
  236. organization,
  237. String(dataRow.trace),
  238. dateSelection,
  239. {}
  240. );
  241. cell = (
  242. <Tooltip title={t('View Trace')}>
  243. <StyledLink data-test-id="view-trace" to={target}>
  244. {cell}
  245. </StyledLink>
  246. </Tooltip>
  247. );
  248. }
  249. }
  250. const fieldName = getAggregateAlias(columnKey);
  251. const value = dataRow[fieldName];
  252. if (tableData.meta[fieldName] === 'integer' && defined(value) && value > 999) {
  253. return (
  254. <Tooltip
  255. title={value.toLocaleString()}
  256. containerDisplayMode="block"
  257. position="right"
  258. >
  259. <CellAction
  260. column={column}
  261. dataRow={dataRow}
  262. handleCellAction={this.handleCellAction(dataRow, column)}
  263. >
  264. {cell}
  265. </CellAction>
  266. </Tooltip>
  267. );
  268. }
  269. return (
  270. <React.Fragment>
  271. {isFirstPage && isTopEvents && rowIndex < TOP_N && columnIndex === 0 ? (
  272. <TopResultsIndicator count={count} index={rowIndex} />
  273. ) : null}
  274. <CellAction
  275. column={column}
  276. dataRow={dataRow}
  277. handleCellAction={this.handleCellAction(dataRow, column)}
  278. >
  279. {cell}
  280. </CellAction>
  281. </React.Fragment>
  282. );
  283. };
  284. handleEditColumns = () => {
  285. const {
  286. organization,
  287. eventView,
  288. tagKeys,
  289. measurementKeys,
  290. spanOperationBreakdownKeys,
  291. } = this.props;
  292. const hasBreakdownFeature = organization.features.includes(
  293. 'performance-ops-breakdown'
  294. );
  295. openModal(
  296. modalProps => (
  297. <ColumnEditModal
  298. {...modalProps}
  299. organization={organization}
  300. tagKeys={tagKeys}
  301. measurementKeys={measurementKeys}
  302. spanOperationBreakdownKeys={
  303. hasBreakdownFeature ? spanOperationBreakdownKeys : undefined
  304. }
  305. columns={eventView.getColumns().map(col => col.column)}
  306. onApply={this.handleUpdateColumns}
  307. />
  308. ),
  309. {modalCss, backdrop: 'static'}
  310. );
  311. };
  312. handleCellAction = (dataRow: TableDataRow, column: TableColumn<keyof TableDataRow>) => {
  313. return (action: Actions, value: React.ReactText) => {
  314. const {eventView, organization, projects} = this.props;
  315. const query = new MutableSearch(eventView.query);
  316. let nextView = eventView.clone();
  317. trackAnalyticsEvent({
  318. eventKey: 'discover_v2.results.cellaction',
  319. eventName: 'Discoverv2: Cell Action Clicked',
  320. organization_id: parseInt(organization.id, 10),
  321. action,
  322. });
  323. switch (action) {
  324. case Actions.TRANSACTION: {
  325. const maybeProject = projects.find(project => project.slug === dataRow.project);
  326. const projectID = maybeProject ? [maybeProject.id] : undefined;
  327. const next = transactionSummaryRouteWithQuery({
  328. orgSlug: organization.slug,
  329. transaction: String(value),
  330. projectID,
  331. query: nextView.getGlobalSelectionQuery(),
  332. });
  333. browserHistory.push(next);
  334. return;
  335. }
  336. case Actions.RELEASE: {
  337. const maybeProject = projects.find(project => {
  338. return project.slug === dataRow.project;
  339. });
  340. browserHistory.push({
  341. pathname: `/organizations/${organization.slug}/releases/${encodeURIComponent(
  342. value
  343. )}/`,
  344. query: {
  345. ...nextView.getGlobalSelectionQuery(),
  346. project: maybeProject ? maybeProject.id : undefined,
  347. },
  348. });
  349. return;
  350. }
  351. case Actions.DRILLDOWN: {
  352. // count_unique(column) drilldown
  353. trackAnalyticsEvent({
  354. eventKey: 'discover_v2.results.drilldown',
  355. eventName: 'Discoverv2: Click aggregate drilldown',
  356. organization_id: parseInt(organization.id, 10),
  357. });
  358. // Drilldown into each distinct value and get a count() for each value.
  359. nextView = getExpandedResults(nextView, {}, dataRow).withNewColumn({
  360. kind: 'function',
  361. function: ['count', '', undefined, undefined],
  362. });
  363. browserHistory.push(nextView.getResultsViewUrlTarget(organization.slug));
  364. return;
  365. }
  366. default: {
  367. updateQuery(query, action, column, value);
  368. }
  369. }
  370. nextView.query = query.formatString();
  371. browserHistory.push(nextView.getResultsViewUrlTarget(organization.slug));
  372. };
  373. };
  374. handleUpdateColumns = (columns: Column[]): void => {
  375. const {organization, eventView, location} = this.props;
  376. // metrics
  377. trackAnalyticsEvent({
  378. eventKey: 'discover_v2.update_columns',
  379. eventName: 'Discoverv2: Update columns',
  380. organization_id: parseInt(organization.id, 10),
  381. });
  382. const nextView = eventView.withColumns(columns);
  383. const resultsViewUrlTarget = nextView.getResultsViewUrlTarget(organization.slug);
  384. // Need to pull yAxis from location since eventView only stores 1 yAxis field at time
  385. const previousYAxis = decodeList(location.query.yAxis);
  386. resultsViewUrlTarget.query.yAxis = previousYAxis.filter(yAxis =>
  387. nextView.getYAxisOptions().find(({value}) => value === yAxis)
  388. );
  389. browserHistory.push(resultsViewUrlTarget);
  390. };
  391. renderHeaderButtons = () => {
  392. const {
  393. organization,
  394. title,
  395. eventView,
  396. isLoading,
  397. error,
  398. tableData,
  399. location,
  400. onChangeShowTags,
  401. showTags,
  402. } = this.props;
  403. return (
  404. <TableActions
  405. title={title}
  406. isLoading={isLoading}
  407. error={error}
  408. organization={organization}
  409. eventView={eventView}
  410. onEdit={this.handleEditColumns}
  411. tableData={tableData}
  412. location={location}
  413. onChangeShowTags={onChangeShowTags}
  414. showTags={showTags}
  415. />
  416. );
  417. };
  418. render() {
  419. const {isLoading, error, location, tableData, eventView} = this.props;
  420. const columnOrder = eventView.getColumns();
  421. const columnSortBy = eventView.getSorts();
  422. const prependColumnWidths = eventView.hasAggregateField()
  423. ? ['40px']
  424. : eventView.hasIdField()
  425. ? []
  426. : [`minmax(${COL_WIDTH_MINIMUM}px, max-content)`];
  427. return (
  428. <GridEditable
  429. isLoading={isLoading}
  430. error={error}
  431. data={tableData ? tableData.data : []}
  432. columnOrder={columnOrder}
  433. columnSortBy={columnSortBy}
  434. title={t('Results')}
  435. grid={{
  436. renderHeadCell: this._renderGridHeaderCell as any,
  437. renderBodyCell: this._renderGridBodyCell as any,
  438. onResizeColumn: this._resizeColumn as any,
  439. renderPrependColumns: this._renderPrependColumns as any,
  440. prependColumnWidths,
  441. }}
  442. headerButtons={this.renderHeaderButtons}
  443. location={location}
  444. />
  445. );
  446. }
  447. }
  448. const PrependHeader = styled('span')`
  449. color: ${p => p.theme.subText};
  450. `;
  451. const StyledTooltip = styled(Tooltip)`
  452. display: initial;
  453. `;
  454. const StyledLink = styled(Link)`
  455. > div {
  456. display: inline;
  457. }
  458. `;
  459. const StyledIcon = styled(IconStack)`
  460. vertical-align: middle;
  461. `;
  462. type TopResultsIndicatorProps = {
  463. count: number;
  464. index: number;
  465. };
  466. const TopResultsIndicator = styled('div')<TopResultsIndicatorProps>`
  467. position: absolute;
  468. left: -1px;
  469. margin-top: 4.5px;
  470. width: 9px;
  471. height: 15px;
  472. border-radius: 0 3px 3px 0;
  473. background-color: ${p => {
  474. // this background color needs to match the colors used in
  475. // app/components/charts/eventsChart so that the ordering matches
  476. // the color pallete contains n + 2 colors, so we subtract 2 here
  477. return p.theme.charts.getColorPalette(p.count - 2)[p.index];
  478. }};
  479. `;
  480. export default withProjects(TableView);