tableView.tsx 16 KB

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