arithmeticInput.tsx 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479
  1. import {createRef, Fragment, PureComponent} from 'react';
  2. import styled from '@emotion/styled';
  3. import isEqual from 'lodash/isEqual';
  4. import Input, {InputProps} from 'sentry/components/input';
  5. import {t} from 'sentry/locale';
  6. import space from 'sentry/styles/space';
  7. import {
  8. Column,
  9. generateFieldAsString,
  10. isLegalEquationColumn,
  11. } from 'sentry/utils/discover/fields';
  12. const NONE_SELECTED = -1;
  13. type DropdownOption = {
  14. active: boolean;
  15. kind: 'field' | 'operator';
  16. value: string;
  17. };
  18. type DropdownOptionGroup = {
  19. options: DropdownOption[];
  20. title: string;
  21. };
  22. type DefaultProps = {
  23. options: Column[];
  24. };
  25. type Props = DefaultProps &
  26. InputProps & {
  27. onUpdate: (value: string) => void;
  28. value: string;
  29. hideFieldOptions?: boolean;
  30. };
  31. type State = {
  32. activeSelection: number;
  33. dropdownOptionGroups: DropdownOptionGroup[];
  34. dropdownVisible: boolean;
  35. partialTerm: string | null;
  36. query: string;
  37. rawOptions: Column[];
  38. };
  39. export default class ArithmeticInput extends PureComponent<Props, State> {
  40. static defaultProps: DefaultProps = {
  41. options: [],
  42. };
  43. static getDerivedStateFromProps(props: Readonly<Props>, state: State): State {
  44. const changed = !isEqual(state.rawOptions, props.options);
  45. if (changed) {
  46. return {
  47. ...state,
  48. rawOptions: props.options,
  49. dropdownOptionGroups: makeOptions(
  50. props.options,
  51. state.partialTerm,
  52. props.hideFieldOptions
  53. ),
  54. activeSelection: NONE_SELECTED,
  55. };
  56. }
  57. return {...state};
  58. }
  59. state: State = {
  60. query: this.props.value,
  61. partialTerm: null,
  62. rawOptions: this.props.options,
  63. dropdownVisible: false,
  64. dropdownOptionGroups: makeOptions(
  65. this.props.options,
  66. null,
  67. this.props.hideFieldOptions
  68. ),
  69. activeSelection: NONE_SELECTED,
  70. };
  71. input = createRef<HTMLInputElement>();
  72. blur = () => {
  73. this.input.current?.blur();
  74. };
  75. focus = (position: number) => {
  76. this.input.current?.focus();
  77. this.input.current?.setSelectionRange(position, position);
  78. };
  79. getCursorPosition(): number {
  80. return this.input.current?.selectionStart ?? -1;
  81. }
  82. splitQuery() {
  83. const {query} = this.state;
  84. const currentPosition = this.getCursorPosition();
  85. // The current term is delimited by whitespaces. So if no spaces are found,
  86. // the entire string is taken to be 1 term.
  87. //
  88. // TODO: add support for when there are no spaces
  89. const matches = [...query.substring(0, currentPosition).matchAll(/\s|^/g)];
  90. const match = matches[matches.length - 1];
  91. const startOfTerm = match[0] === '' ? 0 : (match.index || 0) + 1;
  92. const cursorOffset = query.slice(currentPosition).search(/\s|$/);
  93. const endOfTerm = currentPosition + (cursorOffset === -1 ? 0 : cursorOffset);
  94. return {
  95. startOfTerm,
  96. endOfTerm,
  97. prefix: query.substring(0, startOfTerm),
  98. term: query.substring(startOfTerm, endOfTerm),
  99. suffix: query.substring(endOfTerm),
  100. };
  101. }
  102. handleChange = (event: React.ChangeEvent<HTMLInputElement>) => {
  103. const query = event.target.value.replace('\n', '');
  104. this.setState({query}, this.updateAutocompleteOptions);
  105. };
  106. handleClick = () => {
  107. this.updateAutocompleteOptions();
  108. };
  109. handleFocus = () => {
  110. this.setState({dropdownVisible: true});
  111. };
  112. handleBlur = () => {
  113. this.props.onUpdate(this.state.query);
  114. this.setState({dropdownVisible: false});
  115. };
  116. getSelection(selection: number): DropdownOption | null {
  117. const {dropdownOptionGroups} = this.state;
  118. for (const group of dropdownOptionGroups) {
  119. if (selection >= group.options.length) {
  120. selection -= group.options.length;
  121. continue;
  122. }
  123. return group.options[selection];
  124. }
  125. return null;
  126. }
  127. handleKeyDown = (event: React.KeyboardEvent<HTMLInputElement>) => {
  128. const {key} = event;
  129. const {options, hideFieldOptions} = this.props;
  130. const {activeSelection, partialTerm} = this.state;
  131. const startedSelection = activeSelection >= 0;
  132. // handle arrow navigation
  133. if (key === 'ArrowDown' || key === 'ArrowUp') {
  134. event.preventDefault();
  135. const newOptionGroups = makeOptions(options, partialTerm, hideFieldOptions);
  136. const flattenedOptions = newOptionGroups.map(group => group.options).flat();
  137. if (flattenedOptions.length === 0) {
  138. return;
  139. }
  140. let newSelection;
  141. if (!startedSelection) {
  142. newSelection = key === 'ArrowUp' ? flattenedOptions.length - 1 : 0;
  143. } else {
  144. newSelection =
  145. key === 'ArrowUp'
  146. ? (activeSelection - 1 + flattenedOptions.length) % flattenedOptions.length
  147. : (activeSelection + 1) % flattenedOptions.length;
  148. }
  149. // This is modifying the `active` value of the references so make sure to
  150. // use `newOptionGroups` at the end.
  151. flattenedOptions[newSelection].active = true;
  152. this.setState({
  153. activeSelection: newSelection,
  154. dropdownOptionGroups: newOptionGroups,
  155. });
  156. return;
  157. }
  158. // handle selection
  159. if (startedSelection && (key === 'Tab' || key === 'Enter')) {
  160. event.preventDefault();
  161. const selection = this.getSelection(activeSelection);
  162. if (selection) {
  163. this.handleSelect(selection);
  164. }
  165. return;
  166. }
  167. if (key === 'Enter') {
  168. this.blur();
  169. return;
  170. }
  171. };
  172. handleKeyUp = (event: React.KeyboardEvent<HTMLInputElement>) => {
  173. // Other keys are managed at handleKeyDown function
  174. if (event.key !== 'Escape') {
  175. return;
  176. }
  177. event.preventDefault();
  178. const {activeSelection} = this.state;
  179. const startedSelection = activeSelection >= 0;
  180. if (!startedSelection) {
  181. this.blur();
  182. return;
  183. }
  184. };
  185. handleSelect = (option: DropdownOption) => {
  186. const {prefix, suffix} = this.splitQuery();
  187. this.setState(
  188. {
  189. // make sure to insert a space after the autocompleted term
  190. query: `${prefix}${option.value} ${suffix}`,
  191. activeSelection: NONE_SELECTED,
  192. },
  193. () => {
  194. // updating the query will cause the input to lose focus
  195. // and make sure to move the cursor behind the space after
  196. // the end of the autocompleted term
  197. this.focus(prefix.length + option.value.length + 1);
  198. this.updateAutocompleteOptions();
  199. }
  200. );
  201. };
  202. updateAutocompleteOptions() {
  203. const {options, hideFieldOptions} = this.props;
  204. const {term} = this.splitQuery();
  205. const partialTerm = term || null;
  206. this.setState({
  207. dropdownOptionGroups: makeOptions(options, partialTerm, hideFieldOptions),
  208. partialTerm,
  209. });
  210. }
  211. render() {
  212. const {onUpdate: _onUpdate, options: _options, ...props} = this.props;
  213. const {dropdownVisible, dropdownOptionGroups} = this.state;
  214. return (
  215. <Container isOpen={dropdownVisible}>
  216. <Input
  217. {...props}
  218. ref={this.input}
  219. autoComplete="off"
  220. className="form-control"
  221. value={this.state.query}
  222. onClick={this.handleClick}
  223. onChange={this.handleChange}
  224. onBlur={this.handleBlur}
  225. onFocus={this.handleFocus}
  226. onKeyDown={this.handleKeyDown}
  227. spellCheck={false}
  228. />
  229. <TermDropdown
  230. isOpen={dropdownVisible}
  231. optionGroups={dropdownOptionGroups}
  232. handleSelect={this.handleSelect}
  233. />
  234. </Container>
  235. );
  236. }
  237. }
  238. const Container = styled('div')<{isOpen: boolean}>`
  239. background: ${p => p.theme.background};
  240. position: relative;
  241. border-radius: ${p =>
  242. p.isOpen
  243. ? `${p.theme.borderRadius} ${p.theme.borderRadius} 0 0`
  244. : p.theme.borderRadius};
  245. .show-sidebar & {
  246. background: ${p => p.theme.backgroundSecondary};
  247. }
  248. `;
  249. type TermDropdownProps = {
  250. handleSelect: (option: DropdownOption) => void;
  251. isOpen: boolean;
  252. optionGroups: DropdownOptionGroup[];
  253. };
  254. function TermDropdown({isOpen, optionGroups, handleSelect}: TermDropdownProps) {
  255. return (
  256. <DropdownContainer isOpen={isOpen}>
  257. {isOpen && (
  258. <DropdownItemsList>
  259. {optionGroups.map(group => {
  260. const {title, options} = group;
  261. return (
  262. <Fragment key={title}>
  263. <ListItem>
  264. <DropdownTitle>{title}</DropdownTitle>
  265. </ListItem>
  266. {options.map(option => {
  267. return (
  268. <DropdownListItem
  269. key={option.value}
  270. className={option.active ? 'active' : undefined}
  271. onClick={() => handleSelect(option)}
  272. // prevent the blur event on the input from firing
  273. onMouseDown={event => event.preventDefault()}
  274. // scroll into view if it is the active element
  275. ref={element =>
  276. option.active && element?.scrollIntoView?.({block: 'nearest'})
  277. }
  278. aria-label={option.value}
  279. >
  280. <DropdownItemTitleWrapper>{option.value}</DropdownItemTitleWrapper>
  281. </DropdownListItem>
  282. );
  283. })}
  284. {options.length === 0 && <Info>{t('No items found')}</Info>}
  285. </Fragment>
  286. );
  287. })}
  288. </DropdownItemsList>
  289. )}
  290. </DropdownContainer>
  291. );
  292. }
  293. function makeFieldOptions(
  294. columns: Column[],
  295. partialTerm: string | null
  296. ): DropdownOptionGroup {
  297. const fieldValues = new Set<string>();
  298. const options = columns
  299. .filter(({kind}) => kind !== 'equation')
  300. .filter(isLegalEquationColumn)
  301. .map(option => ({
  302. kind: 'field' as const,
  303. active: false,
  304. value: generateFieldAsString(option),
  305. }))
  306. .filter(({value}) => {
  307. if (fieldValues.has(value)) {
  308. return false;
  309. }
  310. fieldValues.add(value);
  311. return true;
  312. })
  313. .filter(({value}) => (partialTerm ? value.includes(partialTerm) : true));
  314. return {
  315. title: 'Fields',
  316. options,
  317. };
  318. }
  319. function makeOperatorOptions(partialTerm: string | null): DropdownOptionGroup {
  320. const options = ['+', '-', '*', '/', '(', ')']
  321. .filter(operator => (partialTerm ? operator.includes(partialTerm) : true))
  322. .map(operator => ({
  323. kind: 'operator' as const,
  324. active: false,
  325. value: operator,
  326. }));
  327. return {
  328. title: 'Operators',
  329. options,
  330. };
  331. }
  332. function makeOptions(
  333. columns: Column[],
  334. partialTerm: string | null,
  335. hideFieldOptions?: boolean
  336. ): DropdownOptionGroup[] {
  337. if (hideFieldOptions) {
  338. return [makeOperatorOptions(partialTerm)];
  339. }
  340. return [makeFieldOptions(columns, partialTerm), makeOperatorOptions(partialTerm)];
  341. }
  342. const DropdownContainer = styled('div')<{isOpen: boolean}>`
  343. /* Container has a border that we need to account for */
  344. display: ${p => (p.isOpen ? 'block' : 'none')};
  345. position: absolute;
  346. top: 100%;
  347. left: -1px;
  348. right: -1px;
  349. z-index: ${p => p.theme.zIndex.dropdown};
  350. background: ${p => p.theme.backgroundElevated};
  351. box-shadow: ${p => p.theme.dropShadowHeavy};
  352. border: 1px solid ${p => p.theme.border};
  353. border-radius: ${p => p.theme.borderRadius};
  354. margin-top: ${space(1)};
  355. max-height: 300px;
  356. overflow-y: auto;
  357. `;
  358. const DropdownItemsList = styled('ul')`
  359. padding-left: 0;
  360. list-style: none;
  361. margin-bottom: 0;
  362. `;
  363. const ListItem = styled('li')`
  364. &:not(:last-child) {
  365. border-bottom: 1px solid ${p => p.theme.innerBorder};
  366. }
  367. `;
  368. const DropdownTitle = styled('header')`
  369. display: flex;
  370. align-items: center;
  371. background-color: ${p => p.theme.backgroundSecondary};
  372. color: ${p => p.theme.gray300};
  373. font-weight: normal;
  374. font-size: ${p => p.theme.fontSizeMedium};
  375. margin: 0;
  376. padding: ${space(1)} ${space(2)};
  377. & > svg {
  378. margin-right: ${space(1)};
  379. }
  380. `;
  381. const DropdownListItem = styled(ListItem)`
  382. scroll-margin: 40px 0;
  383. font-size: ${p => p.theme.fontSizeLarge};
  384. padding: ${space(1)} ${space(2)};
  385. cursor: pointer;
  386. &:hover,
  387. &.active {
  388. background: ${p => p.theme.hover};
  389. }
  390. `;
  391. const DropdownItemTitleWrapper = styled('div')`
  392. color: ${p => p.theme.textColor};
  393. font-weight: normal;
  394. font-size: ${p => p.theme.fontSizeMedium};
  395. margin: 0;
  396. line-height: ${p => p.theme.text.lineHeightHeading};
  397. ${p => p.theme.overflowEllipsis};
  398. `;
  399. const Info = styled('div')`
  400. display: flex;
  401. padding: ${space(1)} ${space(2)};
  402. font-size: ${p => p.theme.fontSizeLarge};
  403. color: ${p => p.theme.gray300};
  404. &:not(:last-child) {
  405. border-bottom: 1px solid ${p => p.theme.innerBorder};
  406. }
  407. `;