cellAction.tsx 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527
  1. import * as React from 'react';
  2. import ReactDOM from 'react-dom';
  3. import {Manager, Popper, Reference} from 'react-popper';
  4. import styled from '@emotion/styled';
  5. import color from 'color';
  6. import * as PopperJS from 'popper.js';
  7. import {IconEllipsis} from 'app/icons';
  8. import {t} from 'app/locale';
  9. import space from 'app/styles/space';
  10. import {TableDataRow} from 'app/utils/discover/discoverQuery';
  11. import {
  12. getAggregateAlias,
  13. isRelativeSpanOperationBreakdownField,
  14. } from 'app/utils/discover/fields';
  15. import {getDuration} from 'app/utils/formatters';
  16. import {QueryResults} from 'app/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. }
  27. export function updateQuery(
  28. results: QueryResults,
  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.removeTagValue('has', key);
  52. results.addTagValues('!has', [key]);
  53. } else {
  54. // Remove exclusion if it exists.
  55. results.removeTag(`!${key}`);
  56. if (Array.isArray(value)) {
  57. // For array values, add to existing filters
  58. const currentFilters = results.getTagValues(key);
  59. value = [...new Set([...currentFilters, ...value])];
  60. } else {
  61. value = [String(value)];
  62. }
  63. results.setTagValues(key, value);
  64. }
  65. break;
  66. case Actions.EXCLUDE:
  67. if (value === null || value === undefined) {
  68. // Excluding a null value is the same as including truthy values.
  69. // Remove exclusion if it exists.
  70. results.removeTagValue('!has', key);
  71. results.addTagValues('has', [key]);
  72. } else {
  73. // Remove positive if it exists.
  74. results.removeTag(key);
  75. // Negations should stack up.
  76. const negation = `!${key}`;
  77. value = Array.isArray(value) ? value : [String(value)];
  78. const currentNegations = results.getTagValues(negation);
  79. value = [...new Set([...currentNegations, ...value])];
  80. results.setTagValues(negation, value);
  81. }
  82. break;
  83. case Actions.SHOW_GREATER_THAN: {
  84. // Remove query token if it already exists
  85. results.setTagValues(key, [`>${value}`]);
  86. break;
  87. }
  88. case Actions.SHOW_LESS_THAN: {
  89. // Remove query token if it already exists
  90. results.setTagValues(key, [`<${value}`]);
  91. break;
  92. }
  93. // these actions do not modify the query in any way,
  94. // instead they have side effects
  95. case Actions.TRANSACTION:
  96. case Actions.RELEASE:
  97. case Actions.DRILLDOWN:
  98. break;
  99. default:
  100. throw new Error(`Unknown action type. ${action}`);
  101. }
  102. }
  103. type Props = {
  104. column: TableColumn<keyof TableDataRow>;
  105. dataRow: TableDataRow;
  106. children: React.ReactNode;
  107. handleCellAction: (action: Actions, value: React.ReactText) => void;
  108. // allow list of actions to display on the context menu
  109. allowActions?: Actions[];
  110. };
  111. type State = {
  112. isHovering: boolean;
  113. isOpen: boolean;
  114. };
  115. class CellAction extends React.Component<Props, State> {
  116. constructor(props: Props) {
  117. super(props);
  118. let portal = document.getElementById('cell-action-portal');
  119. if (!portal) {
  120. portal = document.createElement('div');
  121. portal.setAttribute('id', 'cell-action-portal');
  122. document.body.appendChild(portal);
  123. }
  124. this.portalEl = portal;
  125. this.menuEl = null;
  126. }
  127. state: State = {
  128. isHovering: false,
  129. isOpen: false,
  130. };
  131. componentDidUpdate(_props: Props, prevState: State) {
  132. if (this.state.isOpen && prevState.isOpen === false) {
  133. document.addEventListener('click', this.handleClickOutside, true);
  134. }
  135. if (this.state.isOpen === false && prevState.isOpen) {
  136. document.removeEventListener('click', this.handleClickOutside, true);
  137. }
  138. }
  139. componentWillUnmount() {
  140. document.removeEventListener('click', this.handleClickOutside, true);
  141. }
  142. private portalEl: Element;
  143. private menuEl: Element | null;
  144. handleClickOutside = (event: MouseEvent) => {
  145. if (!this.menuEl) {
  146. return;
  147. }
  148. if (!(event.target instanceof Element)) {
  149. return;
  150. }
  151. if (this.menuEl.contains(event.target)) {
  152. return;
  153. }
  154. this.setState({isOpen: false, isHovering: false});
  155. };
  156. handleMouseEnter = () => {
  157. this.setState({isHovering: true});
  158. };
  159. handleMouseLeave = () => {
  160. this.setState(state => {
  161. // Don't hide the button if the menu is open.
  162. if (state.isOpen) {
  163. return state;
  164. }
  165. return {...state, isHovering: false};
  166. });
  167. };
  168. handleMenuToggle = (event: React.MouseEvent<HTMLButtonElement>) => {
  169. event.preventDefault();
  170. this.setState({isOpen: !this.state.isOpen});
  171. };
  172. renderMenuButtons() {
  173. const {dataRow, column, handleCellAction, allowActions} = this.props;
  174. // Do not render context menu buttons for the span op breakdown field.
  175. if (isRelativeSpanOperationBreakdownField(column.name)) {
  176. return null;
  177. }
  178. const fieldAlias = getAggregateAlias(column.name);
  179. let value = dataRow[fieldAlias];
  180. // error.handled is a strange field where null = true.
  181. if (
  182. Array.isArray(value) &&
  183. value[0] === null &&
  184. column.column.kind === 'field' &&
  185. column.column.field === 'error.handled'
  186. ) {
  187. value = 1;
  188. }
  189. const actions: React.ReactNode[] = [];
  190. function addMenuItem(action: Actions, menuItem: React.ReactNode) {
  191. if (
  192. (Array.isArray(allowActions) && allowActions.includes(action)) ||
  193. !allowActions
  194. ) {
  195. actions.push(menuItem);
  196. }
  197. }
  198. if (
  199. !['duration', 'number', 'percentage'].includes(column.type) ||
  200. (value === null && column.column.kind === 'field')
  201. ) {
  202. addMenuItem(
  203. Actions.ADD,
  204. <ActionItem
  205. key="add-to-filter"
  206. data-test-id="add-to-filter"
  207. onClick={() => handleCellAction(Actions.ADD, value)}
  208. >
  209. {t('Add to filter')}
  210. </ActionItem>
  211. );
  212. if (column.type !== 'date') {
  213. addMenuItem(
  214. Actions.EXCLUDE,
  215. <ActionItem
  216. key="exclude-from-filter"
  217. data-test-id="exclude-from-filter"
  218. onClick={() => handleCellAction(Actions.EXCLUDE, value)}
  219. >
  220. {t('Exclude from filter')}
  221. </ActionItem>
  222. );
  223. }
  224. }
  225. if (
  226. ['date', 'duration', 'integer', 'number', 'percentage'].includes(column.type) &&
  227. value !== null
  228. ) {
  229. addMenuItem(
  230. Actions.SHOW_GREATER_THAN,
  231. <ActionItem
  232. key="show-values-greater-than"
  233. data-test-id="show-values-greater-than"
  234. onClick={() => handleCellAction(Actions.SHOW_GREATER_THAN, value)}
  235. >
  236. {t('Show values greater than')}
  237. </ActionItem>
  238. );
  239. addMenuItem(
  240. Actions.SHOW_LESS_THAN,
  241. <ActionItem
  242. key="show-values-less-than"
  243. data-test-id="show-values-less-than"
  244. onClick={() => handleCellAction(Actions.SHOW_LESS_THAN, value)}
  245. >
  246. {t('Show values less than')}
  247. </ActionItem>
  248. );
  249. }
  250. if (column.column.kind === 'field' && column.column.field === 'transaction') {
  251. addMenuItem(
  252. Actions.TRANSACTION,
  253. <ActionItem
  254. key="transaction-summary"
  255. data-test-id="transaction-summary"
  256. onClick={() => handleCellAction(Actions.TRANSACTION, value)}
  257. >
  258. {t('Go to summary')}
  259. </ActionItem>
  260. );
  261. }
  262. if (column.column.kind === 'field' && column.column.field === 'release' && value) {
  263. addMenuItem(
  264. Actions.RELEASE,
  265. <ActionItem
  266. key="release"
  267. data-test-id="release"
  268. onClick={() => handleCellAction(Actions.RELEASE, value)}
  269. >
  270. {t('Go to release')}
  271. </ActionItem>
  272. );
  273. }
  274. if (
  275. column.column.kind === 'function' &&
  276. column.column.function[0] === 'count_unique'
  277. ) {
  278. addMenuItem(
  279. Actions.DRILLDOWN,
  280. <ActionItem
  281. key="drilldown"
  282. data-test-id="per-cell-drilldown"
  283. onClick={() => handleCellAction(Actions.DRILLDOWN, value)}
  284. >
  285. {t('View Stacks')}
  286. </ActionItem>
  287. );
  288. }
  289. if (actions.length === 0) {
  290. return null;
  291. }
  292. return (
  293. <MenuButtons
  294. onClick={event => {
  295. // prevent clicks from propagating further
  296. event.stopPropagation();
  297. }}
  298. >
  299. {actions}
  300. </MenuButtons>
  301. );
  302. }
  303. renderMenu() {
  304. const {isOpen} = this.state;
  305. const menuButtons = this.renderMenuButtons();
  306. if (menuButtons === null) {
  307. // do not render the menu if there are no per cell actions
  308. return null;
  309. }
  310. const modifiers: PopperJS.Modifiers = {
  311. hide: {
  312. enabled: false,
  313. },
  314. preventOverflow: {
  315. padding: 10,
  316. enabled: true,
  317. boundariesElement: 'viewport',
  318. },
  319. };
  320. let menu: React.ReactPortal | null = null;
  321. if (isOpen) {
  322. menu = ReactDOM.createPortal(
  323. <Popper placement="top" modifiers={modifiers}>
  324. {({ref: popperRef, style, placement, arrowProps}) => (
  325. <Menu
  326. ref={ref => {
  327. (popperRef as Function)(ref);
  328. this.menuEl = ref;
  329. }}
  330. style={style}
  331. >
  332. <MenuArrow
  333. ref={arrowProps.ref}
  334. data-placement={placement}
  335. style={arrowProps.style}
  336. />
  337. {menuButtons}
  338. </Menu>
  339. )}
  340. </Popper>,
  341. this.portalEl
  342. );
  343. }
  344. return (
  345. <MenuRoot>
  346. <Manager>
  347. <Reference>
  348. {({ref}) => (
  349. <MenuButton ref={ref} onClick={this.handleMenuToggle}>
  350. <IconEllipsis size="sm" data-test-id="cell-action" color="blue300" />
  351. </MenuButton>
  352. )}
  353. </Reference>
  354. {menu}
  355. </Manager>
  356. </MenuRoot>
  357. );
  358. }
  359. render() {
  360. const {children} = this.props;
  361. const {isHovering} = this.state;
  362. return (
  363. <Container
  364. onMouseEnter={this.handleMouseEnter}
  365. onMouseLeave={this.handleMouseLeave}
  366. >
  367. {children}
  368. {isHovering && this.renderMenu()}
  369. </Container>
  370. );
  371. }
  372. }
  373. export default CellAction;
  374. const Container = styled('div')`
  375. position: relative;
  376. width: 100%;
  377. height: 100%;
  378. `;
  379. const MenuRoot = styled('div')`
  380. position: absolute;
  381. top: 0;
  382. right: 0;
  383. `;
  384. const Menu = styled('div')`
  385. margin: ${space(1)} 0;
  386. z-index: ${p => p.theme.zIndex.tooltip};
  387. `;
  388. const MenuButtons = styled('div')`
  389. background: ${p => p.theme.background};
  390. border: 1px solid ${p => p.theme.border};
  391. border-radius: ${p => p.theme.borderRadius};
  392. box-shadow: ${p => p.theme.dropShadowHeavy};
  393. overflow: hidden;
  394. `;
  395. const MenuArrow = styled('span')`
  396. position: absolute;
  397. width: 18px;
  398. height: 9px;
  399. /* left and top set by popper */
  400. &[data-placement*='bottom'] {
  401. margin-top: -9px;
  402. &::before {
  403. border-width: 0 9px 9px 9px;
  404. border-color: transparent transparent ${p => p.theme.border} transparent;
  405. }
  406. &::after {
  407. top: 1px;
  408. left: 1px;
  409. border-width: 0 8px 8px 8px;
  410. border-color: transparent transparent ${p => p.theme.background} transparent;
  411. }
  412. }
  413. &[data-placement*='top'] {
  414. margin-bottom: -8px;
  415. bottom: 0;
  416. &::before {
  417. border-width: 9px 9px 0 9px;
  418. border-color: ${p => p.theme.border} transparent transparent transparent;
  419. }
  420. &::after {
  421. bottom: 1px;
  422. left: 1px;
  423. border-width: 8px 8px 0 8px;
  424. border-color: ${p => p.theme.background} transparent transparent transparent;
  425. }
  426. }
  427. &::before,
  428. &::after {
  429. width: 0;
  430. height: 0;
  431. content: '';
  432. display: block;
  433. position: absolute;
  434. border-style: solid;
  435. }
  436. `;
  437. const ActionItem = styled('button')`
  438. display: block;
  439. width: 100%;
  440. padding: ${space(1)} ${space(2)};
  441. background: transparent;
  442. outline: none;
  443. border: 0;
  444. border-bottom: 1px solid ${p => p.theme.innerBorder};
  445. font-size: ${p => p.theme.fontSizeMedium};
  446. text-align: left;
  447. line-height: 1.2;
  448. &:hover {
  449. background: ${p => p.theme.backgroundSecondary};
  450. }
  451. &:last-child {
  452. border-bottom: 0;
  453. }
  454. `;
  455. const MenuButton = styled('button')`
  456. display: flex;
  457. width: 24px;
  458. height: 24px;
  459. padding: 0;
  460. justify-content: center;
  461. align-items: center;
  462. background: ${p => color(p.theme.background).alpha(0.85).string()};
  463. border-radius: ${p => p.theme.borderRadius};
  464. border: 1px solid ${p => p.theme.border};
  465. cursor: pointer;
  466. outline: none;
  467. `;