cellAction.tsx 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610
  1. import React, {Component} from 'react';
  2. import {createPortal} from 'react-dom';
  3. import {Manager, Popper, Reference} from 'react-popper';
  4. import styled from '@emotion/styled';
  5. import color from 'color';
  6. import {IconEllipsis} from 'sentry/icons';
  7. import {t, tct} from 'sentry/locale';
  8. import {space} from 'sentry/styles/space';
  9. import {defined} from 'sentry/utils';
  10. import {TableDataRow} from 'sentry/utils/discover/discoverQuery';
  11. import {
  12. isEquationAlias,
  13. isRelativeSpanOperationBreakdownField,
  14. } from 'sentry/utils/discover/fields';
  15. import {getDuration} from 'sentry/utils/formatters';
  16. import {MutableSearch} from 'sentry/utils/tokenizeSearch';
  17. import {TableColumn} from './types';
  18. export enum Actions {
  19. ADD = 'add',
  20. EXCLUDE = 'exclude',
  21. SHOW_GREATER_THAN = 'show_greater_than',
  22. SHOW_LESS_THAN = 'show_less_than',
  23. TRANSACTION = 'transaction',
  24. RELEASE = 'release',
  25. DRILLDOWN = 'drilldown',
  26. EDIT_THRESHOLD = 'edit_threshold',
  27. }
  28. export function updateQuery(
  29. results: MutableSearch,
  30. action: Actions,
  31. column: TableColumn<keyof TableDataRow>,
  32. value: React.ReactText | string[]
  33. ) {
  34. const key = column.name;
  35. if (column.type === 'duration' && typeof value === 'number') {
  36. // values are assumed to be in milliseconds
  37. value = getDuration(value / 1000, 2, true);
  38. }
  39. // De-duplicate array values
  40. if (Array.isArray(value)) {
  41. value = [...new Set(value)];
  42. if (value.length === 1) {
  43. value = value[0];
  44. }
  45. }
  46. switch (action) {
  47. case Actions.ADD:
  48. // If the value is null/undefined create a has !has condition.
  49. if (value === null || value === undefined) {
  50. // Adding a null value is the same as excluding truthy values.
  51. // Remove inclusion if it exists.
  52. results.removeFilterValue('has', key);
  53. results.addFilterValues('!has', [key]);
  54. } else {
  55. addToFilter(results, key, value);
  56. }
  57. break;
  58. case Actions.EXCLUDE:
  59. if (value === null || value === undefined) {
  60. // Excluding a null value is the same as including truthy values.
  61. // Remove exclusion if it exists.
  62. results.removeFilterValue('!has', key);
  63. results.addFilterValues('has', [key]);
  64. } else {
  65. excludeFromFilter(results, key, value);
  66. }
  67. break;
  68. case Actions.SHOW_GREATER_THAN: {
  69. // Remove query token if it already exists
  70. results.setFilterValues(key, [`>${value}`]);
  71. break;
  72. }
  73. case Actions.SHOW_LESS_THAN: {
  74. // Remove query token if it already exists
  75. results.setFilterValues(key, [`<${value}`]);
  76. break;
  77. }
  78. // these actions do not modify the query in any way,
  79. // instead they have side effects
  80. case Actions.TRANSACTION:
  81. case Actions.RELEASE:
  82. case Actions.DRILLDOWN:
  83. break;
  84. default:
  85. throw new Error(`Unknown action type. ${action}`);
  86. }
  87. }
  88. export function addToFilter(
  89. oldFilter: MutableSearch,
  90. key: string,
  91. value: React.ReactText | string[]
  92. ) {
  93. // Remove exclusion if it exists.
  94. oldFilter.removeFilter(`!${key}`);
  95. if (Array.isArray(value)) {
  96. // For array values, add to existing filters
  97. const currentFilters = oldFilter.getFilterValues(key);
  98. value = [...new Set([...currentFilters, ...value])];
  99. } else {
  100. value = [String(value)];
  101. }
  102. oldFilter.setFilterValues(key, value);
  103. }
  104. export function excludeFromFilter(
  105. oldFilter: MutableSearch,
  106. key: string,
  107. value: React.ReactText | string[]
  108. ) {
  109. // Remove positive if it exists.
  110. oldFilter.removeFilter(key);
  111. // Negations should stack up.
  112. const negation = `!${key}`;
  113. value = Array.isArray(value) ? value : [String(value)];
  114. const currentNegations = oldFilter.getFilterValues(negation);
  115. oldFilter.removeFilter(negation);
  116. // We shouldn't escape any of the existing conditions since the
  117. // existing conditions have already been set an verified by the user
  118. oldFilter.addFilterValues(
  119. negation,
  120. currentNegations.filter(filterValue => !(value as string[]).includes(filterValue)),
  121. false
  122. );
  123. // Escapes the new condition if necessary
  124. oldFilter.addFilterValues(negation, value);
  125. }
  126. type CellActionsOpts = {
  127. column: TableColumn<keyof TableDataRow>;
  128. dataRow: TableDataRow;
  129. handleCellAction: (action: Actions, value: React.ReactText) => void;
  130. /**
  131. * allow list of actions to display on the context menu
  132. */
  133. allowActions?: Actions[];
  134. };
  135. function makeCellActions({
  136. dataRow,
  137. column,
  138. handleCellAction,
  139. allowActions,
  140. }: CellActionsOpts) {
  141. // Do not render context menu buttons for the span op breakdown field.
  142. if (isRelativeSpanOperationBreakdownField(column.name)) {
  143. return null;
  144. }
  145. // Do not render context menu buttons for the equation fields until we can query on them
  146. if (isEquationAlias(column.name)) {
  147. return null;
  148. }
  149. let value = dataRow[column.name];
  150. // error.handled is a strange field where null = true.
  151. if (
  152. Array.isArray(value) &&
  153. value[0] === null &&
  154. column.column.kind === 'field' &&
  155. column.column.field === 'error.handled'
  156. ) {
  157. value = 1;
  158. }
  159. const actions: React.ReactNode[] = [];
  160. function addMenuItem(action: Actions, menuItem: React.ReactNode) {
  161. if ((Array.isArray(allowActions) && allowActions.includes(action)) || !allowActions) {
  162. actions.push(menuItem);
  163. }
  164. }
  165. if (
  166. !['duration', 'number', 'percentage'].includes(column.type) ||
  167. (value === null && column.column.kind === 'field')
  168. ) {
  169. addMenuItem(
  170. Actions.ADD,
  171. <ActionItem
  172. key="add-to-filter"
  173. data-test-id="add-to-filter"
  174. onClick={() => handleCellAction(Actions.ADD, value)}
  175. >
  176. {t('Add to filter')}
  177. </ActionItem>
  178. );
  179. if (column.type !== 'date') {
  180. addMenuItem(
  181. Actions.EXCLUDE,
  182. <ActionItem
  183. key="exclude-from-filter"
  184. data-test-id="exclude-from-filter"
  185. onClick={() => handleCellAction(Actions.EXCLUDE, value)}
  186. >
  187. {t('Exclude from filter')}
  188. </ActionItem>
  189. );
  190. }
  191. }
  192. if (
  193. ['date', 'duration', 'integer', 'number', 'percentage'].includes(column.type) &&
  194. value !== null
  195. ) {
  196. addMenuItem(
  197. Actions.SHOW_GREATER_THAN,
  198. <ActionItem
  199. key="show-values-greater-than"
  200. data-test-id="show-values-greater-than"
  201. onClick={() => handleCellAction(Actions.SHOW_GREATER_THAN, value)}
  202. >
  203. {t('Show values greater than')}
  204. </ActionItem>
  205. );
  206. addMenuItem(
  207. Actions.SHOW_LESS_THAN,
  208. <ActionItem
  209. key="show-values-less-than"
  210. data-test-id="show-values-less-than"
  211. onClick={() => handleCellAction(Actions.SHOW_LESS_THAN, value)}
  212. >
  213. {t('Show values less than')}
  214. </ActionItem>
  215. );
  216. }
  217. if (column.column.kind === 'field' && column.column.field === 'transaction') {
  218. addMenuItem(
  219. Actions.TRANSACTION,
  220. <ActionItem
  221. key="transaction-summary"
  222. data-test-id="transaction-summary"
  223. onClick={() => handleCellAction(Actions.TRANSACTION, value)}
  224. >
  225. {t('Go to summary')}
  226. </ActionItem>
  227. );
  228. }
  229. if (column.column.kind === 'field' && column.column.field === 'release' && value) {
  230. addMenuItem(
  231. Actions.RELEASE,
  232. <ActionItem
  233. key="release"
  234. data-test-id="release"
  235. onClick={() => handleCellAction(Actions.RELEASE, value)}
  236. >
  237. {t('Go to release')}
  238. </ActionItem>
  239. );
  240. }
  241. if (column.column.kind === 'function' && column.column.function[0] === 'count_unique') {
  242. addMenuItem(
  243. Actions.DRILLDOWN,
  244. <ActionItem
  245. key="drilldown"
  246. data-test-id="per-cell-drilldown"
  247. onClick={() => handleCellAction(Actions.DRILLDOWN, value)}
  248. >
  249. {t('View Stacks')}
  250. </ActionItem>
  251. );
  252. }
  253. if (
  254. column.column.kind === 'function' &&
  255. column.column.function[0] === 'user_misery' &&
  256. defined(dataRow.project_threshold_config)
  257. ) {
  258. addMenuItem(
  259. Actions.EDIT_THRESHOLD,
  260. <ActionItem
  261. key="edit_threshold"
  262. data-test-id="edit-threshold"
  263. onClick={() => handleCellAction(Actions.EDIT_THRESHOLD, value)}
  264. >
  265. {tct('Edit threshold ([threshold]ms)', {
  266. threshold: dataRow.project_threshold_config[1],
  267. })}
  268. </ActionItem>
  269. );
  270. }
  271. if (actions.length === 0) {
  272. return null;
  273. }
  274. return actions;
  275. }
  276. type Props = React.PropsWithoutRef<CellActionsOpts>;
  277. type State = {
  278. isHovering: boolean;
  279. isOpen: boolean;
  280. };
  281. class CellAction extends Component<Props, State> {
  282. constructor(props: Props) {
  283. super(props);
  284. let portal = document.getElementById('cell-action-portal');
  285. if (!portal) {
  286. portal = document.createElement('div');
  287. portal.setAttribute('id', 'cell-action-portal');
  288. document.body.appendChild(portal);
  289. }
  290. this.portalEl = portal;
  291. this.menuEl = null;
  292. }
  293. state: State = {
  294. isHovering: false,
  295. isOpen: false,
  296. };
  297. componentDidUpdate(_props: Props, prevState: State) {
  298. if (this.state.isOpen && prevState.isOpen === false) {
  299. document.addEventListener('click', this.handleClickOutside, true);
  300. }
  301. if (this.state.isOpen === false && prevState.isOpen) {
  302. document.removeEventListener('click', this.handleClickOutside, true);
  303. }
  304. }
  305. componentWillUnmount() {
  306. document.removeEventListener('click', this.handleClickOutside, true);
  307. }
  308. private portalEl: Element;
  309. private menuEl: Element | null;
  310. handleClickOutside = (event: MouseEvent) => {
  311. if (!this.menuEl) {
  312. return;
  313. }
  314. if (!(event.target instanceof Element)) {
  315. return;
  316. }
  317. if (this.menuEl.contains(event.target)) {
  318. return;
  319. }
  320. this.setState({isOpen: false, isHovering: false});
  321. };
  322. handleMouseEnter = () => {
  323. this.setState({isHovering: true});
  324. };
  325. handleMouseLeave = () => {
  326. this.setState(state => {
  327. // Don't hide the button if the menu is open.
  328. if (state.isOpen) {
  329. return state;
  330. }
  331. return {...state, isHovering: false};
  332. });
  333. };
  334. handleMenuToggle = (event: React.MouseEvent<HTMLButtonElement>) => {
  335. event.preventDefault();
  336. this.setState({isOpen: !this.state.isOpen});
  337. };
  338. renderMenu() {
  339. const {isOpen} = this.state;
  340. const actions = makeCellActions(this.props);
  341. if (actions === null) {
  342. // do not render the menu if there are no per cell actions
  343. return null;
  344. }
  345. const modifiers = [
  346. {
  347. name: 'hide',
  348. enabled: false,
  349. },
  350. {
  351. name: 'preventOverflow',
  352. enabled: true,
  353. options: {
  354. padding: 10,
  355. altAxis: true,
  356. },
  357. },
  358. {
  359. name: 'offset',
  360. options: {
  361. offset: [0, ARROW_SIZE / 2],
  362. },
  363. },
  364. {
  365. name: 'computeStyles',
  366. options: {
  367. // Using the `transform` attribute causes our borders to get blurry
  368. // in chrome. See [0]. This just causes it to use `top` / `left`
  369. // positions, which should be fine.
  370. //
  371. // [0]: https://stackoverflow.com/questions/29543142/css3-transformation-blurry-borders
  372. gpuAcceleration: false,
  373. },
  374. },
  375. ];
  376. const menu = !isOpen
  377. ? null
  378. : createPortal(
  379. <Popper placement="top" modifiers={modifiers}>
  380. {({ref: popperRef, style, placement, arrowProps}) => (
  381. <Menu
  382. ref={ref => {
  383. (popperRef as Function)(ref);
  384. this.menuEl = ref;
  385. }}
  386. style={style}
  387. >
  388. <MenuArrow
  389. ref={arrowProps.ref}
  390. data-placement={placement}
  391. style={arrowProps.style}
  392. />
  393. <MenuButtons onClick={event => event.stopPropagation()}>
  394. {actions}
  395. </MenuButtons>
  396. </Menu>
  397. )}
  398. </Popper>,
  399. this.portalEl
  400. );
  401. return (
  402. <MenuRoot>
  403. <Manager>
  404. <Reference>
  405. {({ref}) => (
  406. <MenuButton ref={ref} onClick={this.handleMenuToggle}>
  407. <IconEllipsis size="sm" data-test-id="cell-action" color="linkColor" />
  408. </MenuButton>
  409. )}
  410. </Reference>
  411. {menu}
  412. </Manager>
  413. </MenuRoot>
  414. );
  415. }
  416. render() {
  417. const {children} = this.props;
  418. const {isHovering} = this.state;
  419. return (
  420. <Container
  421. onMouseEnter={this.handleMouseEnter}
  422. onMouseLeave={this.handleMouseLeave}
  423. data-test-id="cell-action-container"
  424. >
  425. {children}
  426. {isHovering && this.renderMenu()}
  427. </Container>
  428. );
  429. }
  430. }
  431. export default CellAction;
  432. const Container = styled('div')`
  433. position: relative;
  434. width: 100%;
  435. height: 100%;
  436. display: flex;
  437. flex-direction: column;
  438. justify-content: center;
  439. `;
  440. const MenuRoot = styled('div')`
  441. position: absolute;
  442. top: 0;
  443. right: 0;
  444. `;
  445. const Menu = styled('div')`
  446. z-index: ${p => p.theme.zIndex.tooltip};
  447. `;
  448. const MenuButtons = styled('div')`
  449. background: ${p => p.theme.background};
  450. border: 1px solid ${p => p.theme.border};
  451. border-radius: ${p => p.theme.borderRadius};
  452. box-shadow: ${p => p.theme.dropShadowHeavy};
  453. overflow: hidden;
  454. `;
  455. const ARROW_SIZE = 12;
  456. const MenuArrow = styled('span')`
  457. pointer-events: none;
  458. position: absolute;
  459. width: ${ARROW_SIZE}px;
  460. height: ${ARROW_SIZE}px;
  461. &::before,
  462. &::after {
  463. content: '';
  464. display: block;
  465. position: absolute;
  466. height: ${ARROW_SIZE}px;
  467. width: ${ARROW_SIZE}px;
  468. border: solid 6px transparent;
  469. }
  470. &[data-placement|='bottom'] {
  471. top: -${ARROW_SIZE}px;
  472. &::before {
  473. bottom: 1px;
  474. border-bottom-color: ${p => p.theme.translucentBorder};
  475. }
  476. &::after {
  477. border-bottom-color: ${p => p.theme.backgroundElevated};
  478. }
  479. }
  480. &[data-placement|='top'] {
  481. bottom: -${ARROW_SIZE}px;
  482. &::before {
  483. top: 1px;
  484. border-top-color: ${p => p.theme.translucentBorder};
  485. }
  486. &::after {
  487. border-top-color: ${p => p.theme.backgroundElevated};
  488. }
  489. }
  490. &[data-placement|='right'] {
  491. left: -${ARROW_SIZE}px;
  492. &::before {
  493. right: 1px;
  494. border-right-color: ${p => p.theme.translucentBorder};
  495. }
  496. &::after {
  497. border-right-color: ${p => p.theme.backgroundElevated};
  498. }
  499. }
  500. &[data-placement|='left'] {
  501. right: -${ARROW_SIZE}px;
  502. &::before {
  503. left: 1px;
  504. border-left-color: ${p => p.theme.translucentBorder};
  505. }
  506. &::after {
  507. border-left-color: ${p => p.theme.backgroundElevated};
  508. }
  509. }
  510. `;
  511. const ActionItem = styled('button')`
  512. display: block;
  513. width: 100%;
  514. padding: ${space(1)} ${space(2)};
  515. background: transparent;
  516. outline: none;
  517. border: 0;
  518. border-bottom: 1px solid ${p => p.theme.innerBorder};
  519. font-size: ${p => p.theme.fontSizeMedium};
  520. text-align: left;
  521. line-height: 1.2;
  522. &:hover {
  523. background: ${p => p.theme.backgroundSecondary};
  524. }
  525. &:last-child {
  526. border-bottom: 0;
  527. }
  528. `;
  529. const MenuButton = styled('button')`
  530. display: flex;
  531. width: 24px;
  532. height: 24px;
  533. padding: 0;
  534. justify-content: center;
  535. align-items: center;
  536. background: ${p => color(p.theme.background).alpha(0.85).string()};
  537. border-radius: ${p => p.theme.borderRadius};
  538. border: 1px solid ${p => p.theme.border};
  539. cursor: pointer;
  540. outline: none;
  541. `;