tableView.tsx 19 KB

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