tableView.tsx 19 KB

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