tableView.tsx 21 KB

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