QueryField.tsx 15 KB

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