cellAction.tsx 13 KB

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