tableView.tsx 19 KB

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