tableView.tsx 16 KB

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