tableView.tsx 21 KB

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