QueryField.tsx 14 KB

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