tableView.tsx 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653
  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 {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 {Organization} from 'sentry/types';
  18. import {trackAnalytics} from 'sentry/utils/analytics';
  19. import {CustomMeasurementCollection} from 'sentry/utils/customMeasurements/customMeasurements';
  20. import {TableData, TableDataRow} from 'sentry/utils/discover/discoverQuery';
  21. import EventView, {
  22. isFieldSortable,
  23. pickRelevantLocationQueryStrings,
  24. } from 'sentry/utils/discover/eventView';
  25. import {
  26. DURATION_UNITS,
  27. getFieldRenderer,
  28. SIZE_UNITS,
  29. } from 'sentry/utils/discover/fieldRenderers';
  30. import {
  31. Column,
  32. fieldAlignment,
  33. getEquationAliasIndex,
  34. isEquationAlias,
  35. } from 'sentry/utils/discover/fields';
  36. import {DisplayModes, TOP_N} from 'sentry/utils/discover/types';
  37. import {
  38. eventDetailsRouteWithEventView,
  39. generateEventSlug,
  40. } from 'sentry/utils/discover/urls';
  41. import ViewReplayLink from 'sentry/utils/discover/viewReplayLink';
  42. import {getShortEventId} from 'sentry/utils/events';
  43. import {generateProfileFlamechartRoute} from 'sentry/utils/profiling/routes';
  44. import {decodeList} from 'sentry/utils/queryString';
  45. import {MutableSearch} from 'sentry/utils/tokenizeSearch';
  46. import useProjects from 'sentry/utils/useProjects';
  47. import {useRoutes} from 'sentry/utils/useRoutes';
  48. import {normalizeUrl} from 'sentry/utils/withDomainRequired';
  49. import {getTraceDetailsUrl} from 'sentry/views/performance/traceDetails/utils';
  50. import {generateReplayLink} from 'sentry/views/performance/transactionSummary/utils';
  51. import {
  52. getExpandedResults,
  53. getTargetForTransactionSummaryLink,
  54. pushEventViewToLocation,
  55. } from '../utils';
  56. import {QuickContextHoverWrapper} from './quickContext/quickContextWrapper';
  57. import {ContextType} from './quickContext/utils';
  58. import CellAction, {Actions, updateQuery} from './cellAction';
  59. import ColumnEditModal, {modalCss} from './columnEditModal';
  60. import TableActions from './tableActions';
  61. import TopResultsIndicator from './topResultsIndicator';
  62. import {TableColumn} from './types';
  63. export type TableViewProps = {
  64. error: string | null;
  65. eventView: EventView;
  66. isFirstPage: boolean;
  67. isLoading: boolean;
  68. location: Location;
  69. measurementKeys: null | string[];
  70. onChangeShowTags: () => void;
  71. organization: Organization;
  72. showTags: boolean;
  73. tableData: TableData | null | undefined;
  74. title: string;
  75. customMeasurements?: CustomMeasurementCollection;
  76. isHomepage?: boolean;
  77. spanOperationBreakdownKeys?: string[];
  78. };
  79. /**
  80. * The `TableView` is marked with leading _ in its method names. It consumes
  81. * the EventView object given in its props to generate new EventView objects
  82. * for actions like resizing column.
  83. *
  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. supportsInvestigationRule
  531. />
  532. );
  533. }
  534. const {error, eventView, isLoading, location, tableData} = props;
  535. const columnOrder = eventView.getColumns();
  536. const columnSortBy = eventView.getSorts();
  537. const prependColumnWidths = eventView.hasAggregateField()
  538. ? ['40px']
  539. : eventView.hasIdField()
  540. ? []
  541. : [`minmax(${COL_WIDTH_MINIMUM}px, max-content)`];
  542. return (
  543. <GridEditable
  544. isLoading={isLoading}
  545. error={error}
  546. data={tableData ? tableData.data : []}
  547. columnOrder={columnOrder}
  548. columnSortBy={columnSortBy}
  549. title={t('Results')}
  550. grid={{
  551. renderHeadCell: _renderGridHeaderCell as any,
  552. renderBodyCell: _renderGridBodyCell as any,
  553. onResizeColumn: _resizeColumn as any,
  554. renderPrependColumns: _renderPrependColumns as any,
  555. prependColumnWidths,
  556. }}
  557. headerButtons={renderHeaderButtons}
  558. location={location}
  559. />
  560. );
  561. }
  562. const PrependHeader = styled('span')`
  563. color: ${p => p.theme.subText};
  564. `;
  565. const StyledTooltip = styled(Tooltip)`
  566. display: initial;
  567. max-width: max-content;
  568. `;
  569. export const StyledLink = styled(Link)`
  570. & div {
  571. display: inline;
  572. }
  573. `;
  574. export const TransactionLink = styled(Link)`
  575. ${p => p.theme.overflowEllipsis}
  576. `;
  577. const StyledIcon = styled(IconStack)`
  578. vertical-align: middle;
  579. `;
  580. export default TableView;