cellAction.tsx 15 KB

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