tableView.tsx 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661
  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 {trackAnalyticsEvent} from 'sentry/utils/analytics';
  21. import trackAdvancedAnalyticsEvent from 'sentry/utils/analytics/trackAdvancedAnalyticsEvent';
  22. import {CustomMeasurementCollection} from 'sentry/utils/customMeasurements/customMeasurements';
  23. import {TableData, TableDataRow} from 'sentry/utils/discover/discoverQuery';
  24. import EventView, {
  25. isFieldSortable,
  26. pickRelevantLocationQueryStrings,
  27. } from 'sentry/utils/discover/eventView';
  28. import {
  29. DURATION_UNITS,
  30. getFieldRenderer,
  31. SIZE_UNITS,
  32. } from 'sentry/utils/discover/fieldRenderers';
  33. import {
  34. Column,
  35. fieldAlignment,
  36. getEquationAliasIndex,
  37. isEquationAlias,
  38. } from 'sentry/utils/discover/fields';
  39. import {DisplayModes, TOP_N} from 'sentry/utils/discover/types';
  40. import {
  41. eventDetailsRouteWithEventView,
  42. generateEventSlug,
  43. } from 'sentry/utils/discover/urls';
  44. import ViewReplayLink from 'sentry/utils/discover/viewReplayLink';
  45. import {getShortEventId} from 'sentry/utils/events';
  46. import {generateProfileFlamechartRoute} from 'sentry/utils/profiling/routes';
  47. import {decodeList} from 'sentry/utils/queryString';
  48. import {MutableSearch} from 'sentry/utils/tokenizeSearch';
  49. import useProjects from 'sentry/utils/useProjects';
  50. import {useRoutes} from 'sentry/utils/useRoutes';
  51. import {normalizeUrl} from 'sentry/utils/withDomainRequired';
  52. import {getTraceDetailsUrl} from 'sentry/views/performance/traceDetails/utils';
  53. import {
  54. generateReplayLink,
  55. transactionSummaryRouteWithQuery,
  56. } from 'sentry/views/performance/transactionSummary/utils';
  57. import {getExpandedResults, pushEventViewToLocation} from '../utils';
  58. import {QuickContextHoverWrapper} from './quickContext/quickContextWrapper';
  59. import {ContextType} from './quickContext/utils';
  60. import CellAction, {Actions, updateQuery} from './cellAction';
  61. import ColumnEditModal, {modalCss} from './columnEditModal';
  62. import TableActions from './tableActions';
  63. import TopResultsIndicator from './topResultsIndicator';
  64. import {TableColumn} from './types';
  65. export type TableViewProps = {
  66. error: string | null;
  67. eventView: EventView;
  68. isFirstPage: boolean;
  69. isLoading: boolean;
  70. location: Location;
  71. measurementKeys: null | string[];
  72. onChangeShowTags: () => void;
  73. organization: Organization;
  74. showTags: boolean;
  75. tableData: TableData | null | undefined;
  76. title: string;
  77. customMeasurements?: CustomMeasurementCollection;
  78. isHomepage?: boolean;
  79. spanOperationBreakdownKeys?: string[];
  80. };
  81. /**
  82. * The `TableView` is marked with leading _ in its method names. It consumes
  83. * the EventView object given in its props to generate new EventView objects
  84. * for actions like resizing column.
  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 && 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 === 'trace') {
  287. const dateSelection = eventView.normalizeDateSelection(location);
  288. if (dataRow.trace) {
  289. const target = getTraceDetailsUrl(
  290. organization,
  291. String(dataRow.trace),
  292. dateSelection,
  293. {}
  294. );
  295. cell = (
  296. <Tooltip title={t('View Trace')}>
  297. <StyledLink data-test-id="view-trace" to={target}>
  298. {cell}
  299. </StyledLink>
  300. </Tooltip>
  301. );
  302. }
  303. } else if (columnKey === 'replayId') {
  304. if (dataRow.replayId) {
  305. if (!dataRow['project.name']) {
  306. return getShortEventId(String(dataRow.replayId));
  307. }
  308. const target = replayLinkGenerator(organization, dataRow, undefined);
  309. cell = (
  310. <ViewReplayLink replayId={dataRow.replayId} to={target}>
  311. {cell}
  312. </ViewReplayLink>
  313. );
  314. }
  315. } else if (columnKey === 'profile.id') {
  316. const projectSlug = dataRow.project || dataRow['project.name'];
  317. const profileId = dataRow['profile.id'];
  318. if (projectSlug && profileId) {
  319. const target = generateProfileFlamechartRoute({
  320. orgSlug: organization.slug,
  321. projectSlug: String(projectSlug),
  322. profileId: String(profileId),
  323. });
  324. cell = (
  325. <StyledTooltip title={t('View Profile')}>
  326. <StyledLink
  327. data-test-id="view-profile"
  328. to={target}
  329. onClick={() =>
  330. trackAdvancedAnalyticsEvent('profiling_views.go_to_flamegraph', {
  331. organization,
  332. source: 'discover.table',
  333. })
  334. }
  335. >
  336. {cell}
  337. </StyledLink>
  338. </StyledTooltip>
  339. );
  340. }
  341. }
  342. const topResultsIndicator =
  343. isFirstPage && isTopEvents && rowIndex < topEvents && columnIndex === 0 ? (
  344. // Add one if we need to include Other in the series
  345. <TopResultsIndicator count={count} index={rowIndex} />
  346. ) : null;
  347. const fieldName = columnKey;
  348. const value = dataRow[fieldName];
  349. if (tableData.meta[fieldName] === 'integer' && defined(value) && value > 999) {
  350. return (
  351. <Tooltip
  352. title={value.toLocaleString()}
  353. containerDisplayMode="block"
  354. position="right"
  355. >
  356. {topResultsIndicator}
  357. <CellAction
  358. column={column}
  359. dataRow={dataRow}
  360. handleCellAction={handleCellAction(dataRow, column)}
  361. >
  362. {cell}
  363. </CellAction>
  364. </Tooltip>
  365. );
  366. }
  367. return (
  368. <Fragment>
  369. {topResultsIndicator}
  370. <CellAction
  371. column={column}
  372. dataRow={dataRow}
  373. handleCellAction={handleCellAction(dataRow, column)}
  374. >
  375. {cell}
  376. </CellAction>
  377. </Fragment>
  378. );
  379. }
  380. function handleEditColumns() {
  381. const {
  382. organization,
  383. eventView,
  384. measurementKeys,
  385. spanOperationBreakdownKeys,
  386. customMeasurements,
  387. } = props;
  388. openModal(
  389. modalProps => (
  390. <ColumnEditModal
  391. {...modalProps}
  392. organization={organization}
  393. measurementKeys={measurementKeys}
  394. spanOperationBreakdownKeys={spanOperationBreakdownKeys}
  395. columns={eventView.getColumns().map(col => col.column)}
  396. onApply={handleUpdateColumns}
  397. customMeasurements={customMeasurements}
  398. />
  399. ),
  400. {modalCss, closeEvents: 'escape-key'}
  401. );
  402. }
  403. function handleCellAction(
  404. dataRow: TableDataRow,
  405. column: TableColumn<keyof TableDataRow>
  406. ) {
  407. return (action: Actions, value: React.ReactText) => {
  408. const {eventView, organization, location, tableData, isHomepage} = props;
  409. const query = new MutableSearch(eventView.query);
  410. let nextView = eventView.clone();
  411. trackAnalyticsEvent({
  412. eventKey: 'discover_v2.results.cellaction',
  413. eventName: 'Discoverv2: Cell Action Clicked',
  414. organization_id: parseInt(organization.id, 10),
  415. action,
  416. });
  417. switch (action) {
  418. case Actions.TRANSACTION: {
  419. const maybeProject = projects.find(
  420. project =>
  421. project.slug &&
  422. [dataRow['project.name'], dataRow.project].includes(project.slug)
  423. );
  424. const projectID = maybeProject ? [maybeProject.id] : undefined;
  425. const next = transactionSummaryRouteWithQuery({
  426. orgSlug: organization.slug,
  427. transaction: String(value),
  428. projectID,
  429. query: nextView.getPageFiltersQuery(),
  430. });
  431. browserHistory.push(normalizeUrl(next));
  432. return;
  433. }
  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. trackAnalyticsEvent({
  454. eventKey: 'discover_v2.results.drilldown',
  455. eventName: 'Discoverv2: Click aggregate drilldown',
  456. organization_id: parseInt(organization.id, 10),
  457. });
  458. // Drilldown into each distinct value and get a count() for each value.
  459. nextView = getExpandedResults(nextView, {}, dataRow).withNewColumn({
  460. kind: 'function',
  461. function: ['count', '', undefined, undefined],
  462. });
  463. browserHistory.push(
  464. normalizeUrl(nextView.getResultsViewUrlTarget(organization.slug, isHomepage))
  465. );
  466. return;
  467. }
  468. default: {
  469. // Some custom perf metrics have units.
  470. // These custom perf metrics need to be adjusted to the correct value.
  471. let cellValue = value;
  472. const unit = tableData?.meta?.units?.[column.name];
  473. if (typeof cellValue === 'number' && unit) {
  474. if (Object.keys(SIZE_UNITS).includes(unit)) {
  475. cellValue *= SIZE_UNITS[unit];
  476. } else if (Object.keys(DURATION_UNITS).includes(unit)) {
  477. cellValue *= DURATION_UNITS[unit];
  478. }
  479. }
  480. updateQuery(query, action, column, cellValue);
  481. }
  482. }
  483. nextView.query = query.formatString();
  484. const target = nextView.getResultsViewUrlTarget(organization.slug, isHomepage);
  485. // Get yAxis from location
  486. target.query.yAxis = decodeList(location.query.yAxis);
  487. browserHistory.push(normalizeUrl(target));
  488. };
  489. }
  490. function handleUpdateColumns(columns: Column[]): void {
  491. const {organization, eventView, location, isHomepage} = props;
  492. // metrics
  493. trackAnalyticsEvent({
  494. eventKey: 'discover_v2.update_columns',
  495. eventName: 'Discoverv2: Update columns',
  496. organization_id: parseInt(organization.id, 10),
  497. });
  498. const nextView = eventView.withColumns(columns);
  499. const resultsViewUrlTarget = nextView.getResultsViewUrlTarget(
  500. organization.slug,
  501. isHomepage
  502. );
  503. // Need to pull yAxis from location since eventView only stores 1 yAxis field at time
  504. const previousYAxis = decodeList(location.query.yAxis);
  505. resultsViewUrlTarget.query.yAxis = previousYAxis.filter(yAxis =>
  506. nextView.getYAxisOptions().find(({value}) => value === yAxis)
  507. );
  508. browserHistory.push(normalizeUrl(resultsViewUrlTarget));
  509. }
  510. function renderHeaderButtons() {
  511. const {
  512. organization,
  513. title,
  514. eventView,
  515. isLoading,
  516. error,
  517. tableData,
  518. location,
  519. onChangeShowTags,
  520. showTags,
  521. } = props;
  522. return (
  523. <TableActions
  524. title={title}
  525. isLoading={isLoading}
  526. error={error}
  527. organization={organization}
  528. eventView={eventView}
  529. onEdit={handleEditColumns}
  530. tableData={tableData}
  531. location={location}
  532. onChangeShowTags={onChangeShowTags}
  533. showTags={showTags}
  534. />
  535. );
  536. }
  537. const {error, eventView, isLoading, location, organization, tableData} = props;
  538. const columnOrder = eventView.getColumns();
  539. const columnSortBy = eventView.getSorts();
  540. const prependColumnWidths = eventView.hasAggregateField()
  541. ? ['40px']
  542. : eventView.hasIdField()
  543. ? []
  544. : [`minmax(${COL_WIDTH_MINIMUM}px, max-content)`];
  545. const replayIds = tableData?.data?.map(row => String(row.replayId)).filter(Boolean);
  546. return (
  547. <ReplayIdCountProvider organization={organization} replayIds={replayIds}>
  548. <GridEditable
  549. isLoading={isLoading}
  550. error={error}
  551. data={tableData ? tableData.data : []}
  552. columnOrder={columnOrder}
  553. columnSortBy={columnSortBy}
  554. title={t('Results')}
  555. grid={{
  556. renderHeadCell: _renderGridHeaderCell as any,
  557. renderBodyCell: _renderGridBodyCell as any,
  558. onResizeColumn: _resizeColumn as any,
  559. renderPrependColumns: _renderPrependColumns as any,
  560. prependColumnWidths,
  561. }}
  562. headerButtons={renderHeaderButtons}
  563. location={location}
  564. />
  565. </ReplayIdCountProvider>
  566. );
  567. }
  568. const PrependHeader = styled('span')`
  569. color: ${p => p.theme.subText};
  570. `;
  571. const StyledTooltip = styled(Tooltip)`
  572. display: initial;
  573. max-width: max-content;
  574. `;
  575. const StyledLink = styled(Link)`
  576. & div {
  577. display: inline;
  578. }
  579. `;
  580. const StyledIcon = styled(IconStack)`
  581. vertical-align: middle;
  582. `;
  583. export default TableView;