QueryField.tsx 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496
  1. import _ from 'lodash';
  2. import React from 'react';
  3. import ReactDOM from 'react-dom';
  4. import { Change, Value } from 'slate';
  5. import { Editor } from 'slate-react';
  6. import Plain from 'slate-plain-serializer';
  7. import classnames from 'classnames';
  8. import { CompletionItem, CompletionItemGroup, TypeaheadOutput } from 'app/types/explore';
  9. import ClearPlugin from './slate-plugins/clear';
  10. import NewlinePlugin from './slate-plugins/newline';
  11. import Typeahead from './Typeahead';
  12. import { makeFragment, makeValue } from './Value';
  13. import PlaceholdersBuffer from './PlaceholdersBuffer';
  14. export const TYPEAHEAD_DEBOUNCE = 100;
  15. function getSuggestionByIndex(suggestions: CompletionItemGroup[], index: number): CompletionItem {
  16. // Flatten suggestion groups
  17. const flattenedSuggestions = suggestions.reduce((acc, g) => acc.concat(g.items), []);
  18. const correctedIndex = Math.max(index, 0) % flattenedSuggestions.length;
  19. return flattenedSuggestions[correctedIndex];
  20. }
  21. function hasSuggestions(suggestions: CompletionItemGroup[]): boolean {
  22. return suggestions && suggestions.length > 0;
  23. }
  24. export interface QueryFieldProps {
  25. additionalPlugins?: any[];
  26. cleanText?: (text: string) => string;
  27. disabled?: boolean;
  28. initialQuery: string | null;
  29. onBlur?: () => void;
  30. onFocus?: () => void;
  31. onTypeahead?: (typeahead: TypeaheadInput) => TypeaheadOutput;
  32. onValueChanged?: (value: string) => void;
  33. onWillApplySuggestion?: (suggestion: string, state: QueryFieldState) => string;
  34. placeholder?: string;
  35. portalOrigin?: string;
  36. syntax?: string;
  37. syntaxLoaded?: boolean;
  38. }
  39. export interface QueryFieldState {
  40. suggestions: CompletionItemGroup[];
  41. typeaheadContext: string | null;
  42. typeaheadIndex: number;
  43. typeaheadPrefix: string;
  44. typeaheadText: string;
  45. value: Value;
  46. }
  47. export interface TypeaheadInput {
  48. editorNode: Element;
  49. prefix: string;
  50. selection?: Selection;
  51. text: string;
  52. value: Value;
  53. wrapperNode: Element;
  54. }
  55. /**
  56. * Renders an editor field.
  57. * Pass initial value as initialQuery and listen to changes in props.onValueChanged.
  58. * This component can only process strings. Internally it uses Slate Value.
  59. * Implement props.onTypeahead to use suggestions, see PromQueryField.tsx as an example.
  60. */
  61. export class QueryField extends React.PureComponent<QueryFieldProps, QueryFieldState> {
  62. menuEl: HTMLElement | null;
  63. placeholdersBuffer: PlaceholdersBuffer;
  64. plugins: any[];
  65. resetTimer: any;
  66. mounted: boolean;
  67. constructor(props: QueryFieldProps, context) {
  68. super(props, context);
  69. this.placeholdersBuffer = new PlaceholdersBuffer(props.initialQuery || '');
  70. // Base plugins
  71. this.plugins = [ClearPlugin(), NewlinePlugin(), ...(props.additionalPlugins || [])].filter(p => p);
  72. this.state = {
  73. suggestions: [],
  74. typeaheadContext: null,
  75. typeaheadIndex: 0,
  76. typeaheadPrefix: '',
  77. typeaheadText: '',
  78. value: makeValue(this.placeholdersBuffer.toString(), props.syntax),
  79. };
  80. }
  81. componentDidMount() {
  82. this.mounted = true;
  83. this.updateMenu();
  84. }
  85. componentWillUnmount() {
  86. this.mounted = false;
  87. clearTimeout(this.resetTimer);
  88. }
  89. componentDidUpdate(prevProps: QueryFieldProps, prevState: QueryFieldState) {
  90. // Only update menu location when suggestion existence or text/selection changed
  91. if (
  92. this.state.value !== prevState.value ||
  93. hasSuggestions(this.state.suggestions) !== hasSuggestions(prevState.suggestions)
  94. ) {
  95. this.updateMenu();
  96. }
  97. }
  98. componentWillReceiveProps(nextProps: QueryFieldProps) {
  99. if (nextProps.syntaxLoaded && !this.props.syntaxLoaded) {
  100. // Need a bogus edit to re-render the editor after syntax has fully loaded
  101. const change = this.state.value
  102. .change()
  103. .insertText(' ')
  104. .deleteBackward();
  105. if (this.placeholdersBuffer.hasPlaceholders()) {
  106. change.move(this.placeholdersBuffer.getNextMoveOffset()).focus();
  107. }
  108. this.onChange(change);
  109. }
  110. }
  111. onChange = ({ value }) => {
  112. const textChanged = value.document !== this.state.value.document;
  113. // Control editor loop, then pass text change up to parent
  114. this.setState({ value }, () => {
  115. if (textChanged) {
  116. this.handleChangeValue();
  117. }
  118. });
  119. // Show suggest menu on text input
  120. if (textChanged && value.selection.isCollapsed) {
  121. // Need one paint to allow DOM-based typeahead rules to work
  122. window.requestAnimationFrame(this.handleTypeahead);
  123. } else if (!this.resetTimer) {
  124. this.resetTypeahead();
  125. }
  126. };
  127. handleChangeValue = () => {
  128. // Send text change to parent
  129. const { onValueChanged } = this.props;
  130. if (onValueChanged) {
  131. onValueChanged(Plain.serialize(this.state.value));
  132. }
  133. };
  134. handleTypeahead = _.debounce(async () => {
  135. const selection = window.getSelection();
  136. const { cleanText, onTypeahead } = this.props;
  137. const { value } = this.state;
  138. if (onTypeahead && selection.anchorNode) {
  139. const wrapperNode = selection.anchorNode.parentElement;
  140. const editorNode = wrapperNode.closest('.slate-query-field');
  141. if (!editorNode || this.state.value.isBlurred) {
  142. // Not inside this editor
  143. return;
  144. }
  145. const range = selection.getRangeAt(0);
  146. const offset = range.startOffset;
  147. const text = selection.anchorNode.textContent;
  148. let prefix = text.substr(0, offset);
  149. // Label values could have valid characters erased if `cleanText()` is
  150. // blindly applied, which would undesirably interfere with suggestions
  151. const labelValueMatch = prefix.match(/(?:!?=~?"?|")(.*)/);
  152. if (labelValueMatch) {
  153. prefix = labelValueMatch[1];
  154. } else if (cleanText) {
  155. prefix = cleanText(prefix);
  156. }
  157. const { suggestions, context, refresher } = onTypeahead({
  158. editorNode,
  159. prefix,
  160. selection,
  161. text,
  162. value,
  163. wrapperNode,
  164. });
  165. let filteredSuggestions = suggestions
  166. .map(group => {
  167. if (group.items) {
  168. if (prefix) {
  169. // Filter groups based on prefix
  170. if (!group.skipFilter) {
  171. group.items = group.items.filter(c => (c.filterText || c.label).length >= prefix.length);
  172. if (group.prefixMatch) {
  173. group.items = group.items.filter(c => (c.filterText || c.label).indexOf(prefix) === 0);
  174. } else {
  175. group.items = group.items.filter(c => (c.filterText || c.label).indexOf(prefix) > -1);
  176. }
  177. }
  178. // Filter out the already typed value (prefix) unless it inserts custom text
  179. group.items = group.items.filter(c => c.insertText || (c.filterText || c.label) !== prefix);
  180. }
  181. if (!group.skipSort) {
  182. group.items = _.sortBy(group.items, item => item.sortText || item.label);
  183. }
  184. }
  185. return group;
  186. })
  187. .filter(group => group.items && group.items.length > 0); // Filter out empty groups
  188. // Keep same object for equality checking later
  189. if (_.isEqual(filteredSuggestions, this.state.suggestions)) {
  190. filteredSuggestions = this.state.suggestions;
  191. }
  192. this.setState(
  193. {
  194. suggestions: filteredSuggestions,
  195. typeaheadPrefix: prefix,
  196. typeaheadContext: context,
  197. typeaheadText: text,
  198. },
  199. () => {
  200. if (refresher) {
  201. refresher.then(this.handleTypeahead).catch(e => console.error(e));
  202. }
  203. }
  204. );
  205. }
  206. }, TYPEAHEAD_DEBOUNCE);
  207. applyTypeahead(change: Change, suggestion: CompletionItem): Change {
  208. const { cleanText, onWillApplySuggestion, syntax } = this.props;
  209. const { typeaheadPrefix, typeaheadText } = this.state;
  210. let suggestionText = suggestion.insertText || suggestion.label;
  211. const preserveSuffix = suggestion.kind === 'function';
  212. const move = suggestion.move || 0;
  213. if (onWillApplySuggestion) {
  214. suggestionText = onWillApplySuggestion(suggestionText, { ...this.state });
  215. }
  216. this.resetTypeahead();
  217. // Remove the current, incomplete text and replace it with the selected suggestion
  218. const backward = suggestion.deleteBackwards || typeaheadPrefix.length;
  219. const text = cleanText ? cleanText(typeaheadText) : typeaheadText;
  220. const suffixLength = text.length - typeaheadPrefix.length;
  221. const offset = typeaheadText.indexOf(typeaheadPrefix);
  222. const midWord = typeaheadPrefix && ((suffixLength > 0 && offset > -1) || suggestionText === typeaheadText);
  223. const forward = midWord && !preserveSuffix ? suffixLength + offset : 0;
  224. // If new-lines, apply suggestion as block
  225. if (suggestionText.match(/\n/)) {
  226. const fragment = makeFragment(suggestionText, syntax);
  227. return change
  228. .deleteBackward(backward)
  229. .deleteForward(forward)
  230. .insertFragment(fragment)
  231. .focus();
  232. }
  233. return change
  234. .deleteBackward(backward)
  235. .deleteForward(forward)
  236. .insertText(suggestionText)
  237. .move(move)
  238. .focus();
  239. }
  240. onKeyDown = (event, change) => {
  241. const { typeaheadIndex, suggestions } = this.state;
  242. switch (event.key) {
  243. case 'Escape': {
  244. if (this.menuEl) {
  245. event.preventDefault();
  246. event.stopPropagation();
  247. this.resetTypeahead();
  248. return true;
  249. }
  250. break;
  251. }
  252. case ' ': {
  253. if (event.ctrlKey) {
  254. event.preventDefault();
  255. this.handleTypeahead();
  256. return true;
  257. }
  258. break;
  259. }
  260. case 'Enter':
  261. case 'Tab': {
  262. if (this.menuEl) {
  263. // Dont blur input
  264. event.preventDefault();
  265. if (!suggestions || suggestions.length === 0) {
  266. return undefined;
  267. }
  268. const suggestion = getSuggestionByIndex(suggestions, typeaheadIndex);
  269. const nextChange = this.applyTypeahead(change, suggestion);
  270. const insertTextOperation = nextChange.operations.find(operation => operation.type === 'insert_text');
  271. if (insertTextOperation) {
  272. const suggestionText = insertTextOperation.text;
  273. this.placeholdersBuffer.setNextPlaceholderValue(suggestionText);
  274. if (this.placeholdersBuffer.hasPlaceholders()) {
  275. nextChange.move(this.placeholdersBuffer.getNextMoveOffset()).focus();
  276. }
  277. }
  278. return true;
  279. }
  280. break;
  281. }
  282. case 'ArrowDown': {
  283. if (this.menuEl) {
  284. // Select next suggestion
  285. event.preventDefault();
  286. this.setState({ typeaheadIndex: typeaheadIndex + 1 });
  287. }
  288. break;
  289. }
  290. case 'ArrowUp': {
  291. if (this.menuEl) {
  292. // Select previous suggestion
  293. event.preventDefault();
  294. this.setState({ typeaheadIndex: Math.max(0, typeaheadIndex - 1) });
  295. }
  296. break;
  297. }
  298. default: {
  299. // console.log('default key', event.key, event.which, event.charCode, event.locale, data.key);
  300. break;
  301. }
  302. }
  303. return undefined;
  304. };
  305. resetTypeahead = () => {
  306. if (this.mounted) {
  307. this.setState({
  308. suggestions: [],
  309. typeaheadIndex: 0,
  310. typeaheadPrefix: '',
  311. typeaheadContext: null,
  312. });
  313. this.resetTimer = null;
  314. }
  315. };
  316. handleBlur = () => {
  317. const { onBlur } = this.props;
  318. // If we dont wait here, menu clicks wont work because the menu
  319. // will be gone.
  320. this.resetTimer = setTimeout(this.resetTypeahead, 100);
  321. // Disrupting placeholder entry wipes all remaining placeholders needing input
  322. this.placeholdersBuffer.clearPlaceholders();
  323. if (onBlur) {
  324. onBlur();
  325. }
  326. };
  327. handleFocus = () => {
  328. const { onFocus } = this.props;
  329. if (onFocus) {
  330. onFocus();
  331. }
  332. };
  333. onClickMenu = (item: CompletionItem) => {
  334. // Manually triggering change
  335. const change = this.applyTypeahead(this.state.value.change(), item);
  336. this.onChange(change);
  337. };
  338. updateMenu = () => {
  339. const { suggestions } = this.state;
  340. const menu = this.menuEl;
  341. const selection = window.getSelection();
  342. const node = selection.anchorNode;
  343. // No menu, nothing to do
  344. if (!menu) {
  345. return;
  346. }
  347. // No suggestions or blur, remove menu
  348. if (!hasSuggestions(suggestions)) {
  349. menu.removeAttribute('style');
  350. return;
  351. }
  352. // Align menu overlay to editor node
  353. if (node) {
  354. // Read from DOM
  355. const rect = node.parentElement.getBoundingClientRect();
  356. const scrollX = window.scrollX;
  357. const scrollY = window.scrollY;
  358. // Write DOM
  359. requestAnimationFrame(() => {
  360. menu.style.opacity = '1';
  361. menu.style.top = `${rect.top + scrollY + rect.height + 4}px`;
  362. menu.style.left = `${rect.left + scrollX - 2}px`;
  363. });
  364. }
  365. };
  366. menuRef = el => {
  367. this.menuEl = el;
  368. };
  369. renderMenu = () => {
  370. const { portalOrigin } = this.props;
  371. const { suggestions, typeaheadIndex, typeaheadPrefix } = this.state;
  372. if (!hasSuggestions(suggestions)) {
  373. return null;
  374. }
  375. const selectedItem = getSuggestionByIndex(suggestions, typeaheadIndex);
  376. // Create typeahead in DOM root so we can later position it absolutely
  377. return (
  378. <Portal origin={portalOrigin}>
  379. <Typeahead
  380. menuRef={this.menuRef}
  381. selectedItem={selectedItem}
  382. onClickItem={this.onClickMenu}
  383. prefix={typeaheadPrefix}
  384. groupedItems={suggestions}
  385. />
  386. </Portal>
  387. );
  388. };
  389. render() {
  390. const { disabled } = this.props;
  391. const wrapperClassName = classnames('slate-query-field__wrapper', {
  392. 'slate-query-field__wrapper--disabled': disabled,
  393. });
  394. return (
  395. <div className={wrapperClassName}>
  396. <div className="slate-query-field">
  397. {this.renderMenu()}
  398. <Editor
  399. autoCorrect={false}
  400. readOnly={this.props.disabled}
  401. onBlur={this.handleBlur}
  402. onKeyDown={this.onKeyDown}
  403. onChange={this.onChange}
  404. onFocus={this.handleFocus}
  405. placeholder={this.props.placeholder}
  406. plugins={this.plugins}
  407. spellCheck={false}
  408. value={this.state.value}
  409. />
  410. </div>
  411. </div>
  412. );
  413. }
  414. }
  415. class Portal extends React.PureComponent<{ index?: number; origin: string }, {}> {
  416. node: HTMLElement;
  417. constructor(props) {
  418. super(props);
  419. const { index = 0, origin = 'query' } = props;
  420. this.node = document.createElement('div');
  421. this.node.classList.add(`slate-typeahead`, `slate-typeahead-${origin}-${index}`);
  422. document.body.appendChild(this.node);
  423. }
  424. componentWillUnmount() {
  425. document.body.removeChild(this.node);
  426. }
  427. render() {
  428. return ReactDOM.createPortal(this.props.children, this.node);
  429. }
  430. }
  431. export default QueryField;