tableView.tsx 21 KB

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