tableView.tsx 21 KB

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