tableView.tsx 16 KB

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