tableView.tsx 18 KB

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