tableView.tsx 19 KB

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