tableView.tsx 16 KB

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