cellAction.tsx 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596
  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. RELEASE = 'release',
  24. DRILLDOWN = 'drilldown',
  25. EDIT_THRESHOLD = 'edit_threshold',
  26. }
  27. export function updateQuery(
  28. results: MutableSearch,
  29. action: Actions,
  30. column: TableColumn<keyof TableDataRow>,
  31. value: React.ReactText | string[]
  32. ) {
  33. const key = column.name;
  34. if (column.type === 'duration' && typeof value === 'number') {
  35. // values are assumed to be in milliseconds
  36. value = getDuration(value / 1000, 2, true);
  37. }
  38. // De-duplicate array values
  39. if (Array.isArray(value)) {
  40. value = [...new Set(value)];
  41. if (value.length === 1) {
  42. value = value[0];
  43. }
  44. }
  45. switch (action) {
  46. case Actions.ADD:
  47. // If the value is null/undefined create a has !has condition.
  48. if (value === null || value === undefined) {
  49. // Adding a null value is the same as excluding truthy values.
  50. // Remove inclusion if it exists.
  51. results.removeFilterValue('has', key);
  52. results.addFilterValues('!has', [key]);
  53. } else {
  54. addToFilter(results, key, value);
  55. }
  56. break;
  57. case Actions.EXCLUDE:
  58. if (value === null || value === undefined) {
  59. // Excluding a null value is the same as including truthy values.
  60. // Remove exclusion if it exists.
  61. results.removeFilterValue('!has', key);
  62. results.addFilterValues('has', [key]);
  63. } else {
  64. excludeFromFilter(results, key, value);
  65. }
  66. break;
  67. case Actions.SHOW_GREATER_THAN: {
  68. // Remove query token if it already exists
  69. results.setFilterValues(key, [`>${value}`]);
  70. break;
  71. }
  72. case Actions.SHOW_LESS_THAN: {
  73. // Remove query token if it already exists
  74. results.setFilterValues(key, [`<${value}`]);
  75. break;
  76. }
  77. // these actions do not modify the query in any way,
  78. // instead they have side effects
  79. case Actions.RELEASE:
  80. case Actions.DRILLDOWN:
  81. break;
  82. default:
  83. throw new Error(`Unknown action type. ${action}`);
  84. }
  85. }
  86. export function addToFilter(
  87. oldFilter: MutableSearch,
  88. key: string,
  89. value: React.ReactText | string[]
  90. ) {
  91. // Remove exclusion if it exists.
  92. oldFilter.removeFilter(`!${key}`);
  93. if (Array.isArray(value)) {
  94. // For array values, add to existing filters
  95. const currentFilters = oldFilter.getFilterValues(key);
  96. value = [...new Set([...currentFilters, ...value])];
  97. } else {
  98. value = [String(value)];
  99. }
  100. oldFilter.setFilterValues(key, value);
  101. }
  102. export function excludeFromFilter(
  103. oldFilter: MutableSearch,
  104. key: string,
  105. value: React.ReactText | string[]
  106. ) {
  107. // Remove positive if it exists.
  108. oldFilter.removeFilter(key);
  109. // Negations should stack up.
  110. const negation = `!${key}`;
  111. value = Array.isArray(value) ? value : [String(value)];
  112. const currentNegations = oldFilter.getFilterValues(negation);
  113. oldFilter.removeFilter(negation);
  114. // We shouldn't escape any of the existing conditions since the
  115. // existing conditions have already been set an verified by the user
  116. oldFilter.addFilterValues(
  117. negation,
  118. currentNegations.filter(filterValue => !(value as string[]).includes(filterValue)),
  119. false
  120. );
  121. // Escapes the new condition if necessary
  122. oldFilter.addFilterValues(negation, value);
  123. }
  124. type CellActionsOpts = {
  125. column: TableColumn<keyof TableDataRow>;
  126. dataRow: TableDataRow;
  127. handleCellAction: (action: Actions, value: React.ReactText) => void;
  128. /**
  129. * allow list of actions to display on the context menu
  130. */
  131. allowActions?: Actions[];
  132. children?: React.ReactNode;
  133. };
  134. function makeCellActions({
  135. dataRow,
  136. column,
  137. handleCellAction,
  138. allowActions,
  139. }: CellActionsOpts) {
  140. // Do not render context menu buttons for the span op breakdown field.
  141. if (isRelativeSpanOperationBreakdownField(column.name)) {
  142. return null;
  143. }
  144. // Do not render context menu buttons for the equation fields until we can query on them
  145. if (isEquationAlias(column.name)) {
  146. return null;
  147. }
  148. let value = dataRow[column.name];
  149. // error.handled is a strange field where null = true.
  150. if (
  151. Array.isArray(value) &&
  152. value[0] === null &&
  153. column.column.kind === 'field' &&
  154. column.column.field === 'error.handled'
  155. ) {
  156. value = 1;
  157. }
  158. const actions: React.ReactNode[] = [];
  159. function addMenuItem(action: Actions, menuItem: React.ReactNode) {
  160. if ((Array.isArray(allowActions) && allowActions.includes(action)) || !allowActions) {
  161. actions.push(menuItem);
  162. }
  163. }
  164. if (
  165. !['duration', 'number', 'percentage'].includes(column.type) ||
  166. (value === null && column.column.kind === 'field')
  167. ) {
  168. addMenuItem(
  169. Actions.ADD,
  170. <ActionItem
  171. key="add-to-filter"
  172. data-test-id="add-to-filter"
  173. onClick={() => handleCellAction(Actions.ADD, value)}
  174. >
  175. {t('Add to filter')}
  176. </ActionItem>
  177. );
  178. if (column.type !== 'date') {
  179. addMenuItem(
  180. Actions.EXCLUDE,
  181. <ActionItem
  182. key="exclude-from-filter"
  183. data-test-id="exclude-from-filter"
  184. onClick={() => handleCellAction(Actions.EXCLUDE, value)}
  185. >
  186. {t('Exclude from filter')}
  187. </ActionItem>
  188. );
  189. }
  190. }
  191. if (
  192. ['date', 'duration', 'integer', 'number', 'percentage'].includes(column.type) &&
  193. value !== null
  194. ) {
  195. addMenuItem(
  196. Actions.SHOW_GREATER_THAN,
  197. <ActionItem
  198. key="show-values-greater-than"
  199. data-test-id="show-values-greater-than"
  200. onClick={() => handleCellAction(Actions.SHOW_GREATER_THAN, value)}
  201. >
  202. {t('Show values greater than')}
  203. </ActionItem>
  204. );
  205. addMenuItem(
  206. Actions.SHOW_LESS_THAN,
  207. <ActionItem
  208. key="show-values-less-than"
  209. data-test-id="show-values-less-than"
  210. onClick={() => handleCellAction(Actions.SHOW_LESS_THAN, value)}
  211. >
  212. {t('Show values less than')}
  213. </ActionItem>
  214. );
  215. }
  216. if (column.column.kind === 'field' && column.column.field === 'release' && value) {
  217. addMenuItem(
  218. Actions.RELEASE,
  219. <ActionItem
  220. key="release"
  221. data-test-id="release"
  222. onClick={() => handleCellAction(Actions.RELEASE, value)}
  223. >
  224. {t('Go to release')}
  225. </ActionItem>
  226. );
  227. }
  228. if (column.column.kind === 'function' && column.column.function[0] === 'count_unique') {
  229. addMenuItem(
  230. Actions.DRILLDOWN,
  231. <ActionItem
  232. key="drilldown"
  233. data-test-id="per-cell-drilldown"
  234. onClick={() => handleCellAction(Actions.DRILLDOWN, value)}
  235. >
  236. {t('View Stacks')}
  237. </ActionItem>
  238. );
  239. }
  240. if (
  241. column.column.kind === 'function' &&
  242. column.column.function[0] === 'user_misery' &&
  243. defined(dataRow.project_threshold_config)
  244. ) {
  245. addMenuItem(
  246. Actions.EDIT_THRESHOLD,
  247. <ActionItem
  248. key="edit_threshold"
  249. data-test-id="edit-threshold"
  250. onClick={() => handleCellAction(Actions.EDIT_THRESHOLD, value)}
  251. >
  252. {tct('Edit threshold ([threshold]ms)', {
  253. threshold: dataRow.project_threshold_config[1],
  254. })}
  255. </ActionItem>
  256. );
  257. }
  258. if (actions.length === 0) {
  259. return null;
  260. }
  261. return actions;
  262. }
  263. type Props = React.PropsWithoutRef<CellActionsOpts>;
  264. type State = {
  265. isHovering: boolean;
  266. isOpen: boolean;
  267. };
  268. class CellAction extends Component<Props, State> {
  269. constructor(props: Props) {
  270. super(props);
  271. let portal = document.getElementById('cell-action-portal');
  272. if (!portal) {
  273. portal = document.createElement('div');
  274. portal.setAttribute('id', 'cell-action-portal');
  275. document.body.appendChild(portal);
  276. }
  277. this.portalEl = portal;
  278. this.menuEl = null;
  279. }
  280. state: State = {
  281. isHovering: false,
  282. isOpen: false,
  283. };
  284. componentDidUpdate(_props: Props, prevState: State) {
  285. if (this.state.isOpen && prevState.isOpen === false) {
  286. document.addEventListener('click', this.handleClickOutside, true);
  287. }
  288. if (this.state.isOpen === false && prevState.isOpen) {
  289. document.removeEventListener('click', this.handleClickOutside, true);
  290. }
  291. }
  292. componentWillUnmount() {
  293. document.removeEventListener('click', this.handleClickOutside, true);
  294. }
  295. private portalEl: Element;
  296. private menuEl: Element | null;
  297. handleClickOutside = (event: MouseEvent) => {
  298. if (!this.menuEl) {
  299. return;
  300. }
  301. if (!(event.target instanceof Element)) {
  302. return;
  303. }
  304. if (this.menuEl.contains(event.target)) {
  305. return;
  306. }
  307. this.setState({isOpen: false, isHovering: false});
  308. };
  309. handleMouseEnter = () => {
  310. this.setState({isHovering: true});
  311. };
  312. handleMouseLeave = () => {
  313. this.setState(state => {
  314. // Don't hide the button if the menu is open.
  315. if (state.isOpen) {
  316. return state;
  317. }
  318. return {...state, isHovering: false};
  319. });
  320. };
  321. handleMenuToggle = (event: React.MouseEvent<HTMLButtonElement>) => {
  322. event.preventDefault();
  323. this.setState({isOpen: !this.state.isOpen});
  324. };
  325. renderMenu() {
  326. const {isOpen} = this.state;
  327. const actions = makeCellActions(this.props);
  328. if (actions === null) {
  329. // do not render the menu if there are no per cell actions
  330. return null;
  331. }
  332. const modifiers = [
  333. {
  334. name: 'hide',
  335. enabled: false,
  336. },
  337. {
  338. name: 'preventOverflow',
  339. enabled: true,
  340. options: {
  341. padding: 10,
  342. altAxis: true,
  343. },
  344. },
  345. {
  346. name: 'offset',
  347. options: {
  348. offset: [0, ARROW_SIZE / 2],
  349. },
  350. },
  351. {
  352. name: 'computeStyles',
  353. options: {
  354. // Using the `transform` attribute causes our borders to get blurry
  355. // in chrome. See [0]. This just causes it to use `top` / `left`
  356. // positions, which should be fine.
  357. //
  358. // [0]: https://stackoverflow.com/questions/29543142/css3-transformation-blurry-borders
  359. gpuAcceleration: false,
  360. },
  361. },
  362. ];
  363. const menu = !isOpen
  364. ? null
  365. : createPortal(
  366. <Popper placement="top" modifiers={modifiers}>
  367. {({ref: popperRef, style, placement, arrowProps}) => (
  368. <Menu
  369. ref={ref => {
  370. (popperRef as Function)(ref);
  371. this.menuEl = ref;
  372. }}
  373. style={style}
  374. >
  375. <MenuArrow
  376. ref={arrowProps.ref}
  377. data-placement={placement}
  378. style={arrowProps.style}
  379. />
  380. <MenuButtons onClick={event => event.stopPropagation()}>
  381. {actions}
  382. </MenuButtons>
  383. </Menu>
  384. )}
  385. </Popper>,
  386. this.portalEl
  387. );
  388. return (
  389. <MenuRoot>
  390. <Manager>
  391. <Reference>
  392. {({ref}) => (
  393. <MenuButton ref={ref} onClick={this.handleMenuToggle}>
  394. <IconEllipsis size="sm" data-test-id="cell-action" color="linkColor" />
  395. </MenuButton>
  396. )}
  397. </Reference>
  398. {menu}
  399. </Manager>
  400. </MenuRoot>
  401. );
  402. }
  403. render() {
  404. const {children} = this.props;
  405. const {isHovering} = this.state;
  406. return (
  407. <Container
  408. onMouseEnter={this.handleMouseEnter}
  409. onMouseLeave={this.handleMouseLeave}
  410. data-test-id="cell-action-container"
  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. `;