QueryField.tsx 14 KB

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