tableView.tsx 20 KB

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