arithmeticInput.tsx 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483
  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. if (key === 'ArrowLeft' || key === 'ArrowRight') {
  172. this.updateAutocompleteOptions();
  173. }
  174. };
  175. handleKeyUp = (event: React.KeyboardEvent<HTMLInputElement>) => {
  176. // Other keys are managed at handleKeyDown function
  177. if (event.key !== 'Escape') {
  178. return;
  179. }
  180. event.preventDefault();
  181. const {activeSelection} = this.state;
  182. const startedSelection = activeSelection >= 0;
  183. if (!startedSelection) {
  184. this.blur();
  185. return;
  186. }
  187. };
  188. handleSelect = (option: DropdownOption) => {
  189. const {prefix, suffix} = this.splitQuery();
  190. this.setState(
  191. {
  192. // make sure to insert a space after the autocompleted term
  193. query: `${prefix}${option.value} ${suffix}`,
  194. activeSelection: NONE_SELECTED,
  195. },
  196. () => {
  197. // updating the query will cause the input to lose focus
  198. // and make sure to move the cursor behind the space after
  199. // the end of the autocompleted term
  200. this.focus(prefix.length + option.value.length + 1);
  201. this.updateAutocompleteOptions();
  202. }
  203. );
  204. };
  205. updateAutocompleteOptions() {
  206. const {options, hideFieldOptions} = this.props;
  207. const {term} = this.splitQuery();
  208. const partialTerm = term || null;
  209. this.setState({
  210. dropdownOptionGroups: makeOptions(options, partialTerm, hideFieldOptions),
  211. partialTerm,
  212. });
  213. }
  214. render() {
  215. const {onUpdate: _onUpdate, options: _options, ...props} = this.props;
  216. const {dropdownVisible, dropdownOptionGroups} = this.state;
  217. return (
  218. <Container isOpen={dropdownVisible}>
  219. <Input
  220. {...props}
  221. ref={this.input}
  222. autoComplete="off"
  223. className="form-control"
  224. value={this.state.query}
  225. onClick={this.handleClick}
  226. onChange={this.handleChange}
  227. onBlur={this.handleBlur}
  228. onFocus={this.handleFocus}
  229. onKeyDown={this.handleKeyDown}
  230. spellCheck={false}
  231. />
  232. <TermDropdown
  233. isOpen={dropdownVisible}
  234. optionGroups={dropdownOptionGroups}
  235. handleSelect={this.handleSelect}
  236. />
  237. </Container>
  238. );
  239. }
  240. }
  241. const Container = styled('div')<{isOpen: boolean}>`
  242. background: ${p => p.theme.background};
  243. position: relative;
  244. border-radius: ${p =>
  245. p.isOpen
  246. ? `${p.theme.borderRadius} ${p.theme.borderRadius} 0 0`
  247. : p.theme.borderRadius};
  248. .show-sidebar & {
  249. background: ${p => p.theme.backgroundSecondary};
  250. }
  251. `;
  252. type TermDropdownProps = {
  253. handleSelect: (option: DropdownOption) => void;
  254. isOpen: boolean;
  255. optionGroups: DropdownOptionGroup[];
  256. };
  257. function TermDropdown({isOpen, optionGroups, handleSelect}: TermDropdownProps) {
  258. return (
  259. <DropdownContainer isOpen={isOpen}>
  260. {isOpen && (
  261. <DropdownItemsList>
  262. {optionGroups.map(group => {
  263. const {title, options} = group;
  264. return (
  265. <Fragment key={title}>
  266. <ListItem>
  267. <DropdownTitle>{title}</DropdownTitle>
  268. </ListItem>
  269. {options.map(option => {
  270. return (
  271. <DropdownListItem
  272. key={option.value}
  273. className={option.active ? 'active' : undefined}
  274. onClick={() => handleSelect(option)}
  275. // prevent the blur event on the input from firing
  276. onMouseDown={event => event.preventDefault()}
  277. // scroll into view if it is the active element
  278. ref={element =>
  279. option.active && element?.scrollIntoView?.({block: 'nearest'})
  280. }
  281. aria-label={option.value}
  282. >
  283. <DropdownItemTitleWrapper>{option.value}</DropdownItemTitleWrapper>
  284. </DropdownListItem>
  285. );
  286. })}
  287. {options.length === 0 && <Info>{t('No items found')}</Info>}
  288. </Fragment>
  289. );
  290. })}
  291. </DropdownItemsList>
  292. )}
  293. </DropdownContainer>
  294. );
  295. }
  296. function makeFieldOptions(
  297. columns: Column[],
  298. partialTerm: string | null
  299. ): DropdownOptionGroup {
  300. const fieldValues = new Set<string>();
  301. const options = columns
  302. .filter(({kind}) => kind !== 'equation')
  303. .filter(isLegalEquationColumn)
  304. .map(option => ({
  305. kind: 'field' as const,
  306. active: false,
  307. value: generateFieldAsString(option),
  308. }))
  309. .filter(({value}) => {
  310. if (fieldValues.has(value)) {
  311. return false;
  312. }
  313. fieldValues.add(value);
  314. return true;
  315. })
  316. .filter(({value}) => (partialTerm ? value.includes(partialTerm) : true));
  317. return {
  318. title: 'Fields',
  319. options,
  320. };
  321. }
  322. function makeOperatorOptions(partialTerm: string | null): DropdownOptionGroup {
  323. const options = ['+', '-', '*', '/', '(', ')']
  324. .filter(operator => (partialTerm ? operator.includes(partialTerm) : true))
  325. .map(operator => ({
  326. kind: 'operator' as const,
  327. active: false,
  328. value: operator,
  329. }));
  330. return {
  331. title: 'Operators',
  332. options,
  333. };
  334. }
  335. function makeOptions(
  336. columns: Column[],
  337. partialTerm: string | null,
  338. hideFieldOptions?: boolean
  339. ): DropdownOptionGroup[] {
  340. if (hideFieldOptions) {
  341. return [makeOperatorOptions(partialTerm)];
  342. }
  343. return [makeFieldOptions(columns, partialTerm), makeOperatorOptions(partialTerm)];
  344. }
  345. const DropdownContainer = styled('div')<{isOpen: boolean}>`
  346. /* Container has a border that we need to account for */
  347. display: ${p => (p.isOpen ? 'block' : 'none')};
  348. position: absolute;
  349. top: 100%;
  350. left: -1px;
  351. right: -1px;
  352. z-index: ${p => p.theme.zIndex.dropdown};
  353. background: ${p => p.theme.backgroundElevated};
  354. box-shadow: ${p => p.theme.dropShadowHeavy};
  355. border: 1px solid ${p => p.theme.border};
  356. border-radius: ${p => p.theme.borderRadius};
  357. margin-top: ${space(1)};
  358. max-height: 300px;
  359. overflow-y: auto;
  360. `;
  361. const DropdownItemsList = styled('ul')`
  362. padding-left: 0;
  363. list-style: none;
  364. margin-bottom: 0;
  365. `;
  366. const ListItem = styled('li')`
  367. &:not(:last-child) {
  368. border-bottom: 1px solid ${p => p.theme.innerBorder};
  369. }
  370. `;
  371. const DropdownTitle = styled('header')`
  372. display: flex;
  373. align-items: center;
  374. background-color: ${p => p.theme.backgroundSecondary};
  375. color: ${p => p.theme.gray300};
  376. font-weight: normal;
  377. font-size: ${p => p.theme.fontSizeMedium};
  378. margin: 0;
  379. padding: ${space(1)} ${space(2)};
  380. & > svg {
  381. margin-right: ${space(1)};
  382. }
  383. `;
  384. const DropdownListItem = styled(ListItem)`
  385. scroll-margin: 40px 0;
  386. font-size: ${p => p.theme.fontSizeLarge};
  387. padding: ${space(1)} ${space(2)};
  388. cursor: pointer;
  389. &:hover,
  390. &.active {
  391. background: ${p => p.theme.hover};
  392. }
  393. `;
  394. const DropdownItemTitleWrapper = styled('div')`
  395. color: ${p => p.theme.textColor};
  396. font-weight: normal;
  397. font-size: ${p => p.theme.fontSizeMedium};
  398. margin: 0;
  399. line-height: ${p => p.theme.text.lineHeightHeading};
  400. ${p => p.theme.overflowEllipsis};
  401. `;
  402. const Info = styled('div')`
  403. display: flex;
  404. padding: ${space(1)} ${space(2)};
  405. font-size: ${p => p.theme.fontSizeLarge};
  406. color: ${p => p.theme.gray300};
  407. &:not(:last-child) {
  408. border-bottom: 1px solid ${p => p.theme.innerBorder};
  409. }
  410. `;