cellAction.tsx 15 KB

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