tableView.tsx 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657
  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. <TransactionLink
  288. data-test-id="tableView-transaction-link"
  289. to={getTargetForTransactionSummaryLink(
  290. dataRow,
  291. organization,
  292. projects,
  293. eventView,
  294. location
  295. )}
  296. >
  297. {cell}
  298. </TransactionLink>
  299. );
  300. } else if (columnKey === 'trace') {
  301. const dateSelection = eventView.normalizeDateSelection(location);
  302. if (dataRow.trace) {
  303. const target = getTraceDetailsUrl(
  304. organization,
  305. String(dataRow.trace),
  306. dateSelection,
  307. {}
  308. );
  309. cell = (
  310. <Tooltip title={t('View Trace')}>
  311. <StyledLink data-test-id="view-trace" to={target}>
  312. {cell}
  313. </StyledLink>
  314. </Tooltip>
  315. );
  316. }
  317. } else if (columnKey === 'replayId') {
  318. if (dataRow.replayId) {
  319. if (!dataRow['project.name']) {
  320. return getShortEventId(String(dataRow.replayId));
  321. }
  322. const target = replayLinkGenerator(organization, dataRow, undefined);
  323. cell = (
  324. <ViewReplayLink replayId={dataRow.replayId} to={target}>
  325. {cell}
  326. </ViewReplayLink>
  327. );
  328. }
  329. } else if (columnKey === 'profile.id') {
  330. const projectSlug = dataRow.project || dataRow['project.name'];
  331. const profileId = dataRow['profile.id'];
  332. if (projectSlug && profileId) {
  333. const target = generateProfileFlamechartRoute({
  334. orgSlug: organization.slug,
  335. projectSlug: String(projectSlug),
  336. profileId: String(profileId),
  337. });
  338. cell = (
  339. <StyledTooltip title={t('View Profile')}>
  340. <StyledLink
  341. data-test-id="view-profile"
  342. to={target}
  343. onClick={() =>
  344. trackAnalytics('profiling_views.go_to_flamegraph', {
  345. organization,
  346. source: 'discover.table',
  347. })
  348. }
  349. >
  350. {cell}
  351. </StyledLink>
  352. </StyledTooltip>
  353. );
  354. }
  355. }
  356. const topResultsIndicator =
  357. isFirstPage && isTopEvents && rowIndex < topEvents && columnIndex === 0 ? (
  358. // Add one if we need to include Other in the series
  359. <TopResultsIndicator count={count} index={rowIndex} />
  360. ) : null;
  361. const fieldName = columnKey;
  362. const value = dataRow[fieldName];
  363. if (
  364. tableData.meta[fieldName] === 'integer' &&
  365. typeof value === 'number' &&
  366. value > 999
  367. ) {
  368. return (
  369. <Tooltip
  370. title={value.toLocaleString()}
  371. containerDisplayMode="block"
  372. position="right"
  373. >
  374. {topResultsIndicator}
  375. <CellAction
  376. column={column}
  377. dataRow={dataRow}
  378. handleCellAction={handleCellAction(dataRow, column)}
  379. >
  380. {cell}
  381. </CellAction>
  382. </Tooltip>
  383. );
  384. }
  385. return (
  386. <Fragment>
  387. {topResultsIndicator}
  388. <CellAction
  389. column={column}
  390. dataRow={dataRow}
  391. handleCellAction={handleCellAction(dataRow, column)}
  392. >
  393. {cell}
  394. </CellAction>
  395. </Fragment>
  396. );
  397. }
  398. function handleEditColumns() {
  399. const {
  400. organization,
  401. eventView,
  402. measurementKeys,
  403. spanOperationBreakdownKeys,
  404. customMeasurements,
  405. } = props;
  406. openModal(
  407. modalProps => (
  408. <ColumnEditModal
  409. {...modalProps}
  410. organization={organization}
  411. measurementKeys={measurementKeys}
  412. spanOperationBreakdownKeys={spanOperationBreakdownKeys}
  413. columns={eventView.getColumns().map(col => col.column)}
  414. onApply={handleUpdateColumns}
  415. customMeasurements={customMeasurements}
  416. />
  417. ),
  418. {modalCss, closeEvents: 'escape-key'}
  419. );
  420. }
  421. function handleCellAction(
  422. dataRow: TableDataRow,
  423. column: TableColumn<keyof TableDataRow>
  424. ) {
  425. return (action: Actions, value: React.ReactText) => {
  426. const {eventView, organization, location, tableData, isHomepage} = props;
  427. const query = new MutableSearch(eventView.query);
  428. let nextView = eventView.clone();
  429. trackAnalytics('discover_v2.results.cellaction', {
  430. organization,
  431. action,
  432. });
  433. switch (action) {
  434. case Actions.RELEASE: {
  435. const maybeProject = projects.find(project => {
  436. return project.slug === dataRow.project;
  437. });
  438. browserHistory.push(
  439. normalizeUrl({
  440. pathname: `/organizations/${
  441. organization.slug
  442. }/releases/${encodeURIComponent(value)}/`,
  443. query: {
  444. ...nextView.getPageFiltersQuery(),
  445. project: maybeProject ? maybeProject.id : undefined,
  446. },
  447. })
  448. );
  449. return;
  450. }
  451. case Actions.DRILLDOWN: {
  452. // count_unique(column) drilldown
  453. trackAnalytics('discover_v2.results.drilldown', {
  454. organization,
  455. });
  456. // Drilldown into each distinct value and get a count() for each value.
  457. nextView = getExpandedResults(nextView, {}, dataRow).withNewColumn({
  458. kind: 'function',
  459. function: ['count', '', undefined, undefined],
  460. });
  461. browserHistory.push(
  462. normalizeUrl(nextView.getResultsViewUrlTarget(organization.slug, isHomepage))
  463. );
  464. return;
  465. }
  466. default: {
  467. // Some custom perf metrics have units.
  468. // These custom perf metrics need to be adjusted to the correct value.
  469. let cellValue = value;
  470. const unit = tableData?.meta?.units?.[column.name];
  471. if (typeof cellValue === 'number' && unit) {
  472. if (Object.keys(SIZE_UNITS).includes(unit)) {
  473. cellValue *= SIZE_UNITS[unit];
  474. } else if (Object.keys(DURATION_UNITS).includes(unit)) {
  475. cellValue *= DURATION_UNITS[unit];
  476. }
  477. }
  478. updateQuery(query, action, column, cellValue);
  479. }
  480. }
  481. nextView.query = query.formatString();
  482. const target = nextView.getResultsViewUrlTarget(organization.slug, isHomepage);
  483. // Get yAxis from location
  484. target.query.yAxis = decodeList(location.query.yAxis);
  485. browserHistory.push(normalizeUrl(target));
  486. };
  487. }
  488. function handleUpdateColumns(columns: Column[]): void {
  489. const {organization, eventView, location, isHomepage} = props;
  490. // metrics
  491. trackAnalytics('discover_v2.update_columns', {
  492. organization,
  493. });
  494. const nextView = eventView.withColumns(columns);
  495. const resultsViewUrlTarget = nextView.getResultsViewUrlTarget(
  496. organization.slug,
  497. isHomepage
  498. );
  499. // Need to pull yAxis from location since eventView only stores 1 yAxis field at time
  500. const previousYAxis = decodeList(location.query.yAxis);
  501. resultsViewUrlTarget.query.yAxis = previousYAxis.filter(yAxis =>
  502. nextView.getYAxisOptions().find(({value}) => value === yAxis)
  503. );
  504. browserHistory.push(normalizeUrl(resultsViewUrlTarget));
  505. }
  506. function renderHeaderButtons() {
  507. const {
  508. organization,
  509. title,
  510. eventView,
  511. isLoading,
  512. error,
  513. tableData,
  514. location,
  515. onChangeShowTags,
  516. showTags,
  517. } = props;
  518. return (
  519. <TableActions
  520. title={title}
  521. isLoading={isLoading}
  522. error={error}
  523. organization={organization}
  524. eventView={eventView}
  525. onEdit={handleEditColumns}
  526. tableData={tableData}
  527. location={location}
  528. onChangeShowTags={onChangeShowTags}
  529. showTags={showTags}
  530. />
  531. );
  532. }
  533. const {error, eventView, isLoading, location, organization, tableData} = props;
  534. const columnOrder = eventView.getColumns();
  535. const columnSortBy = eventView.getSorts();
  536. const prependColumnWidths = eventView.hasAggregateField()
  537. ? ['40px']
  538. : eventView.hasIdField()
  539. ? []
  540. : [`minmax(${COL_WIDTH_MINIMUM}px, max-content)`];
  541. const replayIds = tableData?.data?.map(row => String(row.replayId)).filter(Boolean);
  542. return (
  543. <ReplayIdCountProvider organization={organization} replayIds={replayIds}>
  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. </ReplayIdCountProvider>
  562. );
  563. }
  564. const PrependHeader = styled('span')`
  565. color: ${p => p.theme.subText};
  566. `;
  567. const StyledTooltip = styled(Tooltip)`
  568. display: initial;
  569. max-width: max-content;
  570. `;
  571. export const StyledLink = styled(Link)`
  572. & div {
  573. display: inline;
  574. }
  575. `;
  576. export const TransactionLink = styled(Link)`
  577. ${p => p.theme.overflowEllipsis}
  578. `;
  579. const StyledIcon = styled(IconStack)`
  580. vertical-align: middle;
  581. `;
  582. export default TableView;