tableView.tsx 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697
  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. {},
  348. timestamp
  349. );
  350. cell = (
  351. <Tooltip title={t('View Trace')}>
  352. <StyledLink data-test-id="view-trace" to={target}>
  353. {cell}
  354. </StyledLink>
  355. </Tooltip>
  356. );
  357. }
  358. } else if (columnKey === 'replayId') {
  359. if (dataRow.replayId) {
  360. if (!dataRow['project.name']) {
  361. return getShortEventId(String(dataRow.replayId));
  362. }
  363. const target = replayLinkGenerator(organization, dataRow, undefined);
  364. cell = (
  365. <ViewReplayLink replayId={dataRow.replayId} to={target}>
  366. {cell}
  367. </ViewReplayLink>
  368. );
  369. }
  370. } else if (columnKey === 'profile.id') {
  371. const projectSlug = dataRow.project || dataRow['project.name'];
  372. const profileId = dataRow['profile.id'];
  373. if (projectSlug && profileId) {
  374. const target = generateProfileFlamechartRoute({
  375. orgSlug: organization.slug,
  376. projectSlug: String(projectSlug),
  377. profileId: String(profileId),
  378. });
  379. cell = (
  380. <StyledTooltip title={t('View Profile')}>
  381. <StyledLink
  382. data-test-id="view-profile"
  383. to={target}
  384. onClick={() =>
  385. trackAnalytics('profiling_views.go_to_flamegraph', {
  386. organization,
  387. source: 'discover.table',
  388. })
  389. }
  390. >
  391. {cell}
  392. </StyledLink>
  393. </StyledTooltip>
  394. );
  395. }
  396. }
  397. const topResultsIndicator =
  398. isFirstPage && isTopEvents && rowIndex < topEvents && columnIndex === 0 ? (
  399. // Add one if we need to include Other in the series
  400. <TopResultsIndicator count={count} index={rowIndex} />
  401. ) : null;
  402. const fieldName = columnKey;
  403. const value = dataRow[fieldName];
  404. if (
  405. tableData.meta[fieldName] === 'integer' &&
  406. typeof value === 'number' &&
  407. value > 999
  408. ) {
  409. return (
  410. <Tooltip
  411. title={value.toLocaleString()}
  412. containerDisplayMode="block"
  413. position="right"
  414. >
  415. {topResultsIndicator}
  416. <CellAction
  417. column={column}
  418. dataRow={dataRow}
  419. handleCellAction={handleCellAction(dataRow, column)}
  420. >
  421. {cell}
  422. </CellAction>
  423. </Tooltip>
  424. );
  425. }
  426. return (
  427. <Fragment>
  428. {topResultsIndicator}
  429. <CellAction
  430. column={column}
  431. dataRow={dataRow}
  432. handleCellAction={handleCellAction(dataRow, column)}
  433. >
  434. {cell}
  435. </CellAction>
  436. </Fragment>
  437. );
  438. }
  439. function handleEditColumns() {
  440. const {
  441. organization,
  442. eventView,
  443. measurementKeys,
  444. spanOperationBreakdownKeys,
  445. customMeasurements,
  446. } = props;
  447. openModal(
  448. modalProps => (
  449. <ColumnEditModal
  450. {...modalProps}
  451. organization={organization}
  452. measurementKeys={measurementKeys}
  453. spanOperationBreakdownKeys={spanOperationBreakdownKeys}
  454. columns={eventView.getColumns().map(col => col.column)}
  455. onApply={handleUpdateColumns}
  456. customMeasurements={customMeasurements}
  457. />
  458. ),
  459. {modalCss, closeEvents: 'escape-key'}
  460. );
  461. }
  462. function handleCellAction(
  463. dataRow: TableDataRow,
  464. column: TableColumn<keyof TableDataRow>
  465. ) {
  466. return (action: Actions, value: React.ReactText) => {
  467. const {eventView, organization, location, tableData, isHomepage} = props;
  468. const query = new MutableSearch(eventView.query);
  469. let nextView = eventView.clone();
  470. trackAnalytics('discover_v2.results.cellaction', {
  471. organization,
  472. action,
  473. });
  474. switch (action) {
  475. case Actions.RELEASE: {
  476. const maybeProject = projects.find(project => {
  477. return project.slug === dataRow.project;
  478. });
  479. browserHistory.push(
  480. normalizeUrl({
  481. pathname: `/organizations/${
  482. organization.slug
  483. }/releases/${encodeURIComponent(value)}/`,
  484. query: {
  485. ...nextView.getPageFiltersQuery(),
  486. project: maybeProject ? maybeProject.id : undefined,
  487. },
  488. })
  489. );
  490. return;
  491. }
  492. case Actions.DRILLDOWN: {
  493. // count_unique(column) drilldown
  494. trackAnalytics('discover_v2.results.drilldown', {
  495. organization,
  496. });
  497. // Drilldown into each distinct value and get a count() for each value.
  498. nextView = getExpandedResults(nextView, {}, dataRow).withNewColumn({
  499. kind: 'function',
  500. function: ['count', '', undefined, undefined],
  501. });
  502. browserHistory.push(
  503. normalizeUrl(nextView.getResultsViewUrlTarget(organization.slug, isHomepage))
  504. );
  505. return;
  506. }
  507. default: {
  508. // Some custom perf metrics have units.
  509. // These custom perf metrics need to be adjusted to the correct value.
  510. let cellValue = value;
  511. const unit = tableData?.meta?.units?.[column.name];
  512. if (typeof cellValue === 'number' && unit) {
  513. if (Object.keys(SIZE_UNITS).includes(unit)) {
  514. cellValue *= SIZE_UNITS[unit];
  515. } else if (Object.keys(DURATION_UNITS).includes(unit)) {
  516. cellValue *= DURATION_UNITS[unit];
  517. }
  518. }
  519. updateQuery(query, action, column, cellValue);
  520. }
  521. }
  522. nextView.query = query.formatString();
  523. const target = nextView.getResultsViewUrlTarget(organization.slug, isHomepage);
  524. // Get yAxis from location
  525. target.query.yAxis = decodeList(location.query.yAxis);
  526. browserHistory.push(normalizeUrl(target));
  527. };
  528. }
  529. function handleUpdateColumns(columns: Column[]): void {
  530. const {organization, eventView, location, isHomepage} = props;
  531. // metrics
  532. trackAnalytics('discover_v2.update_columns', {
  533. organization,
  534. });
  535. const nextView = eventView.withColumns(columns);
  536. const resultsViewUrlTarget = nextView.getResultsViewUrlTarget(
  537. organization.slug,
  538. isHomepage
  539. );
  540. // Need to pull yAxis from location since eventView only stores 1 yAxis field at time
  541. const previousYAxis = decodeList(location.query.yAxis);
  542. resultsViewUrlTarget.query.yAxis = previousYAxis.filter(yAxis =>
  543. nextView.getYAxisOptions().find(({value}) => value === yAxis)
  544. );
  545. browserHistory.push(normalizeUrl(resultsViewUrlTarget));
  546. }
  547. function renderHeaderButtons() {
  548. const {
  549. organization,
  550. title,
  551. eventView,
  552. isLoading,
  553. error,
  554. tableData,
  555. location,
  556. onChangeShowTags,
  557. showTags,
  558. } = props;
  559. return (
  560. <TableActions
  561. title={title}
  562. isLoading={isLoading}
  563. error={error}
  564. organization={organization}
  565. eventView={eventView}
  566. onEdit={handleEditColumns}
  567. tableData={tableData}
  568. location={location}
  569. onChangeShowTags={onChangeShowTags}
  570. showTags={showTags}
  571. supportsInvestigationRule
  572. />
  573. );
  574. }
  575. const {error, eventView, isLoading, location, tableData} = props;
  576. const columnOrder = eventView.getColumns();
  577. const columnSortBy = eventView.getSorts();
  578. const prependColumnWidths = eventView.hasAggregateField()
  579. ? ['40px']
  580. : eventView.hasIdField()
  581. ? []
  582. : [`minmax(${COL_WIDTH_MINIMUM}px, max-content)`];
  583. return (
  584. <GridEditable
  585. isLoading={isLoading}
  586. error={error}
  587. data={tableData ? tableData.data : []}
  588. columnOrder={columnOrder}
  589. columnSortBy={columnSortBy}
  590. title={t('Results')}
  591. grid={{
  592. renderHeadCell: _renderGridHeaderCell as any,
  593. renderBodyCell: _renderGridBodyCell as any,
  594. onResizeColumn: _resizeColumn as any,
  595. renderPrependColumns: _renderPrependColumns as any,
  596. prependColumnWidths,
  597. }}
  598. headerButtons={renderHeaderButtons}
  599. location={location}
  600. />
  601. );
  602. }
  603. const PrependHeader = styled('span')`
  604. color: ${p => p.theme.subText};
  605. `;
  606. const StyledTooltip = styled(Tooltip)`
  607. display: initial;
  608. max-width: max-content;
  609. `;
  610. export const StyledLink = styled(Link)`
  611. & div {
  612. display: inline;
  613. }
  614. `;
  615. export const TransactionLink = styled(Link)`
  616. ${p => p.theme.overflowEllipsis}
  617. `;
  618. const StyledIcon = styled(IconStack)`
  619. vertical-align: middle;
  620. `;
  621. export default TableView;