tableView.tsx 19 KB

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