tableView.tsx 19 KB

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