tableView.tsx 17 KB

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