tableView.tsx 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654
  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 type {TableData, TableDataRow} from 'sentry/utils/discover/discoverQuery';
  21. import type EventView from 'sentry/utils/discover/eventView';
  22. import {
  23. isFieldSortable,
  24. pickRelevantLocationQueryStrings,
  25. } from 'sentry/utils/discover/eventView';
  26. import {
  27. DURATION_UNITS,
  28. getFieldRenderer,
  29. SIZE_UNITS,
  30. } from 'sentry/utils/discover/fieldRenderers';
  31. import type {Column} from 'sentry/utils/discover/fields';
  32. import {
  33. fieldAlignment,
  34. getEquationAliasIndex,
  35. isEquationAlias,
  36. } from 'sentry/utils/discover/fields';
  37. import {DisplayModes, TOP_N} from 'sentry/utils/discover/types';
  38. import {
  39. eventDetailsRouteWithEventView,
  40. generateEventSlug,
  41. } from 'sentry/utils/discover/urls';
  42. import ViewReplayLink from 'sentry/utils/discover/viewReplayLink';
  43. import {getShortEventId} from 'sentry/utils/events';
  44. import {generateProfileFlamechartRoute} from 'sentry/utils/profiling/routes';
  45. import {decodeList} from 'sentry/utils/queryString';
  46. import {MutableSearch} from 'sentry/utils/tokenizeSearch';
  47. import useProjects from 'sentry/utils/useProjects';
  48. import {useRoutes} from 'sentry/utils/useRoutes';
  49. import {normalizeUrl} from 'sentry/utils/withDomainRequired';
  50. import {getTraceDetailsUrl} from 'sentry/views/performance/traceDetails/utils';
  51. import {generateReplayLink} from 'sentry/views/performance/transactionSummary/utils';
  52. import {
  53. getExpandedResults,
  54. getTargetForTransactionSummaryLink,
  55. pushEventViewToLocation,
  56. } from '../utils';
  57. import {QuickContextHoverWrapper} from './quickContext/quickContextWrapper';
  58. import {ContextType} from './quickContext/utils';
  59. import CellAction, {Actions, updateQuery} from './cellAction';
  60. import ColumnEditModal, {modalCss} from './columnEditModal';
  61. import TableActions from './tableActions';
  62. import TopResultsIndicator from './topResultsIndicator';
  63. import type {TableColumn} from './types';
  64. export type TableViewProps = {
  65. error: string | null;
  66. eventView: EventView;
  67. isFirstPage: boolean;
  68. isLoading: boolean;
  69. location: Location;
  70. measurementKeys: null | string[];
  71. onChangeShowTags: () => void;
  72. organization: Organization;
  73. showTags: boolean;
  74. tableData: TableData | null | undefined;
  75. title: string;
  76. customMeasurements?: CustomMeasurementCollection;
  77. isHomepage?: boolean;
  78. spanOperationBreakdownKeys?: string[];
  79. };
  80. /**
  81. * The `TableView` is marked with leading _ in its method names. It consumes
  82. * the EventView object given in its props to generate new EventView objects
  83. * for actions like resizing column.
  84. *
  85. * The entire state of the table view (or event view) is co-located within
  86. * the EventView object. This object is fed from the props.
  87. *
  88. * Attempting to modify the state, and therefore, modifying the given EventView
  89. * object given from its props, will generate new instances of EventView objects.
  90. *
  91. * In most cases, the new EventView object differs from the previous EventView
  92. * object. The new EventView object is pushed to the location object.
  93. */
  94. function TableView(props: TableViewProps) {
  95. const {projects} = useProjects();
  96. const routes = useRoutes();
  97. const replayLinkGenerator = generateReplayLink(routes);
  98. /**
  99. * Updates a column on resizing
  100. */
  101. function _resizeColumn(
  102. columnIndex: number,
  103. nextColumn: TableColumn<keyof TableDataRow>
  104. ) {
  105. const {location, eventView} = props;
  106. const newWidth = nextColumn.width ? Number(nextColumn.width) : COL_WIDTH_UNDEFINED;
  107. const nextEventView = eventView.withResizedColumn(columnIndex, newWidth);
  108. pushEventViewToLocation({
  109. location,
  110. nextEventView,
  111. extraQuery: pickRelevantLocationQueryStrings(location),
  112. });
  113. }
  114. function _renderPrependColumns(
  115. isHeader: boolean,
  116. dataRow?: any,
  117. rowIndex?: number
  118. ): React.ReactNode[] {
  119. const {organization, eventView, tableData, location, isHomepage} = props;
  120. const hasAggregates = eventView.hasAggregateField();
  121. const hasIdField = eventView.hasIdField();
  122. if (isHeader) {
  123. if (hasAggregates) {
  124. return [
  125. <PrependHeader key="header-icon">
  126. <IconStack size="sm" />
  127. </PrependHeader>,
  128. ];
  129. }
  130. if (!hasIdField) {
  131. return [
  132. <PrependHeader key="header-event-id">
  133. <SortLink
  134. align="left"
  135. title={t('event id')}
  136. direction={undefined}
  137. canSort={false}
  138. generateSortLink={() => undefined}
  139. />
  140. </PrependHeader>,
  141. ];
  142. }
  143. return [];
  144. }
  145. if (hasAggregates) {
  146. const nextView = getExpandedResults(eventView, {}, dataRow);
  147. const target = {
  148. pathname: location.pathname,
  149. query: nextView.generateQueryStringObject(),
  150. };
  151. return [
  152. <Tooltip key={`eventlink${rowIndex}`} title={t('Open Group')}>
  153. <Link
  154. to={target}
  155. data-test-id="open-group"
  156. onClick={() => {
  157. if (nextView.isEqualTo(eventView)) {
  158. Sentry.captureException(new Error('Failed to drilldown'));
  159. }
  160. }}
  161. >
  162. <StyledIcon size="sm" />
  163. </Link>
  164. </Tooltip>,
  165. ];
  166. }
  167. if (!hasIdField) {
  168. let value = dataRow.id;
  169. if (tableData?.meta) {
  170. const fieldRenderer = getFieldRenderer('id', tableData.meta);
  171. value = fieldRenderer(dataRow, {organization, location});
  172. }
  173. const eventSlug = generateEventSlug(dataRow);
  174. const target = eventDetailsRouteWithEventView({
  175. orgSlug: organization.slug,
  176. eventSlug,
  177. eventView,
  178. isHomepage,
  179. });
  180. const eventIdLink = (
  181. <StyledLink data-test-id="view-event" to={target}>
  182. {value}
  183. </StyledLink>
  184. );
  185. return [
  186. <QuickContextHoverWrapper
  187. key={`quickContextEventHover${rowIndex}`}
  188. dataRow={dataRow}
  189. contextType={ContextType.EVENT}
  190. organization={organization}
  191. projects={projects}
  192. eventView={eventView}
  193. >
  194. {eventIdLink}
  195. </QuickContextHoverWrapper>,
  196. ];
  197. }
  198. return [];
  199. }
  200. function _renderGridHeaderCell(
  201. column: TableColumn<keyof TableDataRow>
  202. ): React.ReactNode {
  203. const {eventView, location, tableData} = props;
  204. const tableMeta = tableData?.meta;
  205. const align = fieldAlignment(column.name, column.type, tableMeta);
  206. const field = {field: column.key as string, width: column.width};
  207. function generateSortLink(): LocationDescriptorObject | undefined {
  208. if (!tableMeta) {
  209. return undefined;
  210. }
  211. const nextEventView = eventView.sortOnField(field, tableMeta);
  212. const queryStringObject = nextEventView.generateQueryStringObject();
  213. // Need to pull yAxis from location since eventView only stores 1 yAxis field at time
  214. queryStringObject.yAxis = decodeList(location.query.yAxis);
  215. return {
  216. ...location,
  217. query: queryStringObject,
  218. };
  219. }
  220. const currentSort = eventView.sortForField(field, tableMeta);
  221. const canSort = isFieldSortable(field, tableMeta);
  222. let titleText = isEquationAlias(column.name)
  223. ? eventView.getEquations()[getEquationAliasIndex(column.name)]
  224. : column.name;
  225. if (column.name.toLowerCase() === 'replayid') {
  226. titleText = 'Replay';
  227. }
  228. const title = (
  229. <StyledTooltip title={titleText}>
  230. <Truncate value={titleText} maxLength={60} expandable={false} />
  231. </StyledTooltip>
  232. );
  233. return (
  234. <SortLink
  235. align={align}
  236. title={title}
  237. direction={currentSort ? currentSort.kind : undefined}
  238. canSort={canSort}
  239. generateSortLink={generateSortLink}
  240. />
  241. );
  242. }
  243. function _renderGridBodyCell(
  244. column: TableColumn<keyof TableDataRow>,
  245. dataRow: TableDataRow,
  246. rowIndex: number,
  247. columnIndex: number
  248. ): React.ReactNode {
  249. const {isFirstPage, eventView, location, organization, tableData, isHomepage} = props;
  250. if (!tableData || !tableData.meta) {
  251. return dataRow[column.key];
  252. }
  253. const columnKey = String(column.key);
  254. const fieldRenderer = getFieldRenderer(columnKey, tableData.meta, false);
  255. const display = eventView.getDisplayMode();
  256. const isTopEvents =
  257. display === DisplayModes.TOP5 || display === DisplayModes.DAILYTOP5;
  258. const topEvents = eventView.topEvents ? parseInt(eventView.topEvents, 10) : TOP_N;
  259. const count = Math.min(tableData?.data?.length ?? topEvents, topEvents);
  260. const unit = tableData.meta.units?.[columnKey];
  261. let cell = fieldRenderer(dataRow, {organization, location, unit});
  262. if (columnKey === 'id') {
  263. const eventSlug = generateEventSlug(dataRow);
  264. const target = eventDetailsRouteWithEventView({
  265. orgSlug: organization.slug,
  266. eventSlug,
  267. eventView,
  268. isHomepage,
  269. });
  270. const idLink = (
  271. <StyledLink data-test-id="view-event" to={target}>
  272. {cell}
  273. </StyledLink>
  274. );
  275. cell = (
  276. <QuickContextHoverWrapper
  277. organization={organization}
  278. dataRow={dataRow}
  279. contextType={ContextType.EVENT}
  280. projects={projects}
  281. eventView={eventView}
  282. >
  283. {idLink}
  284. </QuickContextHoverWrapper>
  285. );
  286. } else if (columnKey === 'transaction' && dataRow.transaction) {
  287. cell = (
  288. <TransactionLink
  289. data-test-id="tableView-transaction-link"
  290. to={getTargetForTransactionSummaryLink(
  291. dataRow,
  292. organization,
  293. projects,
  294. eventView,
  295. location
  296. )}
  297. >
  298. {cell}
  299. </TransactionLink>
  300. );
  301. } else if (columnKey === 'trace') {
  302. const dateSelection = eventView.normalizeDateSelection(location);
  303. if (dataRow.trace) {
  304. const target = getTraceDetailsUrl(
  305. organization,
  306. String(dataRow.trace),
  307. dateSelection,
  308. {}
  309. );
  310. cell = (
  311. <Tooltip title={t('View Trace')}>
  312. <StyledLink data-test-id="view-trace" to={target}>
  313. {cell}
  314. </StyledLink>
  315. </Tooltip>
  316. );
  317. }
  318. } else if (columnKey === 'replayId') {
  319. if (dataRow.replayId) {
  320. if (!dataRow['project.name']) {
  321. return getShortEventId(String(dataRow.replayId));
  322. }
  323. const target = replayLinkGenerator(organization, dataRow, undefined);
  324. cell = (
  325. <ViewReplayLink replayId={dataRow.replayId} to={target}>
  326. {cell}
  327. </ViewReplayLink>
  328. );
  329. }
  330. } else if (columnKey === 'profile.id') {
  331. const projectSlug = dataRow.project || dataRow['project.name'];
  332. const profileId = dataRow['profile.id'];
  333. if (projectSlug && profileId) {
  334. const target = generateProfileFlamechartRoute({
  335. orgSlug: organization.slug,
  336. projectSlug: String(projectSlug),
  337. profileId: String(profileId),
  338. });
  339. cell = (
  340. <StyledTooltip title={t('View Profile')}>
  341. <StyledLink
  342. data-test-id="view-profile"
  343. to={target}
  344. onClick={() =>
  345. trackAnalytics('profiling_views.go_to_flamegraph', {
  346. organization,
  347. source: 'discover.table',
  348. })
  349. }
  350. >
  351. {cell}
  352. </StyledLink>
  353. </StyledTooltip>
  354. );
  355. }
  356. }
  357. const topResultsIndicator =
  358. isFirstPage && isTopEvents && rowIndex < topEvents && columnIndex === 0 ? (
  359. // Add one if we need to include Other in the series
  360. <TopResultsIndicator count={count} index={rowIndex} />
  361. ) : null;
  362. const fieldName = columnKey;
  363. const value = dataRow[fieldName];
  364. if (
  365. tableData.meta[fieldName] === 'integer' &&
  366. typeof value === 'number' &&
  367. value > 999
  368. ) {
  369. return (
  370. <Tooltip
  371. title={value.toLocaleString()}
  372. containerDisplayMode="block"
  373. position="right"
  374. >
  375. {topResultsIndicator}
  376. <CellAction
  377. column={column}
  378. dataRow={dataRow}
  379. handleCellAction={handleCellAction(dataRow, column)}
  380. >
  381. {cell}
  382. </CellAction>
  383. </Tooltip>
  384. );
  385. }
  386. return (
  387. <Fragment>
  388. {topResultsIndicator}
  389. <CellAction
  390. column={column}
  391. dataRow={dataRow}
  392. handleCellAction={handleCellAction(dataRow, column)}
  393. >
  394. {cell}
  395. </CellAction>
  396. </Fragment>
  397. );
  398. }
  399. function handleEditColumns() {
  400. const {
  401. organization,
  402. eventView,
  403. measurementKeys,
  404. spanOperationBreakdownKeys,
  405. customMeasurements,
  406. } = props;
  407. openModal(
  408. modalProps => (
  409. <ColumnEditModal
  410. {...modalProps}
  411. organization={organization}
  412. measurementKeys={measurementKeys}
  413. spanOperationBreakdownKeys={spanOperationBreakdownKeys}
  414. columns={eventView.getColumns().map(col => col.column)}
  415. onApply={handleUpdateColumns}
  416. customMeasurements={customMeasurements}
  417. />
  418. ),
  419. {modalCss, closeEvents: 'escape-key'}
  420. );
  421. }
  422. function handleCellAction(
  423. dataRow: TableDataRow,
  424. column: TableColumn<keyof TableDataRow>
  425. ) {
  426. return (action: Actions, value: React.ReactText) => {
  427. const {eventView, organization, location, tableData, isHomepage} = props;
  428. const query = new MutableSearch(eventView.query);
  429. let nextView = eventView.clone();
  430. trackAnalytics('discover_v2.results.cellaction', {
  431. organization,
  432. action,
  433. });
  434. switch (action) {
  435. case Actions.RELEASE: {
  436. const maybeProject = projects.find(project => {
  437. return project.slug === dataRow.project;
  438. });
  439. browserHistory.push(
  440. normalizeUrl({
  441. pathname: `/organizations/${
  442. organization.slug
  443. }/releases/${encodeURIComponent(value)}/`,
  444. query: {
  445. ...nextView.getPageFiltersQuery(),
  446. project: maybeProject ? maybeProject.id : undefined,
  447. },
  448. })
  449. );
  450. return;
  451. }
  452. case Actions.DRILLDOWN: {
  453. // count_unique(column) drilldown
  454. trackAnalytics('discover_v2.results.drilldown', {
  455. organization,
  456. });
  457. // Drilldown into each distinct value and get a count() for each value.
  458. nextView = getExpandedResults(nextView, {}, dataRow).withNewColumn({
  459. kind: 'function',
  460. function: ['count', '', undefined, undefined],
  461. });
  462. browserHistory.push(
  463. normalizeUrl(nextView.getResultsViewUrlTarget(organization.slug, isHomepage))
  464. );
  465. return;
  466. }
  467. default: {
  468. // Some custom perf metrics have units.
  469. // These custom perf metrics need to be adjusted to the correct value.
  470. let cellValue = value;
  471. const unit = tableData?.meta?.units?.[column.name];
  472. if (typeof cellValue === 'number' && unit) {
  473. if (Object.keys(SIZE_UNITS).includes(unit)) {
  474. cellValue *= SIZE_UNITS[unit];
  475. } else if (Object.keys(DURATION_UNITS).includes(unit)) {
  476. cellValue *= DURATION_UNITS[unit];
  477. }
  478. }
  479. updateQuery(query, action, column, cellValue);
  480. }
  481. }
  482. nextView.query = query.formatString();
  483. const target = nextView.getResultsViewUrlTarget(organization.slug, isHomepage);
  484. // Get yAxis from location
  485. target.query.yAxis = decodeList(location.query.yAxis);
  486. browserHistory.push(normalizeUrl(target));
  487. };
  488. }
  489. function handleUpdateColumns(columns: Column[]): void {
  490. const {organization, eventView, location, isHomepage} = props;
  491. // metrics
  492. trackAnalytics('discover_v2.update_columns', {
  493. organization,
  494. });
  495. const nextView = eventView.withColumns(columns);
  496. const resultsViewUrlTarget = nextView.getResultsViewUrlTarget(
  497. organization.slug,
  498. isHomepage
  499. );
  500. // Need to pull yAxis from location since eventView only stores 1 yAxis field at time
  501. const previousYAxis = decodeList(location.query.yAxis);
  502. resultsViewUrlTarget.query.yAxis = previousYAxis.filter(yAxis =>
  503. nextView.getYAxisOptions().find(({value}) => value === yAxis)
  504. );
  505. browserHistory.push(normalizeUrl(resultsViewUrlTarget));
  506. }
  507. function renderHeaderButtons() {
  508. const {
  509. organization,
  510. title,
  511. eventView,
  512. isLoading,
  513. error,
  514. tableData,
  515. location,
  516. onChangeShowTags,
  517. showTags,
  518. } = props;
  519. return (
  520. <TableActions
  521. title={title}
  522. isLoading={isLoading}
  523. error={error}
  524. organization={organization}
  525. eventView={eventView}
  526. onEdit={handleEditColumns}
  527. tableData={tableData}
  528. location={location}
  529. onChangeShowTags={onChangeShowTags}
  530. showTags={showTags}
  531. supportsInvestigationRule
  532. />
  533. );
  534. }
  535. const {error, eventView, isLoading, location, tableData} = props;
  536. const columnOrder = eventView.getColumns();
  537. const columnSortBy = eventView.getSorts();
  538. const prependColumnWidths = eventView.hasAggregateField()
  539. ? ['40px']
  540. : eventView.hasIdField()
  541. ? []
  542. : [`minmax(${COL_WIDTH_MINIMUM}px, max-content)`];
  543. return (
  544. <GridEditable
  545. isLoading={isLoading}
  546. error={error}
  547. data={tableData ? tableData.data : []}
  548. columnOrder={columnOrder}
  549. columnSortBy={columnSortBy}
  550. title={t('Results')}
  551. grid={{
  552. renderHeadCell: _renderGridHeaderCell as any,
  553. renderBodyCell: _renderGridBodyCell as any,
  554. onResizeColumn: _resizeColumn as any,
  555. renderPrependColumns: _renderPrependColumns as any,
  556. prependColumnWidths,
  557. }}
  558. headerButtons={renderHeaderButtons}
  559. location={location}
  560. />
  561. );
  562. }
  563. const PrependHeader = styled('span')`
  564. color: ${p => p.theme.subText};
  565. `;
  566. const StyledTooltip = styled(Tooltip)`
  567. display: initial;
  568. max-width: max-content;
  569. `;
  570. export const StyledLink = styled(Link)`
  571. & div {
  572. display: inline;
  573. }
  574. `;
  575. export const TransactionLink = styled(Link)`
  576. ${p => p.theme.overflowEllipsis}
  577. `;
  578. const StyledIcon = styled(IconStack)`
  579. vertical-align: middle;
  580. `;
  581. export default TableView;