tableView.tsx 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696
  1. import {Fragment} from 'react';
  2. import {browserHistory} from 'react-router';
  3. import styled from '@emotion/styled';
  4. import * as Sentry from '@sentry/react';
  5. import type {Location, LocationDescriptorObject} from 'history';
  6. import {openModal} from 'sentry/actionCreators/modal';
  7. import GridEditable, {
  8. COL_WIDTH_MINIMUM,
  9. COL_WIDTH_UNDEFINED,
  10. } from 'sentry/components/gridEditable';
  11. import SortLink from 'sentry/components/gridEditable/sortLink';
  12. import Link from 'sentry/components/links/link';
  13. import {Tooltip} from 'sentry/components/tooltip';
  14. import Truncate from 'sentry/components/truncate';
  15. import {IconStack} from 'sentry/icons';
  16. import {t} from 'sentry/locale';
  17. import type {Organization} from 'sentry/types/organization';
  18. import {trackAnalytics} from 'sentry/utils/analytics';
  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 {
  40. generateEventSlug,
  41. generateLinkToEventInTraceView,
  42. } from 'sentry/utils/discover/urls';
  43. import ViewReplayLink from 'sentry/utils/discover/viewReplayLink';
  44. import {getShortEventId} from 'sentry/utils/events';
  45. import {generateProfileFlamechartRoute} from 'sentry/utils/profiling/routes';
  46. import {decodeList} from 'sentry/utils/queryString';
  47. import {MutableSearch} from 'sentry/utils/tokenizeSearch';
  48. import useProjects from 'sentry/utils/useProjects';
  49. import {useRoutes} from 'sentry/utils/useRoutes';
  50. import {normalizeUrl} from 'sentry/utils/withDomainRequired';
  51. import {getTraceDetailsUrl} from 'sentry/views/performance/traceDetails/utils';
  52. import {generateReplayLink} from 'sentry/views/performance/transactionSummary/utils';
  53. import {
  54. getExpandedResults,
  55. getTargetForTransactionSummaryLink,
  56. pushEventViewToLocation,
  57. } from '../utils';
  58. import {QuickContextHoverWrapper} from './quickContext/quickContextWrapper';
  59. import {ContextType} from './quickContext/utils';
  60. import CellAction, {Actions, updateQuery} from './cellAction';
  61. import ColumnEditModal, {modalCss} from './columnEditModal';
  62. import TableActions from './tableActions';
  63. import TopResultsIndicator from './topResultsIndicator';
  64. import type {TableColumn} from './types';
  65. export type TableViewProps = {
  66. error: string | null;
  67. eventView: EventView;
  68. isFirstPage: boolean;
  69. isLoading: boolean;
  70. location: Location;
  71. measurementKeys: null | string[];
  72. onChangeShowTags: () => void;
  73. organization: Organization;
  74. showTags: boolean;
  75. tableData: TableData | null | undefined;
  76. title: string;
  77. customMeasurements?: CustomMeasurementCollection;
  78. isHomepage?: boolean;
  79. spanOperationBreakdownKeys?: string[];
  80. };
  81. /**
  82. * The `TableView` is marked with leading _ in its method names. It consumes
  83. * the EventView object given in its props to generate new EventView objects
  84. * for actions like resizing column.
  85. *
  86. * The entire state of the table view (or event view) is co-located within
  87. * the EventView object. This object is fed from the props.
  88. *
  89. * Attempting to modify the state, and therefore, modifying the given EventView
  90. * object given from its props, will generate new instances of EventView objects.
  91. *
  92. * In most cases, the new EventView object differs from the previous EventView
  93. * object. The new EventView object is pushed to the location object.
  94. */
  95. function TableView(props: TableViewProps) {
  96. const {projects} = useProjects();
  97. const routes = useRoutes();
  98. const replayLinkGenerator = generateReplayLink(routes);
  99. /**
  100. * Updates a column on resizing
  101. */
  102. function _resizeColumn(
  103. columnIndex: number,
  104. nextColumn: TableColumn<keyof TableDataRow>
  105. ) {
  106. const {location, eventView} = props;
  107. const newWidth = nextColumn.width ? Number(nextColumn.width) : COL_WIDTH_UNDEFINED;
  108. const nextEventView = eventView.withResizedColumn(columnIndex, newWidth);
  109. pushEventViewToLocation({
  110. location,
  111. nextEventView,
  112. extraQuery: pickRelevantLocationQueryStrings(location),
  113. });
  114. }
  115. function _renderPrependColumns(
  116. isHeader: boolean,
  117. dataRow?: any,
  118. rowIndex?: number
  119. ): React.ReactNode[] {
  120. const {organization, eventView, tableData, location, isHomepage} = props;
  121. const hasAggregates = eventView.hasAggregateField();
  122. const hasIdField = eventView.hasIdField();
  123. if (isHeader) {
  124. if (hasAggregates) {
  125. return [
  126. <PrependHeader key="header-icon">
  127. <IconStack size="sm" />
  128. </PrependHeader>,
  129. ];
  130. }
  131. if (!hasIdField) {
  132. return [
  133. <PrependHeader key="header-event-id">
  134. <SortLink
  135. align="left"
  136. title={t('event id')}
  137. direction={undefined}
  138. canSort={false}
  139. generateSortLink={() => undefined}
  140. />
  141. </PrependHeader>,
  142. ];
  143. }
  144. return [];
  145. }
  146. if (hasAggregates) {
  147. const nextView = getExpandedResults(eventView, {}, dataRow);
  148. const target = {
  149. pathname: location.pathname,
  150. query: nextView.generateQueryStringObject(),
  151. };
  152. return [
  153. <Tooltip key={`eventlink${rowIndex}`} title={t('Open Group')}>
  154. <Link
  155. to={target}
  156. data-test-id="open-group"
  157. onClick={() => {
  158. if (nextView.isEqualTo(eventView)) {
  159. Sentry.captureException(new Error('Failed to drilldown'));
  160. }
  161. }}
  162. >
  163. <StyledIcon size="sm" />
  164. </Link>
  165. </Tooltip>,
  166. ];
  167. }
  168. if (!hasIdField) {
  169. let value = dataRow.id;
  170. if (tableData?.meta) {
  171. const fieldRenderer = getFieldRenderer('id', tableData.meta);
  172. value = fieldRenderer(dataRow, {organization, location});
  173. }
  174. let target;
  175. if (dataRow['event.type'] === 'transaction') {
  176. if (dataRow.trace === null) {
  177. throw new Error(
  178. 'Transaction event should always have a trace associated with it.'
  179. );
  180. }
  181. target = generateLinkToEventInTraceView({
  182. eventSlug: generateEventSlug(dataRow),
  183. dataRow,
  184. organization,
  185. eventView,
  186. isHomepage,
  187. location,
  188. type: 'discover',
  189. });
  190. } else {
  191. const project = dataRow.project || dataRow['project.name'];
  192. target = {
  193. // NOTE: This uses a legacy redirect for project event to the issue group event link
  194. pathname: `/${organization.slug}/${project}/events/${dataRow.id}/?referrer=discover-events-table`,
  195. query: location.query,
  196. };
  197. }
  198. const eventIdLink = (
  199. <StyledLink data-test-id="view-event" to={target}>
  200. {value}
  201. </StyledLink>
  202. );
  203. return [
  204. <QuickContextHoverWrapper
  205. key={`quickContextEventHover${rowIndex}`}
  206. dataRow={dataRow}
  207. contextType={ContextType.EVENT}
  208. organization={organization}
  209. projects={projects}
  210. eventView={eventView}
  211. >
  212. {eventIdLink}
  213. </QuickContextHoverWrapper>,
  214. ];
  215. }
  216. return [];
  217. }
  218. function _renderGridHeaderCell(
  219. column: TableColumn<keyof TableDataRow>
  220. ): React.ReactNode {
  221. const {eventView, location, tableData} = props;
  222. const tableMeta = tableData?.meta;
  223. const align = fieldAlignment(column.name, column.type, tableMeta);
  224. const field = {field: column.key as string, width: column.width};
  225. function generateSortLink(): LocationDescriptorObject | undefined {
  226. if (!tableMeta) {
  227. return undefined;
  228. }
  229. const nextEventView = eventView.sortOnField(field, tableMeta);
  230. const queryStringObject = nextEventView.generateQueryStringObject();
  231. // Need to pull yAxis from location since eventView only stores 1 yAxis field at time
  232. queryStringObject.yAxis = decodeList(location.query.yAxis);
  233. return {
  234. ...location,
  235. query: queryStringObject,
  236. };
  237. }
  238. const currentSort = eventView.sortForField(field, tableMeta);
  239. const canSort = isFieldSortable(field, tableMeta);
  240. let titleText = isEquationAlias(column.name)
  241. ? eventView.getEquations()[getEquationAliasIndex(column.name)]
  242. : column.name;
  243. if (column.name.toLowerCase() === 'replayid') {
  244. titleText = 'Replay';
  245. }
  246. const title = (
  247. <StyledTooltip title={titleText}>
  248. <Truncate value={titleText} maxLength={60} expandable={false} />
  249. </StyledTooltip>
  250. );
  251. return (
  252. <SortLink
  253. align={align}
  254. title={title}
  255. direction={currentSort ? currentSort.kind : undefined}
  256. canSort={canSort}
  257. generateSortLink={generateSortLink}
  258. />
  259. );
  260. }
  261. function _renderGridBodyCell(
  262. column: TableColumn<keyof TableDataRow>,
  263. dataRow: TableDataRow,
  264. rowIndex: number,
  265. columnIndex: number
  266. ): React.ReactNode {
  267. const {isFirstPage, eventView, location, organization, tableData, isHomepage} = props;
  268. if (!tableData || !tableData.meta) {
  269. return dataRow[column.key];
  270. }
  271. const columnKey = String(column.key);
  272. const fieldRenderer = getFieldRenderer(columnKey, tableData.meta, false);
  273. const display = eventView.getDisplayMode();
  274. const isTopEvents =
  275. display === DisplayModes.TOP5 || display === DisplayModes.DAILYTOP5;
  276. const topEvents = eventView.topEvents ? parseInt(eventView.topEvents, 10) : TOP_N;
  277. const count = Math.min(tableData?.data?.length ?? topEvents, topEvents);
  278. const unit = tableData.meta.units?.[columnKey];
  279. let cell = fieldRenderer(dataRow, {organization, location, unit});
  280. if (columnKey === 'id') {
  281. let target;
  282. if (dataRow['event.type'] === 'transaction') {
  283. if (dataRow.trace === null) {
  284. throw new Error(
  285. 'Transaction event should always have a trace associated with it.'
  286. );
  287. }
  288. target = generateLinkToEventInTraceView({
  289. eventSlug: generateEventSlug(dataRow),
  290. dataRow,
  291. organization,
  292. eventView,
  293. isHomepage,
  294. location,
  295. type: 'discover',
  296. });
  297. } else {
  298. const project = dataRow.project || dataRow['project.name'];
  299. target = {
  300. // NOTE: This uses a legacy redirect for project event to the issue group event link
  301. pathname: `/${organization.slug}/${project}/events/${dataRow.id}/?referrer=discover-events-table`,
  302. query: location.query,
  303. };
  304. }
  305. const idLink = (
  306. <StyledLink data-test-id="view-event" to={target}>
  307. {cell}
  308. </StyledLink>
  309. );
  310. cell = (
  311. <QuickContextHoverWrapper
  312. organization={organization}
  313. dataRow={dataRow}
  314. contextType={ContextType.EVENT}
  315. projects={projects}
  316. eventView={eventView}
  317. >
  318. {idLink}
  319. </QuickContextHoverWrapper>
  320. );
  321. } else if (columnKey === 'transaction' && dataRow.transaction) {
  322. cell = (
  323. <TransactionLink
  324. data-test-id="tableView-transaction-link"
  325. to={getTargetForTransactionSummaryLink(
  326. dataRow,
  327. organization,
  328. projects,
  329. eventView,
  330. location
  331. )}
  332. >
  333. {cell}
  334. </TransactionLink>
  335. );
  336. } else if (columnKey === 'trace') {
  337. const timestamp = getTimeStampFromTableDateField(
  338. dataRow['max(timestamp)'] ?? dataRow.timestamp
  339. );
  340. const dateSelection = eventView.normalizeDateSelection(location);
  341. if (dataRow.trace) {
  342. const target = getTraceDetailsUrl(
  343. organization,
  344. String(dataRow.trace),
  345. dateSelection,
  346. {},
  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;