tableView.tsx 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637
  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 {defined} from 'sentry/utils';
  19. import {trackAnalyticsEvent} 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 getRouteStringFromRoutes from 'sentry/utils/getRouteStringFromRoutes';
  43. import {decodeList} from 'sentry/utils/queryString';
  44. import {MutableSearch} from 'sentry/utils/tokenizeSearch';
  45. import useProjects from 'sentry/utils/useProjects';
  46. import {useRoutes} from 'sentry/utils/useRoutes';
  47. import {normalizeUrl} from 'sentry/utils/withDomainRequired';
  48. import {getTraceDetailsUrl} from 'sentry/views/performance/traceDetails/utils';
  49. import {transactionSummaryRouteWithQuery} from 'sentry/views/performance/transactionSummary/utils';
  50. import {getExpandedResults, pushEventViewToLocation} from '../utils';
  51. import {QuickContextHoverWrapper} from './quickContext/quickContextWrapper';
  52. import {ContextType} from './quickContext/utils';
  53. import CellAction, {Actions, updateQuery} from './cellAction';
  54. import ColumnEditModal, {modalCss} from './columnEditModal';
  55. import TableActions from './tableActions';
  56. import TopResultsIndicator from './topResultsIndicator';
  57. import {TableColumn} from './types';
  58. export type TableViewProps = {
  59. error: string | null;
  60. eventView: EventView;
  61. isFirstPage: boolean;
  62. isLoading: boolean;
  63. location: Location;
  64. measurementKeys: null | string[];
  65. onChangeShowTags: () => void;
  66. organization: Organization;
  67. showTags: boolean;
  68. tableData: TableData | null | undefined;
  69. title: string;
  70. customMeasurements?: CustomMeasurementCollection;
  71. isHomepage?: boolean;
  72. spanOperationBreakdownKeys?: string[];
  73. };
  74. /**
  75. * The `TableView` is marked with leading _ in its method names. It consumes
  76. * the EventView object given in its props to generate new EventView objects
  77. * for actions like resizing column.
  78. * The entire state of the table view (or event view) is co-located within
  79. * the EventView object. This object is fed from the props.
  80. *
  81. * Attempting to modify the state, and therefore, modifying the given EventView
  82. * object given from its props, will generate new instances of EventView objects.
  83. *
  84. * In most cases, the new EventView object differs from the previous EventView
  85. * object. The new EventView object is pushed to the location object.
  86. */
  87. function TableView(props: TableViewProps) {
  88. const {projects} = useProjects();
  89. const routes = useRoutes();
  90. /**
  91. * Updates a column on resizing
  92. */
  93. function _resizeColumn(
  94. columnIndex: number,
  95. nextColumn: TableColumn<keyof TableDataRow>
  96. ) {
  97. const {location, eventView} = props;
  98. const newWidth = nextColumn.width ? Number(nextColumn.width) : COL_WIDTH_UNDEFINED;
  99. const nextEventView = eventView.withResizedColumn(columnIndex, newWidth);
  100. pushEventViewToLocation({
  101. location,
  102. nextEventView,
  103. extraQuery: pickRelevantLocationQueryStrings(location),
  104. });
  105. }
  106. function _renderPrependColumns(
  107. isHeader: boolean,
  108. dataRow?: any,
  109. rowIndex?: number
  110. ): React.ReactNode[] {
  111. const {organization, eventView, tableData, location, isHomepage} = props;
  112. const hasAggregates = eventView.hasAggregateField();
  113. const hasIdField = eventView.hasIdField();
  114. if (isHeader) {
  115. if (hasAggregates) {
  116. return [
  117. <PrependHeader key="header-icon">
  118. <IconStack size="sm" />
  119. </PrependHeader>,
  120. ];
  121. }
  122. if (!hasIdField) {
  123. return [
  124. <PrependHeader key="header-event-id">
  125. <SortLink
  126. align="left"
  127. title={t('event id')}
  128. direction={undefined}
  129. canSort={false}
  130. generateSortLink={() => undefined}
  131. />
  132. </PrependHeader>,
  133. ];
  134. }
  135. return [];
  136. }
  137. if (hasAggregates) {
  138. const nextView = getExpandedResults(eventView, {}, dataRow);
  139. const target = {
  140. pathname: location.pathname,
  141. query: nextView.generateQueryStringObject(),
  142. };
  143. return [
  144. <Tooltip key={`eventlink${rowIndex}`} title={t('Open Group')}>
  145. <Link
  146. to={target}
  147. data-test-id="open-group"
  148. onClick={() => {
  149. if (nextView.isEqualTo(eventView)) {
  150. Sentry.captureException(new Error('Failed to drilldown'));
  151. }
  152. }}
  153. >
  154. <StyledIcon size="sm" />
  155. </Link>
  156. </Tooltip>,
  157. ];
  158. }
  159. if (!hasIdField) {
  160. let value = dataRow.id;
  161. if (tableData && tableData.meta) {
  162. const fieldRenderer = getFieldRenderer('id', tableData.meta);
  163. value = fieldRenderer(dataRow, {organization, location});
  164. }
  165. const eventSlug = generateEventSlug(dataRow);
  166. const target = eventDetailsRouteWithEventView({
  167. orgSlug: organization.slug,
  168. eventSlug,
  169. eventView,
  170. isHomepage,
  171. });
  172. const eventIdLink = (
  173. <StyledLink data-test-id="view-event" to={target}>
  174. {value}
  175. </StyledLink>
  176. );
  177. if (!organization.features.includes('discover-quick-context')) {
  178. return [
  179. <Tooltip key={`eventlink${rowIndex}`} title={t('View Event')}>
  180. {eventIdLink}
  181. </Tooltip>,
  182. ];
  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 = organization.features.includes('discover-quick-context') ? (
  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. <StyledTooltip title={t('View Event')}>{idLink}</StyledTooltip>
  286. );
  287. } else if (columnKey === 'trace') {
  288. const dateSelection = eventView.normalizeDateSelection(location);
  289. if (dataRow.trace) {
  290. const target = getTraceDetailsUrl(
  291. organization,
  292. String(dataRow.trace),
  293. dateSelection,
  294. {}
  295. );
  296. cell = (
  297. <Tooltip title={t('View Trace')}>
  298. <StyledLink data-test-id="view-trace" to={target}>
  299. {cell}
  300. </StyledLink>
  301. </Tooltip>
  302. );
  303. }
  304. } else if (columnKey === 'replayId') {
  305. if (dataRow.replayId) {
  306. const replaySlug = `${dataRow['project.name']}:${dataRow.replayId}`;
  307. const referrer = getRouteStringFromRoutes(routes);
  308. const target = {
  309. pathname: `/organizations/${organization.slug}/replays/${replaySlug}/`,
  310. query: {
  311. referrer,
  312. },
  313. };
  314. cell = (
  315. <Tooltip title={t('View Replay')}>
  316. <StyledLink data-test-id="view-replay" to={target}>
  317. {cell}
  318. </StyledLink>
  319. </Tooltip>
  320. );
  321. }
  322. }
  323. const topResultsIndicator =
  324. isFirstPage && isTopEvents && rowIndex < topEvents && columnIndex === 0 ? (
  325. // Add one if we need to include Other in the series
  326. <TopResultsIndicator count={count} index={rowIndex} />
  327. ) : null;
  328. const fieldName = columnKey;
  329. const value = dataRow[fieldName];
  330. if (tableData.meta[fieldName] === 'integer' && defined(value) && value > 999) {
  331. return (
  332. <Tooltip
  333. title={value.toLocaleString()}
  334. containerDisplayMode="block"
  335. position="right"
  336. >
  337. {topResultsIndicator}
  338. <CellAction
  339. column={column}
  340. dataRow={dataRow}
  341. handleCellAction={handleCellAction(dataRow, column)}
  342. >
  343. {cell}
  344. </CellAction>
  345. </Tooltip>
  346. );
  347. }
  348. return (
  349. <Fragment>
  350. {topResultsIndicator}
  351. <CellAction
  352. column={column}
  353. dataRow={dataRow}
  354. handleCellAction={handleCellAction(dataRow, column)}
  355. >
  356. {cell}
  357. </CellAction>
  358. </Fragment>
  359. );
  360. }
  361. function handleEditColumns() {
  362. const {
  363. organization,
  364. eventView,
  365. measurementKeys,
  366. spanOperationBreakdownKeys,
  367. customMeasurements,
  368. } = props;
  369. openModal(
  370. modalProps => (
  371. <ColumnEditModal
  372. {...modalProps}
  373. organization={organization}
  374. measurementKeys={measurementKeys}
  375. spanOperationBreakdownKeys={spanOperationBreakdownKeys}
  376. columns={eventView.getColumns().map(col => col.column)}
  377. onApply={handleUpdateColumns}
  378. customMeasurements={customMeasurements}
  379. />
  380. ),
  381. {modalCss, closeEvents: 'escape-key'}
  382. );
  383. }
  384. function handleCellAction(
  385. dataRow: TableDataRow,
  386. column: TableColumn<keyof TableDataRow>
  387. ) {
  388. return (action: Actions, value: React.ReactText) => {
  389. const {eventView, organization, location, tableData, isHomepage} = props;
  390. const query = new MutableSearch(eventView.query);
  391. let nextView = eventView.clone();
  392. trackAnalyticsEvent({
  393. eventKey: 'discover_v2.results.cellaction',
  394. eventName: 'Discoverv2: Cell Action Clicked',
  395. organization_id: parseInt(organization.id, 10),
  396. action,
  397. });
  398. switch (action) {
  399. case Actions.TRANSACTION: {
  400. const maybeProject = projects.find(
  401. project =>
  402. project.slug &&
  403. [dataRow['project.name'], dataRow.project].includes(project.slug)
  404. );
  405. const projectID = maybeProject ? [maybeProject.id] : undefined;
  406. const next = transactionSummaryRouteWithQuery({
  407. orgSlug: organization.slug,
  408. transaction: String(value),
  409. projectID,
  410. query: nextView.getPageFiltersQuery(),
  411. });
  412. browserHistory.push(normalizeUrl(next));
  413. return;
  414. }
  415. case Actions.RELEASE: {
  416. const maybeProject = projects.find(project => {
  417. return project.slug === dataRow.project;
  418. });
  419. browserHistory.push(
  420. normalizeUrl({
  421. pathname: `/organizations/${
  422. organization.slug
  423. }/releases/${encodeURIComponent(value)}/`,
  424. query: {
  425. ...nextView.getPageFiltersQuery(),
  426. project: maybeProject ? maybeProject.id : undefined,
  427. },
  428. })
  429. );
  430. return;
  431. }
  432. case Actions.DRILLDOWN: {
  433. // count_unique(column) drilldown
  434. trackAnalyticsEvent({
  435. eventKey: 'discover_v2.results.drilldown',
  436. eventName: 'Discoverv2: Click aggregate drilldown',
  437. organization_id: parseInt(organization.id, 10),
  438. });
  439. // Drilldown into each distinct value and get a count() for each value.
  440. nextView = getExpandedResults(nextView, {}, dataRow).withNewColumn({
  441. kind: 'function',
  442. function: ['count', '', undefined, undefined],
  443. });
  444. browserHistory.push(
  445. normalizeUrl(nextView.getResultsViewUrlTarget(organization.slug, isHomepage))
  446. );
  447. return;
  448. }
  449. default: {
  450. // Some custom perf metrics have units.
  451. // These custom perf metrics need to be adjusted to the correct value.
  452. let cellValue = value;
  453. const unit = tableData?.meta?.units?.[column.name];
  454. if (typeof cellValue === 'number' && unit) {
  455. if (Object.keys(SIZE_UNITS).includes(unit)) {
  456. cellValue *= SIZE_UNITS[unit];
  457. } else if (Object.keys(DURATION_UNITS).includes(unit)) {
  458. cellValue *= DURATION_UNITS[unit];
  459. }
  460. }
  461. updateQuery(query, action, column, cellValue);
  462. }
  463. }
  464. nextView.query = query.formatString();
  465. const target = nextView.getResultsViewUrlTarget(organization.slug, isHomepage);
  466. // Get yAxis from location
  467. target.query.yAxis = decodeList(location.query.yAxis);
  468. browserHistory.push(normalizeUrl(target));
  469. };
  470. }
  471. function handleUpdateColumns(columns: Column[]): void {
  472. const {organization, eventView, location, isHomepage} = props;
  473. // metrics
  474. trackAnalyticsEvent({
  475. eventKey: 'discover_v2.update_columns',
  476. eventName: 'Discoverv2: Update columns',
  477. organization_id: parseInt(organization.id, 10),
  478. });
  479. const nextView = eventView.withColumns(columns);
  480. const resultsViewUrlTarget = nextView.getResultsViewUrlTarget(
  481. organization.slug,
  482. isHomepage
  483. );
  484. // Need to pull yAxis from location since eventView only stores 1 yAxis field at time
  485. const previousYAxis = decodeList(location.query.yAxis);
  486. resultsViewUrlTarget.query.yAxis = previousYAxis.filter(yAxis =>
  487. nextView.getYAxisOptions().find(({value}) => value === yAxis)
  488. );
  489. browserHistory.push(normalizeUrl(resultsViewUrlTarget));
  490. }
  491. function renderHeaderButtons() {
  492. const {
  493. organization,
  494. title,
  495. eventView,
  496. isLoading,
  497. error,
  498. tableData,
  499. location,
  500. onChangeShowTags,
  501. showTags,
  502. } = props;
  503. return (
  504. <TableActions
  505. title={title}
  506. isLoading={isLoading}
  507. error={error}
  508. organization={organization}
  509. eventView={eventView}
  510. onEdit={handleEditColumns}
  511. tableData={tableData}
  512. location={location}
  513. onChangeShowTags={onChangeShowTags}
  514. showTags={showTags}
  515. />
  516. );
  517. }
  518. const {isLoading, error, location, tableData, eventView} = props;
  519. const columnOrder = eventView.getColumns();
  520. const columnSortBy = eventView.getSorts();
  521. const prependColumnWidths = eventView.hasAggregateField()
  522. ? ['40px']
  523. : eventView.hasIdField()
  524. ? []
  525. : [`minmax(${COL_WIDTH_MINIMUM}px, max-content)`];
  526. return (
  527. <GridEditable
  528. isLoading={isLoading}
  529. error={error}
  530. data={tableData ? tableData.data : []}
  531. columnOrder={columnOrder}
  532. columnSortBy={columnSortBy}
  533. title={t('Results')}
  534. grid={{
  535. renderHeadCell: _renderGridHeaderCell as any,
  536. renderBodyCell: _renderGridBodyCell as any,
  537. onResizeColumn: _resizeColumn as any,
  538. renderPrependColumns: _renderPrependColumns as any,
  539. prependColumnWidths,
  540. }}
  541. headerButtons={renderHeaderButtons}
  542. location={location}
  543. />
  544. );
  545. }
  546. const PrependHeader = styled('span')`
  547. color: ${p => p.theme.subText};
  548. `;
  549. const StyledTooltip = styled(Tooltip)`
  550. display: initial;
  551. max-width: max-content;
  552. `;
  553. const StyledLink = styled(Link)`
  554. & div {
  555. display: inline;
  556. }
  557. `;
  558. const StyledIcon = styled(IconStack)`
  559. vertical-align: middle;
  560. `;
  561. export default TableView;