QueryField.tsx 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478
  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 QueryFieldProps {
  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: QueryFieldState) => string;
  32. placeholder?: string;
  33. portalOrigin?: string;
  34. syntax?: string;
  35. syntaxLoaded?: boolean;
  36. }
  37. export interface QueryFieldState {
  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. export class QueryField extends React.PureComponent<QueryFieldProps, QueryFieldState> {
  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].filter(p => p);
  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: QueryFieldProps) {
  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 preserveSuffix = suggestion.kind === 'function';
  201. const move = suggestion.move || 0;
  202. if (onWillApplySuggestion) {
  203. suggestionText = onWillApplySuggestion(suggestionText, { ...this.state });
  204. }
  205. this.resetTypeahead();
  206. // Remove the current, incomplete text and replace it with the selected suggestion
  207. const backward = suggestion.deleteBackwards || typeaheadPrefix.length;
  208. const text = cleanText ? cleanText(typeaheadText) : typeaheadText;
  209. const suffixLength = text.length - typeaheadPrefix.length;
  210. const offset = typeaheadText.indexOf(typeaheadPrefix);
  211. const midWord = typeaheadPrefix && ((suffixLength > 0 && offset > -1) || suggestionText === typeaheadText);
  212. const forward = midWord && !preserveSuffix ? suffixLength + offset : 0;
  213. // If new-lines, apply suggestion as block
  214. if (suggestionText.match(/\n/)) {
  215. const fragment = makeFragment(suggestionText, syntax);
  216. return change
  217. .deleteBackward(backward)
  218. .deleteForward(forward)
  219. .insertFragment(fragment)
  220. .focus();
  221. }
  222. return change
  223. .deleteBackward(backward)
  224. .deleteForward(forward)
  225. .insertText(suggestionText)
  226. .move(move)
  227. .focus();
  228. }
  229. onKeyDown = (event, change) => {
  230. const { typeaheadIndex, suggestions } = this.state;
  231. switch (event.key) {
  232. case 'Escape': {
  233. if (this.menuEl) {
  234. event.preventDefault();
  235. event.stopPropagation();
  236. this.resetTypeahead();
  237. return true;
  238. }
  239. break;
  240. }
  241. case ' ': {
  242. if (event.ctrlKey) {
  243. event.preventDefault();
  244. this.handleTypeahead();
  245. return true;
  246. }
  247. break;
  248. }
  249. case 'Enter':
  250. case 'Tab': {
  251. if (this.menuEl) {
  252. // Dont blur input
  253. event.preventDefault();
  254. if (!suggestions || suggestions.length === 0) {
  255. return undefined;
  256. }
  257. const suggestion = getSuggestionByIndex(suggestions, typeaheadIndex);
  258. const nextChange = this.applyTypeahead(change, suggestion);
  259. const insertTextOperation = nextChange.operations.find(operation => operation.type === 'insert_text');
  260. if (insertTextOperation) {
  261. const suggestionText = insertTextOperation.text;
  262. this.placeholdersBuffer.setNextPlaceholderValue(suggestionText);
  263. if (this.placeholdersBuffer.hasPlaceholders()) {
  264. nextChange.move(this.placeholdersBuffer.getNextMoveOffset()).focus();
  265. }
  266. }
  267. return true;
  268. }
  269. break;
  270. }
  271. case 'ArrowDown': {
  272. if (this.menuEl) {
  273. // Select next suggestion
  274. event.preventDefault();
  275. this.setState({ typeaheadIndex: typeaheadIndex + 1 });
  276. }
  277. break;
  278. }
  279. case 'ArrowUp': {
  280. if (this.menuEl) {
  281. // Select previous suggestion
  282. event.preventDefault();
  283. this.setState({ typeaheadIndex: Math.max(0, typeaheadIndex - 1) });
  284. }
  285. break;
  286. }
  287. default: {
  288. // console.log('default key', event.key, event.which, event.charCode, event.locale, data.key);
  289. break;
  290. }
  291. }
  292. return undefined;
  293. };
  294. resetTypeahead = () => {
  295. this.setState({
  296. suggestions: [],
  297. typeaheadIndex: 0,
  298. typeaheadPrefix: '',
  299. typeaheadContext: null,
  300. });
  301. this.resetTimer = null;
  302. };
  303. handleBlur = () => {
  304. const { onBlur } = this.props;
  305. // If we dont wait here, menu clicks wont work because the menu
  306. // will be gone.
  307. this.resetTimer = setTimeout(this.resetTypeahead, 100);
  308. // Disrupting placeholder entry wipes all remaining placeholders needing input
  309. this.placeholdersBuffer.clearPlaceholders();
  310. if (onBlur) {
  311. onBlur();
  312. }
  313. };
  314. handleFocus = () => {
  315. const { onFocus } = this.props;
  316. if (onFocus) {
  317. onFocus();
  318. }
  319. };
  320. onClickMenu = (item: CompletionItem) => {
  321. // Manually triggering change
  322. const change = this.applyTypeahead(this.state.value.change(), item);
  323. this.onChange(change);
  324. };
  325. updateMenu = () => {
  326. const { suggestions } = this.state;
  327. const menu = this.menuEl;
  328. const selection = window.getSelection();
  329. const node = selection.anchorNode;
  330. // No menu, nothing to do
  331. if (!menu) {
  332. return;
  333. }
  334. // No suggestions or blur, remove menu
  335. if (!hasSuggestions(suggestions)) {
  336. menu.removeAttribute('style');
  337. return;
  338. }
  339. // Align menu overlay to editor node
  340. if (node) {
  341. // Read from DOM
  342. const rect = node.parentElement.getBoundingClientRect();
  343. const scrollX = window.scrollX;
  344. const scrollY = window.scrollY;
  345. // Write DOM
  346. requestAnimationFrame(() => {
  347. menu.style.opacity = '1';
  348. menu.style.top = `${rect.top + scrollY + rect.height + 4}px`;
  349. menu.style.left = `${rect.left + scrollX - 2}px`;
  350. });
  351. }
  352. };
  353. menuRef = el => {
  354. this.menuEl = el;
  355. };
  356. renderMenu = () => {
  357. const { portalOrigin } = this.props;
  358. const { suggestions, typeaheadIndex, typeaheadPrefix } = this.state;
  359. if (!hasSuggestions(suggestions)) {
  360. return null;
  361. }
  362. const selectedItem = getSuggestionByIndex(suggestions, typeaheadIndex);
  363. // Create typeahead in DOM root so we can later position it absolutely
  364. return (
  365. <Portal origin={portalOrigin}>
  366. <Typeahead
  367. menuRef={this.menuRef}
  368. selectedItem={selectedItem}
  369. onClickItem={this.onClickMenu}
  370. prefix={typeaheadPrefix}
  371. groupedItems={suggestions}
  372. />
  373. </Portal>
  374. );
  375. };
  376. render() {
  377. return (
  378. <div className="slate-query-field-wrapper">
  379. <div className="slate-query-field">
  380. {this.renderMenu()}
  381. <Editor
  382. autoCorrect={false}
  383. onBlur={this.handleBlur}
  384. onKeyDown={this.onKeyDown}
  385. onChange={this.onChange}
  386. onFocus={this.handleFocus}
  387. placeholder={this.props.placeholder}
  388. plugins={this.plugins}
  389. spellCheck={false}
  390. value={this.state.value}
  391. />
  392. </div>
  393. </div>
  394. );
  395. }
  396. }
  397. class Portal extends React.PureComponent<{ index?: number; origin: string }, {}> {
  398. node: HTMLElement;
  399. constructor(props) {
  400. super(props);
  401. const { index = 0, origin = 'query' } = props;
  402. this.node = document.createElement('div');
  403. this.node.classList.add(`slate-typeahead`, `slate-typeahead-${origin}-${index}`);
  404. document.body.appendChild(this.node);
  405. }
  406. componentWillUnmount() {
  407. document.body.removeChild(this.node);
  408. }
  409. render() {
  410. return ReactDOM.createPortal(this.props.children, this.node);
  411. }
  412. }
  413. export default QueryField;