tableView.tsx 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571
  1. import {Component, 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, Project} 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 {decodeList} from 'sentry/utils/queryString';
  43. import {MutableSearch} from 'sentry/utils/tokenizeSearch';
  44. import withProjects from 'sentry/utils/withProjects';
  45. import {getTraceDetailsUrl} from 'sentry/views/performance/traceDetails/utils';
  46. import {transactionSummaryRouteWithQuery} from 'sentry/views/performance/transactionSummary/utils';
  47. import {getExpandedResults, pushEventViewToLocation} from '../utils';
  48. import CellAction, {Actions, updateQuery} from './cellAction';
  49. import ColumnEditModal, {modalCss} from './columnEditModal';
  50. import TableActions from './tableActions';
  51. import TopResultsIndicator from './topResultsIndicator';
  52. import {TableColumn} from './types';
  53. export type TableViewProps = {
  54. error: string | null;
  55. eventView: EventView;
  56. isFirstPage: boolean;
  57. isLoading: boolean;
  58. location: Location;
  59. measurementKeys: null | string[];
  60. onChangeShowTags: () => void;
  61. organization: Organization;
  62. projects: Project[];
  63. showTags: boolean;
  64. tableData: TableData | null | undefined;
  65. title: string;
  66. customMeasurements?: CustomMeasurementCollection;
  67. spanOperationBreakdownKeys?: string[];
  68. };
  69. /**
  70. * The `TableView` is marked with leading _ in its method names. It consumes
  71. * the EventView object given in its props to generate new EventView objects
  72. * for actions like resizing column.
  73. * The entire state of the table view (or event view) is co-located within
  74. * the EventView object. This object is fed from the props.
  75. *
  76. * Attempting to modify the state, and therefore, modifying the given EventView
  77. * object given from its props, will generate new instances of EventView objects.
  78. *
  79. * In most cases, the new EventView object differs from the previous EventView
  80. * object. The new EventView object is pushed to the location object.
  81. */
  82. class TableView extends Component<TableViewProps> {
  83. /**
  84. * Updates a column on resizing
  85. */
  86. _resizeColumn = (columnIndex: number, nextColumn: TableColumn<keyof TableDataRow>) => {
  87. const {location, eventView} = this.props;
  88. const newWidth = nextColumn.width ? Number(nextColumn.width) : COL_WIDTH_UNDEFINED;
  89. const nextEventView = eventView.withResizedColumn(columnIndex, newWidth);
  90. pushEventViewToLocation({
  91. location,
  92. nextEventView,
  93. extraQuery: pickRelevantLocationQueryStrings(location),
  94. });
  95. };
  96. _renderPrependColumns = (
  97. isHeader: boolean,
  98. dataRow?: any,
  99. rowIndex?: number
  100. ): React.ReactNode[] => {
  101. const {organization, eventView, tableData, location} = this.props;
  102. const hasAggregates = eventView.hasAggregateField();
  103. const hasIdField = eventView.hasIdField();
  104. if (isHeader) {
  105. if (hasAggregates) {
  106. return [
  107. <PrependHeader key="header-icon">
  108. <IconStack size="sm" />
  109. </PrependHeader>,
  110. ];
  111. }
  112. if (!hasIdField) {
  113. return [
  114. <PrependHeader key="header-event-id">
  115. <SortLink
  116. align="left"
  117. title={t('event id')}
  118. direction={undefined}
  119. canSort={false}
  120. generateSortLink={() => undefined}
  121. />
  122. </PrependHeader>,
  123. ];
  124. }
  125. return [];
  126. }
  127. if (hasAggregates) {
  128. const nextView = getExpandedResults(eventView, {}, dataRow);
  129. const target = {
  130. pathname: location.pathname,
  131. query: nextView.generateQueryStringObject(),
  132. };
  133. return [
  134. <Tooltip key={`eventlink${rowIndex}`} title={t('Open Group')}>
  135. <Link
  136. to={target}
  137. data-test-id="open-group"
  138. onClick={() => {
  139. if (nextView.isEqualTo(eventView)) {
  140. Sentry.captureException(new Error('Failed to drilldown'));
  141. }
  142. }}
  143. >
  144. <StyledIcon size="sm" />
  145. </Link>
  146. </Tooltip>,
  147. ];
  148. }
  149. if (!hasIdField) {
  150. let value = dataRow.id;
  151. if (tableData && tableData.meta) {
  152. const fieldRenderer = getFieldRenderer('id', tableData.meta);
  153. value = fieldRenderer(dataRow, {organization, location});
  154. }
  155. const eventSlug = generateEventSlug(dataRow);
  156. const target = eventDetailsRouteWithEventView({
  157. orgSlug: organization.slug,
  158. eventSlug,
  159. eventView,
  160. });
  161. return [
  162. <Tooltip key={`eventlink${rowIndex}`} title={t('View Event')}>
  163. <StyledLink data-test-id="view-event" to={target}>
  164. {value}
  165. </StyledLink>
  166. </Tooltip>,
  167. ];
  168. }
  169. return [];
  170. };
  171. _renderGridHeaderCell = (column: TableColumn<keyof TableDataRow>): React.ReactNode => {
  172. const {eventView, location, tableData} = this.props;
  173. const tableMeta = tableData?.meta;
  174. const align = fieldAlignment(column.name, column.type, tableMeta);
  175. const field = {field: column.key as string, width: column.width};
  176. function generateSortLink(): LocationDescriptorObject | undefined {
  177. if (!tableMeta) {
  178. return undefined;
  179. }
  180. const nextEventView = eventView.sortOnField(field, tableMeta);
  181. const queryStringObject = nextEventView.generateQueryStringObject();
  182. // Need to pull yAxis from location since eventView only stores 1 yAxis field at time
  183. queryStringObject.yAxis = decodeList(location.query.yAxis);
  184. return {
  185. ...location,
  186. query: queryStringObject,
  187. };
  188. }
  189. const currentSort = eventView.sortForField(field, tableMeta);
  190. const canSort = isFieldSortable(field, tableMeta);
  191. const titleText = isEquationAlias(column.name)
  192. ? eventView.getEquations()[getEquationAliasIndex(column.name)]
  193. : column.name;
  194. const title = (
  195. <StyledTooltip title={titleText}>
  196. <Truncate value={titleText} maxLength={60} expandable={false} />
  197. </StyledTooltip>
  198. );
  199. return (
  200. <SortLink
  201. align={align}
  202. title={title}
  203. direction={currentSort ? currentSort.kind : undefined}
  204. canSort={canSort}
  205. generateSortLink={generateSortLink}
  206. />
  207. );
  208. };
  209. _renderGridBodyCell = (
  210. column: TableColumn<keyof TableDataRow>,
  211. dataRow: TableDataRow,
  212. rowIndex: number,
  213. columnIndex: number
  214. ): React.ReactNode => {
  215. const {isFirstPage, eventView, location, organization, tableData} = this.props;
  216. if (!tableData || !tableData.meta) {
  217. return dataRow[column.key];
  218. }
  219. const columnKey = String(column.key);
  220. const fieldRenderer = getFieldRenderer(
  221. columnKey,
  222. tableData.meta,
  223. !organization.features.includes('discover-frontend-use-events-endpoint')
  224. );
  225. const display = eventView.getDisplayMode();
  226. const isTopEvents =
  227. display === DisplayModes.TOP5 || display === DisplayModes.DAILYTOP5;
  228. const topEvents = eventView.topEvents ? parseInt(eventView.topEvents, 10) : TOP_N;
  229. const count = Math.min(tableData?.data?.length ?? topEvents, topEvents);
  230. const unit = tableData.meta.units?.[columnKey];
  231. let cell = fieldRenderer(dataRow, {organization, location, unit});
  232. if (columnKey === 'id') {
  233. const eventSlug = generateEventSlug(dataRow);
  234. const target = eventDetailsRouteWithEventView({
  235. orgSlug: organization.slug,
  236. eventSlug,
  237. eventView,
  238. });
  239. cell = (
  240. <Tooltip title={t('View Event')}>
  241. <StyledLink data-test-id="view-event" to={target}>
  242. {cell}
  243. </StyledLink>
  244. </Tooltip>
  245. );
  246. } else if (columnKey === 'trace') {
  247. const dateSelection = eventView.normalizeDateSelection(location);
  248. if (dataRow.trace) {
  249. const target = getTraceDetailsUrl(
  250. organization,
  251. String(dataRow.trace),
  252. dateSelection,
  253. {}
  254. );
  255. cell = (
  256. <Tooltip title={t('View Trace')}>
  257. <StyledLink data-test-id="view-trace" to={target}>
  258. {cell}
  259. </StyledLink>
  260. </Tooltip>
  261. );
  262. }
  263. }
  264. const topResultsIndicator =
  265. isFirstPage && isTopEvents && rowIndex < topEvents && columnIndex === 0 ? (
  266. // Add one if we need to include Other in the series
  267. <TopResultsIndicator count={count} index={rowIndex} />
  268. ) : null;
  269. const fieldName = columnKey;
  270. const value = dataRow[fieldName];
  271. if (tableData.meta[fieldName] === 'integer' && defined(value) && value > 999) {
  272. return (
  273. <Tooltip
  274. title={value.toLocaleString()}
  275. containerDisplayMode="block"
  276. position="right"
  277. >
  278. {topResultsIndicator}
  279. <CellAction
  280. column={column}
  281. dataRow={dataRow}
  282. handleCellAction={this.handleCellAction(dataRow, column)}
  283. >
  284. {cell}
  285. </CellAction>
  286. </Tooltip>
  287. );
  288. }
  289. return (
  290. <Fragment>
  291. {topResultsIndicator}
  292. <CellAction
  293. column={column}
  294. dataRow={dataRow}
  295. handleCellAction={this.handleCellAction(dataRow, column)}
  296. >
  297. {cell}
  298. </CellAction>
  299. </Fragment>
  300. );
  301. };
  302. handleEditColumns = () => {
  303. const {
  304. organization,
  305. eventView,
  306. measurementKeys,
  307. spanOperationBreakdownKeys,
  308. customMeasurements,
  309. } = this.props;
  310. const hasBreakdownFeature = organization.features.includes(
  311. 'performance-ops-breakdown'
  312. );
  313. openModal(
  314. modalProps => (
  315. <ColumnEditModal
  316. {...modalProps}
  317. organization={organization}
  318. measurementKeys={measurementKeys}
  319. spanOperationBreakdownKeys={
  320. hasBreakdownFeature ? spanOperationBreakdownKeys : undefined
  321. }
  322. columns={eventView.getColumns().map(col => col.column)}
  323. onApply={this.handleUpdateColumns}
  324. customMeasurements={customMeasurements}
  325. />
  326. ),
  327. {modalCss, backdrop: 'static'}
  328. );
  329. };
  330. handleCellAction = (dataRow: TableDataRow, column: TableColumn<keyof TableDataRow>) => {
  331. return (action: Actions, value: React.ReactText) => {
  332. const {eventView, organization, projects, location, tableData} = this.props;
  333. const query = new MutableSearch(eventView.query);
  334. let nextView = eventView.clone();
  335. trackAnalyticsEvent({
  336. eventKey: 'discover_v2.results.cellaction',
  337. eventName: 'Discoverv2: Cell Action Clicked',
  338. organization_id: parseInt(organization.id, 10),
  339. action,
  340. });
  341. switch (action) {
  342. case Actions.TRANSACTION: {
  343. const maybeProject = projects.find(
  344. project =>
  345. project.slug &&
  346. [dataRow['project.name'], dataRow.project].includes(project.slug)
  347. );
  348. const projectID = maybeProject ? [maybeProject.id] : undefined;
  349. const next = transactionSummaryRouteWithQuery({
  350. orgSlug: organization.slug,
  351. transaction: String(value),
  352. projectID,
  353. query: nextView.getPageFiltersQuery(),
  354. });
  355. browserHistory.push(next);
  356. return;
  357. }
  358. case Actions.RELEASE: {
  359. const maybeProject = projects.find(project => {
  360. return project.slug === dataRow.project;
  361. });
  362. browserHistory.push({
  363. pathname: `/organizations/${organization.slug}/releases/${encodeURIComponent(
  364. value
  365. )}/`,
  366. query: {
  367. ...nextView.getPageFiltersQuery(),
  368. project: maybeProject ? maybeProject.id : undefined,
  369. },
  370. });
  371. return;
  372. }
  373. case Actions.DRILLDOWN: {
  374. // count_unique(column) drilldown
  375. trackAnalyticsEvent({
  376. eventKey: 'discover_v2.results.drilldown',
  377. eventName: 'Discoverv2: Click aggregate drilldown',
  378. organization_id: parseInt(organization.id, 10),
  379. });
  380. // Drilldown into each distinct value and get a count() for each value.
  381. nextView = getExpandedResults(nextView, {}, dataRow).withNewColumn({
  382. kind: 'function',
  383. function: ['count', '', undefined, undefined],
  384. });
  385. browserHistory.push(nextView.getResultsViewUrlTarget(organization.slug));
  386. return;
  387. }
  388. default: {
  389. // Some custom perf metrics have units.
  390. // These custom perf metrics need to be adjusted to the correct value.
  391. let cellValue = value;
  392. const unit = tableData?.meta?.units?.[column.name];
  393. if (typeof cellValue === 'number' && unit) {
  394. if (Object.keys(SIZE_UNITS).includes(unit)) {
  395. cellValue *= SIZE_UNITS[unit];
  396. } else if (Object.keys(DURATION_UNITS).includes(unit)) {
  397. cellValue *= DURATION_UNITS[unit];
  398. }
  399. }
  400. updateQuery(query, action, column, cellValue);
  401. }
  402. }
  403. nextView.query = query.formatString();
  404. const target = nextView.getResultsViewUrlTarget(organization.slug);
  405. // Get yAxis from location
  406. target.query.yAxis = decodeList(location.query.yAxis);
  407. browserHistory.push(target);
  408. };
  409. };
  410. handleUpdateColumns = (columns: Column[]): void => {
  411. const {organization, eventView, location} = this.props;
  412. // metrics
  413. trackAnalyticsEvent({
  414. eventKey: 'discover_v2.update_columns',
  415. eventName: 'Discoverv2: Update columns',
  416. organization_id: parseInt(organization.id, 10),
  417. });
  418. const nextView = eventView.withColumns(columns);
  419. const resultsViewUrlTarget = nextView.getResultsViewUrlTarget(organization.slug);
  420. // Need to pull yAxis from location since eventView only stores 1 yAxis field at time
  421. const previousYAxis = decodeList(location.query.yAxis);
  422. resultsViewUrlTarget.query.yAxis = previousYAxis.filter(yAxis =>
  423. nextView.getYAxisOptions().find(({value}) => value === yAxis)
  424. );
  425. browserHistory.push(resultsViewUrlTarget);
  426. };
  427. renderHeaderButtons = () => {
  428. const {
  429. organization,
  430. title,
  431. eventView,
  432. isLoading,
  433. error,
  434. tableData,
  435. location,
  436. onChangeShowTags,
  437. showTags,
  438. } = this.props;
  439. return (
  440. <TableActions
  441. title={title}
  442. isLoading={isLoading}
  443. error={error}
  444. organization={organization}
  445. eventView={eventView}
  446. onEdit={this.handleEditColumns}
  447. tableData={tableData}
  448. location={location}
  449. onChangeShowTags={onChangeShowTags}
  450. showTags={showTags}
  451. />
  452. );
  453. };
  454. render() {
  455. const {isLoading, error, location, tableData, eventView, organization} = this.props;
  456. const columnOrder = eventView.getColumns(
  457. organization.features.includes('discover-frontend-use-events-endpoint')
  458. );
  459. const columnSortBy = eventView.getSorts();
  460. const prependColumnWidths = eventView.hasAggregateField()
  461. ? ['40px']
  462. : eventView.hasIdField()
  463. ? []
  464. : [`minmax(${COL_WIDTH_MINIMUM}px, max-content)`];
  465. return (
  466. <GridEditable
  467. isLoading={isLoading}
  468. error={error}
  469. data={tableData ? tableData.data : []}
  470. columnOrder={columnOrder}
  471. columnSortBy={columnSortBy}
  472. title={t('Results')}
  473. grid={{
  474. renderHeadCell: this._renderGridHeaderCell as any,
  475. renderBodyCell: this._renderGridBodyCell as any,
  476. onResizeColumn: this._resizeColumn as any,
  477. renderPrependColumns: this._renderPrependColumns as any,
  478. prependColumnWidths,
  479. }}
  480. headerButtons={this.renderHeaderButtons}
  481. location={location}
  482. />
  483. );
  484. }
  485. }
  486. const PrependHeader = styled('span')`
  487. color: ${p => p.theme.subText};
  488. `;
  489. const StyledTooltip = styled(Tooltip)`
  490. display: initial;
  491. `;
  492. const StyledLink = styled(Link)`
  493. > div {
  494. display: inline;
  495. }
  496. `;
  497. const StyledIcon = styled(IconStack)`
  498. vertical-align: middle;
  499. `;
  500. export default withProjects(TableView);