tableView.tsx 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606
  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. const titleText = isEquationAlias(column.name)
  196. ? eventView.getEquations()[getEquationAliasIndex(column.name)]
  197. : column.name;
  198. const title = (
  199. <StyledTooltip title={titleText}>
  200. <Truncate value={titleText} maxLength={60} expandable={false} />
  201. </StyledTooltip>
  202. );
  203. return (
  204. <SortLink
  205. align={align}
  206. title={title}
  207. direction={currentSort ? currentSort.kind : undefined}
  208. canSort={canSort}
  209. generateSortLink={generateSortLink}
  210. />
  211. );
  212. };
  213. _renderGridBodyCell = (
  214. column: TableColumn<keyof TableDataRow>,
  215. dataRow: TableDataRow,
  216. rowIndex: number,
  217. columnIndex: number
  218. ): React.ReactNode => {
  219. const {isFirstPage, eventView, location, organization, tableData, isHomepage} =
  220. this.props;
  221. if (!tableData || !tableData.meta) {
  222. return dataRow[column.key];
  223. }
  224. const columnKey = String(column.key);
  225. const fieldRenderer = getFieldRenderer(
  226. columnKey,
  227. tableData.meta,
  228. !organization.features.includes('discover-frontend-use-events-endpoint')
  229. );
  230. const display = eventView.getDisplayMode();
  231. const isTopEvents =
  232. display === DisplayModes.TOP5 || display === DisplayModes.DAILYTOP5;
  233. const topEvents = eventView.topEvents ? parseInt(eventView.topEvents, 10) : TOP_N;
  234. const count = Math.min(tableData?.data?.length ?? topEvents, topEvents);
  235. const unit = tableData.meta.units?.[columnKey];
  236. let cell = fieldRenderer(dataRow, {organization, location, unit});
  237. if (columnKey === 'id') {
  238. const eventSlug = generateEventSlug(dataRow);
  239. const target = eventDetailsRouteWithEventView({
  240. orgSlug: organization.slug,
  241. eventSlug,
  242. eventView,
  243. isHomepage,
  244. });
  245. cell = (
  246. <Tooltip title={t('View Event')}>
  247. <StyledLink data-test-id="view-event" to={target}>
  248. {cell}
  249. </StyledLink>
  250. </Tooltip>
  251. );
  252. } else if (columnKey === 'trace') {
  253. const dateSelection = eventView.normalizeDateSelection(location);
  254. if (dataRow.trace) {
  255. const target = getTraceDetailsUrl(
  256. organization,
  257. String(dataRow.trace),
  258. dateSelection,
  259. {}
  260. );
  261. cell = (
  262. <Tooltip title={t('View Trace')}>
  263. <StyledLink data-test-id="view-trace" to={target}>
  264. {cell}
  265. </StyledLink>
  266. </Tooltip>
  267. );
  268. }
  269. } else if (columnKey === 'replayId') {
  270. if (dataRow.replayId) {
  271. const replaySlug = `${dataRow['project.name']}:${dataRow.replayId}`;
  272. const referrer = encodeURIComponent(getRouteStringFromRoutes(this.props.routes));
  273. const target = {
  274. pathname: `/organizations/${organization.slug}/replays/${replaySlug}`,
  275. query: {
  276. referrer,
  277. },
  278. };
  279. cell = (
  280. <Tooltip title={t('View Replay')}>
  281. <StyledLink data-test-id="view-replay" to={target}>
  282. {cell}
  283. </StyledLink>
  284. </Tooltip>
  285. );
  286. }
  287. }
  288. const topResultsIndicator =
  289. isFirstPage && isTopEvents && rowIndex < topEvents && columnIndex === 0 ? (
  290. // Add one if we need to include Other in the series
  291. <TopResultsIndicator count={count} index={rowIndex} />
  292. ) : null;
  293. const fieldName = columnKey;
  294. const value = dataRow[fieldName];
  295. if (tableData.meta[fieldName] === 'integer' && defined(value) && value > 999) {
  296. return (
  297. <Tooltip
  298. title={value.toLocaleString()}
  299. containerDisplayMode="block"
  300. position="right"
  301. >
  302. {topResultsIndicator}
  303. <CellAction
  304. column={column}
  305. dataRow={dataRow}
  306. handleCellAction={this.handleCellAction(dataRow, column)}
  307. organization={organization}
  308. showQuickContextMenu
  309. >
  310. {cell}
  311. </CellAction>
  312. </Tooltip>
  313. );
  314. }
  315. return (
  316. <Fragment>
  317. {topResultsIndicator}
  318. <CellAction
  319. column={column}
  320. dataRow={dataRow}
  321. handleCellAction={this.handleCellAction(dataRow, column)}
  322. organization={organization}
  323. showQuickContextMenu
  324. >
  325. {cell}
  326. </CellAction>
  327. </Fragment>
  328. );
  329. };
  330. handleEditColumns = () => {
  331. const {
  332. organization,
  333. eventView,
  334. measurementKeys,
  335. spanOperationBreakdownKeys,
  336. customMeasurements,
  337. } = this.props;
  338. const hasBreakdownFeature = organization.features.includes(
  339. 'performance-ops-breakdown'
  340. );
  341. openModal(
  342. modalProps => (
  343. <ColumnEditModal
  344. {...modalProps}
  345. organization={organization}
  346. measurementKeys={measurementKeys}
  347. spanOperationBreakdownKeys={
  348. hasBreakdownFeature ? spanOperationBreakdownKeys : undefined
  349. }
  350. columns={eventView.getColumns().map(col => col.column)}
  351. onApply={this.handleUpdateColumns}
  352. customMeasurements={customMeasurements}
  353. />
  354. ),
  355. {modalCss, backdrop: 'static'}
  356. );
  357. };
  358. handleCellAction = (dataRow: TableDataRow, column: TableColumn<keyof TableDataRow>) => {
  359. return (action: Actions, value: React.ReactText) => {
  360. const {eventView, organization, projects, location, tableData, isHomepage} =
  361. this.props;
  362. const query = new MutableSearch(eventView.query);
  363. let nextView = eventView.clone();
  364. trackAnalyticsEvent({
  365. eventKey: 'discover_v2.results.cellaction',
  366. eventName: 'Discoverv2: Cell Action Clicked',
  367. organization_id: parseInt(organization.id, 10),
  368. action,
  369. });
  370. switch (action) {
  371. case Actions.TRANSACTION: {
  372. const maybeProject = projects.find(
  373. project =>
  374. project.slug &&
  375. [dataRow['project.name'], dataRow.project].includes(project.slug)
  376. );
  377. const projectID = maybeProject ? [maybeProject.id] : undefined;
  378. const next = transactionSummaryRouteWithQuery({
  379. orgSlug: organization.slug,
  380. transaction: String(value),
  381. projectID,
  382. query: nextView.getPageFiltersQuery(),
  383. });
  384. browserHistory.push(next);
  385. return;
  386. }
  387. case Actions.RELEASE: {
  388. const maybeProject = projects.find(project => {
  389. return project.slug === dataRow.project;
  390. });
  391. browserHistory.push({
  392. pathname: `/organizations/${organization.slug}/releases/${encodeURIComponent(
  393. value
  394. )}/`,
  395. query: {
  396. ...nextView.getPageFiltersQuery(),
  397. project: maybeProject ? maybeProject.id : undefined,
  398. },
  399. });
  400. return;
  401. }
  402. case Actions.DRILLDOWN: {
  403. // count_unique(column) drilldown
  404. trackAnalyticsEvent({
  405. eventKey: 'discover_v2.results.drilldown',
  406. eventName: 'Discoverv2: Click aggregate drilldown',
  407. organization_id: parseInt(organization.id, 10),
  408. });
  409. // Drilldown into each distinct value and get a count() for each value.
  410. nextView = getExpandedResults(nextView, {}, dataRow).withNewColumn({
  411. kind: 'function',
  412. function: ['count', '', undefined, undefined],
  413. });
  414. browserHistory.push(
  415. nextView.getResultsViewUrlTarget(organization.slug, isHomepage)
  416. );
  417. return;
  418. }
  419. default: {
  420. // Some custom perf metrics have units.
  421. // These custom perf metrics need to be adjusted to the correct value.
  422. let cellValue = value;
  423. const unit = tableData?.meta?.units?.[column.name];
  424. if (typeof cellValue === 'number' && unit) {
  425. if (Object.keys(SIZE_UNITS).includes(unit)) {
  426. cellValue *= SIZE_UNITS[unit];
  427. } else if (Object.keys(DURATION_UNITS).includes(unit)) {
  428. cellValue *= DURATION_UNITS[unit];
  429. }
  430. }
  431. updateQuery(query, action, column, cellValue);
  432. }
  433. }
  434. nextView.query = query.formatString();
  435. const target = nextView.getResultsViewUrlTarget(organization.slug, isHomepage);
  436. // Get yAxis from location
  437. target.query.yAxis = decodeList(location.query.yAxis);
  438. browserHistory.push(target);
  439. };
  440. };
  441. handleUpdateColumns = (columns: Column[]): void => {
  442. const {organization, eventView, location, isHomepage} = this.props;
  443. // metrics
  444. trackAnalyticsEvent({
  445. eventKey: 'discover_v2.update_columns',
  446. eventName: 'Discoverv2: Update columns',
  447. organization_id: parseInt(organization.id, 10),
  448. });
  449. const nextView = eventView.withColumns(columns);
  450. const resultsViewUrlTarget = nextView.getResultsViewUrlTarget(
  451. organization.slug,
  452. isHomepage
  453. );
  454. // Need to pull yAxis from location since eventView only stores 1 yAxis field at time
  455. const previousYAxis = decodeList(location.query.yAxis);
  456. resultsViewUrlTarget.query.yAxis = previousYAxis.filter(yAxis =>
  457. nextView.getYAxisOptions().find(({value}) => value === yAxis)
  458. );
  459. browserHistory.push(resultsViewUrlTarget);
  460. };
  461. renderHeaderButtons = () => {
  462. const {
  463. organization,
  464. title,
  465. eventView,
  466. isLoading,
  467. error,
  468. tableData,
  469. location,
  470. onChangeShowTags,
  471. showTags,
  472. } = this.props;
  473. return (
  474. <TableActions
  475. title={title}
  476. isLoading={isLoading}
  477. error={error}
  478. organization={organization}
  479. eventView={eventView}
  480. onEdit={this.handleEditColumns}
  481. tableData={tableData}
  482. location={location}
  483. onChangeShowTags={onChangeShowTags}
  484. showTags={showTags}
  485. />
  486. );
  487. };
  488. render() {
  489. const {isLoading, error, location, tableData, eventView, organization} = this.props;
  490. const columnOrder = eventView.getColumns(
  491. organization.features.includes('discover-frontend-use-events-endpoint')
  492. );
  493. const columnSortBy = eventView.getSorts();
  494. const prependColumnWidths = eventView.hasAggregateField()
  495. ? ['40px']
  496. : eventView.hasIdField()
  497. ? []
  498. : [`minmax(${COL_WIDTH_MINIMUM}px, max-content)`];
  499. return (
  500. <GridEditable
  501. isLoading={isLoading}
  502. error={error}
  503. data={tableData ? tableData.data : []}
  504. columnOrder={columnOrder}
  505. columnSortBy={columnSortBy}
  506. title={t('Results')}
  507. grid={{
  508. renderHeadCell: this._renderGridHeaderCell as any,
  509. renderBodyCell: this._renderGridBodyCell as any,
  510. onResizeColumn: this._resizeColumn as any,
  511. renderPrependColumns: this._renderPrependColumns as any,
  512. prependColumnWidths,
  513. }}
  514. headerButtons={this.renderHeaderButtons}
  515. location={location}
  516. />
  517. );
  518. }
  519. }
  520. const PrependHeader = styled('span')`
  521. color: ${p => p.theme.subText};
  522. `;
  523. const StyledTooltip = styled(Tooltip)`
  524. display: initial;
  525. `;
  526. const StyledLink = styled(Link)`
  527. & div {
  528. display: inline;
  529. }
  530. `;
  531. const StyledIcon = styled(IconStack)`
  532. vertical-align: middle;
  533. `;
  534. export default withRouter(withProjects(TableView));