QueryField.tsx 13 KB

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