tableView.tsx 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552
  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. const unit = tableData.meta.units?.[columnKey];
  227. let cell = fieldRenderer(dataRow, {organization, location, unit});
  228. if (columnKey === 'id') {
  229. const eventSlug = generateEventSlug(dataRow);
  230. const target = eventDetailsRouteWithEventView({
  231. orgSlug: organization.slug,
  232. eventSlug,
  233. eventView,
  234. });
  235. cell = (
  236. <Tooltip title={t('View Event')}>
  237. <StyledLink data-test-id="view-event" to={target}>
  238. {cell}
  239. </StyledLink>
  240. </Tooltip>
  241. );
  242. } else if (columnKey === 'trace') {
  243. const dateSelection = eventView.normalizeDateSelection(location);
  244. if (dataRow.trace) {
  245. const target = getTraceDetailsUrl(
  246. organization,
  247. String(dataRow.trace),
  248. dateSelection,
  249. {}
  250. );
  251. cell = (
  252. <Tooltip title={t('View Trace')}>
  253. <StyledLink data-test-id="view-trace" to={target}>
  254. {cell}
  255. </StyledLink>
  256. </Tooltip>
  257. );
  258. }
  259. }
  260. const fieldName = columnKey;
  261. const value = dataRow[fieldName];
  262. if (tableData.meta[fieldName] === 'integer' && defined(value) && value > 999) {
  263. return (
  264. <Tooltip
  265. title={value.toLocaleString()}
  266. containerDisplayMode="block"
  267. position="right"
  268. >
  269. <CellAction
  270. column={column}
  271. dataRow={dataRow}
  272. handleCellAction={this.handleCellAction(dataRow, column)}
  273. >
  274. {cell}
  275. </CellAction>
  276. </Tooltip>
  277. );
  278. }
  279. return (
  280. <Fragment>
  281. {isFirstPage && isTopEvents && rowIndex < topEvents && columnIndex === 0 ? (
  282. // Add one if we need to include Other in the series
  283. <TopResultsIndicator count={count} index={rowIndex} />
  284. ) : null}
  285. <CellAction
  286. column={column}
  287. dataRow={dataRow}
  288. handleCellAction={this.handleCellAction(dataRow, column)}
  289. >
  290. {cell}
  291. </CellAction>
  292. </Fragment>
  293. );
  294. };
  295. handleEditColumns = () => {
  296. const {
  297. organization,
  298. eventView,
  299. measurementKeys,
  300. spanOperationBreakdownKeys,
  301. customMeasurements,
  302. } = this.props;
  303. const hasBreakdownFeature = organization.features.includes(
  304. 'performance-ops-breakdown'
  305. );
  306. openModal(
  307. modalProps => (
  308. <ColumnEditModal
  309. {...modalProps}
  310. organization={organization}
  311. measurementKeys={measurementKeys}
  312. spanOperationBreakdownKeys={
  313. hasBreakdownFeature ? spanOperationBreakdownKeys : undefined
  314. }
  315. columns={eventView.getColumns().map(col => col.column)}
  316. onApply={this.handleUpdateColumns}
  317. customMeasurements={customMeasurements}
  318. />
  319. ),
  320. {modalCss, backdrop: 'static'}
  321. );
  322. };
  323. handleCellAction = (dataRow: TableDataRow, column: TableColumn<keyof TableDataRow>) => {
  324. return (action: Actions, value: React.ReactText) => {
  325. const {eventView, organization, projects, location} = this.props;
  326. const query = new MutableSearch(eventView.query);
  327. let nextView = eventView.clone();
  328. trackAnalyticsEvent({
  329. eventKey: 'discover_v2.results.cellaction',
  330. eventName: 'Discoverv2: Cell Action Clicked',
  331. organization_id: parseInt(organization.id, 10),
  332. action,
  333. });
  334. switch (action) {
  335. case Actions.TRANSACTION: {
  336. const maybeProject = projects.find(
  337. project =>
  338. project.slug &&
  339. [dataRow['project.name'], dataRow.project].includes(project.slug)
  340. );
  341. const projectID = maybeProject ? [maybeProject.id] : undefined;
  342. const next = transactionSummaryRouteWithQuery({
  343. orgSlug: organization.slug,
  344. transaction: String(value),
  345. projectID,
  346. query: nextView.getPageFiltersQuery(),
  347. });
  348. browserHistory.push(next);
  349. return;
  350. }
  351. case Actions.RELEASE: {
  352. const maybeProject = projects.find(project => {
  353. return project.slug === dataRow.project;
  354. });
  355. browserHistory.push({
  356. pathname: `/organizations/${organization.slug}/releases/${encodeURIComponent(
  357. value
  358. )}/`,
  359. query: {
  360. ...nextView.getPageFiltersQuery(),
  361. project: maybeProject ? maybeProject.id : undefined,
  362. },
  363. });
  364. return;
  365. }
  366. case Actions.DRILLDOWN: {
  367. // count_unique(column) drilldown
  368. trackAnalyticsEvent({
  369. eventKey: 'discover_v2.results.drilldown',
  370. eventName: 'Discoverv2: Click aggregate drilldown',
  371. organization_id: parseInt(organization.id, 10),
  372. });
  373. // Drilldown into each distinct value and get a count() for each value.
  374. nextView = getExpandedResults(nextView, {}, dataRow).withNewColumn({
  375. kind: 'function',
  376. function: ['count', '', undefined, undefined],
  377. });
  378. browserHistory.push(nextView.getResultsViewUrlTarget(organization.slug));
  379. return;
  380. }
  381. default: {
  382. updateQuery(query, action, column, value);
  383. }
  384. }
  385. nextView.query = query.formatString();
  386. const target = nextView.getResultsViewUrlTarget(organization.slug);
  387. // Get yAxis from location
  388. target.query.yAxis = decodeList(location.query.yAxis);
  389. browserHistory.push(target);
  390. };
  391. };
  392. handleUpdateColumns = (columns: Column[]): void => {
  393. const {organization, eventView, location} = this.props;
  394. // metrics
  395. trackAnalyticsEvent({
  396. eventKey: 'discover_v2.update_columns',
  397. eventName: 'Discoverv2: Update columns',
  398. organization_id: parseInt(organization.id, 10),
  399. });
  400. const nextView = eventView.withColumns(columns);
  401. const resultsViewUrlTarget = nextView.getResultsViewUrlTarget(organization.slug);
  402. // Need to pull yAxis from location since eventView only stores 1 yAxis field at time
  403. const previousYAxis = decodeList(location.query.yAxis);
  404. resultsViewUrlTarget.query.yAxis = previousYAxis.filter(yAxis =>
  405. nextView.getYAxisOptions().find(({value}) => value === yAxis)
  406. );
  407. browserHistory.push(resultsViewUrlTarget);
  408. };
  409. renderHeaderButtons = () => {
  410. const {
  411. organization,
  412. title,
  413. eventView,
  414. isLoading,
  415. error,
  416. tableData,
  417. location,
  418. onChangeShowTags,
  419. showTags,
  420. } = this.props;
  421. return (
  422. <TableActions
  423. title={title}
  424. isLoading={isLoading}
  425. error={error}
  426. organization={organization}
  427. eventView={eventView}
  428. onEdit={this.handleEditColumns}
  429. tableData={tableData}
  430. location={location}
  431. onChangeShowTags={onChangeShowTags}
  432. showTags={showTags}
  433. />
  434. );
  435. };
  436. render() {
  437. const {isLoading, error, location, tableData, eventView, organization} = this.props;
  438. const columnOrder = eventView.getColumns(
  439. organization.features.includes('discover-frontend-use-events-endpoint')
  440. );
  441. const columnSortBy = eventView.getSorts();
  442. const prependColumnWidths = eventView.hasAggregateField()
  443. ? ['40px']
  444. : eventView.hasIdField()
  445. ? []
  446. : [`minmax(${COL_WIDTH_MINIMUM}px, max-content)`];
  447. return (
  448. <GridEditable
  449. isLoading={isLoading}
  450. error={error}
  451. data={tableData ? tableData.data : []}
  452. columnOrder={columnOrder}
  453. columnSortBy={columnSortBy}
  454. title={t('Results')}
  455. grid={{
  456. renderHeadCell: this._renderGridHeaderCell as any,
  457. renderBodyCell: this._renderGridBodyCell as any,
  458. onResizeColumn: this._resizeColumn as any,
  459. renderPrependColumns: this._renderPrependColumns as any,
  460. prependColumnWidths,
  461. }}
  462. headerButtons={this.renderHeaderButtons}
  463. location={location}
  464. />
  465. );
  466. }
  467. }
  468. const PrependHeader = styled('span')`
  469. color: ${p => p.theme.subText};
  470. `;
  471. const StyledTooltip = styled(Tooltip)`
  472. display: initial;
  473. `;
  474. const StyledLink = styled(Link)`
  475. > div {
  476. display: inline;
  477. }
  478. `;
  479. const StyledIcon = styled(IconStack)`
  480. vertical-align: middle;
  481. `;
  482. export default withProjects(TableView);