QueryField.tsx 14 KB

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